Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
 
 
DZone MVB

Links

Social

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.


public partial class PartialClass
{
    public void MethodA()
    {
        Console.WriteLine("I am A!");
    }
}

public partial class PartialClass
{
    public void MethodB()
    {
        Console.WriteLine("I am B!");
    }
}


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

Methods of partial class

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-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!

This is also prove to multi-tier arcitecture example I gave in entry titled as Behind the Compiler.

Comments

My Favourite Links (06/07/2008) | .Net said:

Pingback from  My Favourite Links (06/07/2008)   | .Net

# June 8, 2008 1:07 AM

Granville Barnett said:

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.

# June 10, 2008 6:26 PM

NJ said:

how to use the partial classes in web applications.

Can somebody give me any example of _Default.aspx.cs.How to create partial class for it.

# July 10, 2008 6:59 AM

naga said:

nice

# July 9, 2009 2:47 AM

sbr said:

It is good

# January 6, 2010 5:41 AM

jayesh said:

it really very nice.

# October 9, 2010 3:11 AM

nagaraju said:

It is really Good example

# December 12, 2010 11:59 AM

Khuda Bux Mari Baloch said:

Very nice

# March 9, 2011 1:26 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)