7.9.08

Partial Classes with C#.NET

Partial Classes:
It is possible to split definition of classes, interfaces and structures over more than one files.some Features of partial classes are
  • More than one developer can simultaneously write the code for the class.
  • You can easily write your code (for extended functionality) for a VS.NET generated class. This will allow you to write the code of your own need without messing with the system generated code.

Things that you should be careful about when writing code for partial classes:

  • All the partial definitions must preceede with the key word "Partial".
  • All the partial types meant to be the part of same type must be defined within a same assembly and module.
  • Method signatures (retrn type, name of the method, and parameters) must be unique for the agregated typed (which was defined partially). i.e. you can write default constructor in two separate definitions for a particular partial class.

Example:

File 1:
public partial class myPartialClass
{
public myPartialClass(string pString)
{
Console.WriteLine("I am in a partial class in Partial.cs. The parmeter passed is: " + pString);
}
public void doSomethingElse()
{
Console.WriteLine(" I am in Partial.cs ");
}
}
File 2:
public partial class myPartialClass
{
public myPartialClass()
{
Console.WriteLine(" I am in a partial class in Program.cs");t
}
public void doSomething()
{
Console.WriteLine(" I am in Progam.cs ");
}
}
class TestProgram
{
static void Main(string[] args)
{
/// see the classe are partial but the object is complete.
myPartialClass myCompleteObject = new myPartialClass();
myCompleteObject.doSomething();
myCompleteObject.doSomethingElse();
Console.ReadLine();
}
}

No comments: