C# and Partial Classes

.Net 2.0 provided us with new feature called partial classes. Using partial classes we can use multiple files to keep the code of same class. Yes – we can put some methods to one file and the others to another file. Although partial classes may be extremely useful they can be also used to ruin system’s technical design if developers don’t know what happens behind the compiler.

Visual Studio uses partial classes to keep Windows and Web forms automatically generated code separately of user written code behind the forms.

Let’s see one very simple partial class that has two methods. The parts of this class can be also defined in same file if needed.

If we try to call methods of this class we can see something like this on screen.

Partial class methods

As we can see, IntelliSense doesn’t say a thing about separation of these methods. You can see hint of extension methods if you check out one of my previuos entries Extension methods – how they look like after compiling.

Let’s compile this code now and let’s see what has compiler done. Here is the class shown in Reflector.

Partial class in Reflector

As we can see there is no separation of methods after compiling – all parts are compiled together and we can see it as one class. No separation anymore!

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    6 thoughts on “C# and Partial Classes

    • June 11, 2008 at 12:26 am
      Permalink

      I’m not a fan of partial classes or methods, the only use they have is providing a cleaner way to extend/modify designer generated code.

    • July 10, 2008 at 12:59 pm
      Permalink

      how to use the partial classes in web applications.

    • July 10, 2008 at 12:59 pm
      Permalink

      how to use the partial classes in web applications.

    • October 9, 2010 at 9:11 am
      Permalink

      it really very nice.

    • December 12, 2010 at 5:59 pm
      Permalink

      It is really Good example

    • March 14, 2012 at 3:46 pm
      Permalink

      so if one method takes 16 bytes and other one takes 16 bytes, then will the partial class will have 32 bytes of memory

    Leave a Reply

    Your email address will not be published. Required fields are marked *