Friday, October 26, 2007

Finally...a use for .NET partial classes

When .NET 2.0 was released, partial classes was recognized as one of the top four cool new features (along with generics, anonymous methods, and iterators). After developing with 2.0 for some time now, I haven’t found a good reason to use partial classes (besides the Page class in ASP.NET that is created for you automatically). I do however recognize its importance for Visual Studio 2005 and how the auto-generated code and our own Page classes are created. Besides that, I just haven’t ran into a situation where I really needed it.

Recently I wrote some code where I stood up and cheered partial classes. If you ever used the .NET xsd.exe utility in .NET 1.1 to create a strong-typed class for an XSD file, you know that the tool created this handy set of classes for you to access the elements of an XML file. This was a good thing, but I would always end up writing several separate utility classes to provide a layer on top of, or along side of, the auto-generated class from xsd.exe. Although tempted at times, I couldn’t modify the auto-generated class file since I might regenerate it at a later time (I always did).

Much to my glee, xsd.exe in .NET 2.0 now creates partial classes! This now allows me to write separate class files and add properties and methods to the auto-generated ones from xsd.exe. This provides a nice separation/coupling from the xsd.exe generated code. Excellent!

I see a pattern here…for things that auto-generate code, partial classes are a welcome addition to .NET.

No comments:

Can't RDP? How to enable / disable virtual machine firewall for Azure VM

Oh no!  I accidentally blocked the RDP port on an Azure virtual machine which resulted in not being able to log into the VM anymore.  I did ...