Sunday, November 28, 2004

Partial Classes in C#

With C# 2.0 it is possible to split definition of classes, interfaces and structures over more than one files.
This feature allows you to do a couple of fancy things like:

1- More than one developer can simultaneously write the code for the class.

2- 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.

There are a few things that you should be careful about when writing code for partial classes:

1- All the partial definitions must preceede with the key word "Partial".
2- All the partial types meant to be the part of same type must be defined within a same assembly and module.
3- 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 classe.

Now here is the code:
File 1:

public partial class myPartialClass
{
/*
///
///
///

public myPartialClass()
{
Console.WriteLine(" I am in partial class in other Partial.cs");
}*/

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: