Author : Suresh Konjerla
It is possible to split the definition of a class or a struct, or an interface over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled.
To split a class definition, use the partial keyword.
Using the partial keyword indicates that other parts of the class, struct, or interface can be defined within the namespace. All the parts must use the partial keyword. All of the parts must be available at compile time to form the final type. All the parts must have the same accessibility, such as public, private, and so on.
Benefit of partial classes
1) More than one developer can simultaneously write the code for the class.
2) You can easily extend VS.NET generated class. This will allow you to write the code of your own need without messing with the system generated code.
Points to be noted while writing code for partial classes
1) All the partial definitions must proceed 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 (return type, name of the method, and parameters) must be unique for the aggregated typed (which was defined partially).
4) The partial types must have the same accessibility.
5) If any part is sealed, the entire class is sealed.
6) If any part is abstract, the entire class is abstract.
7) Inheritance at any partial type applies to the entire class.
Example program:
using System;
using System.Collections.Generic;
using System.Text;
namespace Partial_Class
{
public partial class Add
{
private int x;
private int y;
public Add(int x, int y)
{
this.x = x;
this.y = y;
}
}
public class test
{
static void Main(string[] args)
{
Add a1 = new Add(10, 15);
a1.Print();
Console.ReadKey();
}
}
}
Add another .cs file under same project and add the code
using System;
using System.Collections.Generic;
using System.Text;
namespace Partial_Class
{
public partial class Add
{
public void Print()
{
System.Console.WriteLine(" Addition of {0} and {1} is {2}", x, y, x + y);
}
}
}
No comments:
Post a Comment