Monday, January 5, 2009

Partial classes in .Net Framework 2.0

Partial Classes


Today we shall see a new feature “Partial Classes” which was added to .Net 2.0

As the name suggests this allows us to create a part of a class in one file and the rest in another file. There is no restriction to the number of files which we use to code a single class. While declaring a partial class the keyword “partial” should be mentioned in all the files.



Let us see an example of how to declare a partial class.


File1.cs

public partial class MyClass

{

public MyClass()

{

//Constructor code goes here.

}

}

File2.cs

public partial class MyClass

{

//Methods and other implementation code goes here.

}


On compilation the C# compiler automatically detects parts of the partial classes in various files and builds them into a common assembly file.


Practical uses of Partial Classes


  • Split the class when the implementation code is very big, exceeding 1000 lines.
  • Place the properties, variables & constants in one class and the actual implementation in another file.
  • Use a different file for machine generated file and a different one for manual code, this improves readability and avoids the risk of changing the machine generated code by mistake.
  • In general source code is placed in a “Source Safe” environment like VSS or Clear Case, which allows only one person to modify a particular file at any given point in time. When the class file is very large and if different developers need to work on different methods of the class then we can split the class into multiple partial classes and the developers can work on the file which contains their methods.
  • Apart from classes the “partial” concept can also be applied to Interfaces and Structure definition.

While splitting the class into multiple parts we can make one part appear as the key file (usually the file with the implementation) and the other files to appear as its supporting files in the VS.Net editor. To do this we will have to make a few modifications to the project file (.csproj)


MyClass

File2.cs

MyClass



After modifying the project file as above, the solution explorer will display “File2.cs” as a main file and the file “File1.cs” will appear as a supporting file as a child node under “File2.cs”


File2.cs

| File1.cs


Thus partial classes allow us to split the content of a single class into multiple files and VS.Net allows us to organize the files based on priorities.

Search Flipkart Products:
Flipkart.com

No comments: