X

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.

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.

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!

Liked this post? Empower your friends by sharing it!
Categories: C#

View Comments (6)

Related Post