The Partial Class

When .NET 2.0 hit the streets I never paid much attention to the partial class, the concept being that you can define a class over multiple source locations. For example I could have a source file with the following definition of MyDog:

public partial class MyDog
{
	public MyDog(int eyes)
	{
		Eyes = eyes;
	}

	private int Eyes;

	public int NumberofEyes
	{
		get { return Eyes; }
		set { Eyes = value; }
	}
}

... then within another source file complete the definition of MyDog as follows (within the same namespace of course).

public partial class MyDog
{
	public string Vocalize()
	{
		return string.Empty;
	}
}

For all intents and purposes this is the same as just creating one big "public class MyDog", you intellisense features are none the wiser and ILDASM does not appear to be able to discern the difference either.

image 

I had overlooked the features of the partial class, up until now, because I could not envision why I would need to spread a class over multiple source files. Surely spreading the definition of a class over multiple files was a singular waste of time ... except when you have automatic source file generation.

Fast forward to LINQ to SQL when it suddenly became trendy to allow Visual Studio to define your database connections and you will see that the auto generated files are replete with partial class definitions. This allows us, the humble LINQ to SQL consumer, to modify the auto generated class without actually modifying the source file in which it was so carefully created ... now *that* makes all the sense in the world!

Technorati tags: ,


Comment Section

Comments are closed.