Partial class in .net

Posted by Techie Cocktail | 5:40 PM | | 0 comments »

Partial class feature was introduced in .Net 2.0. Partial classes enable us to use multiple files to store the code of the same class. At the time of compilation all the pieces are clubbed together by the compiler and treated as a single class. Partial concept is also true for struct or an interface.

The developers must be careful doing this and must have good understanding of this feature else it may result in some design issues.

Advantages of using this feature are:
a. The .net available classes can be further extended based on your requirements.
b. Multiple developers can work on the same class simultaneously.

Lets see this using an example,


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace clsPartial
{
partial class pCls
{
int a;

public int A
{
get { return a; }
set { a = value; }
}
}

partial class pCls
{
int b;

public int B
{
get { return b; }
set { b = value; }
}
}

class MainClass
{
public static void Main()
{
pCls ab = new pCls();


Console.WriteLine(ab.A + "," + ab.B);
}
}

}

There are some rules when implementing partial class that we must need to follow to avoid errors. Below are some of the important points to consider:

a. Every piece of the partial class must contain the partial keyword & must used the same class name.
b. All pieces of the partial class must be defined in the same assembly or a module.
c. If any of the pieces are declared as abstract, the whole class is considered as the abstract class.
d. All pieces of the partial class must use the same access specifier. For example, public, private etc.
e. If any of its pieces are declared as sealed, the complete class is considered to be a sealed class.
f. If any of its pieces inherits from a base class, the complete class inherits that base class.

0 comments