A partial class or struct may contain a partial method. One part of the class contains the signature of the method. An optional implementation may be defined in the same part or another part. If the implementation is not supplied, then the method and all calls to the method are removed at compile time.
Partial methods enable the implementer of one part of a class to define a method, similar to an event. The implementer of the other part of the class can decide whether to implement the method or not. If the method is not implemented, then the compiler removes the method signature and all calls to the method. The calls to the method, including any results that would occur from evaluation of arguments in the calls, have no effect at run time. Therefore, any code in the partial class can freely use a partial method, even if the implementation is not supplied. No compile-time or run-time errors will result if the method is called but not implemented.
Partial methods are especially useful as a way to customize generated code. They allow for a method name and signature to be reserved, so that generated code can call the method but the developer can decide whether to implement the method. Much like partial classes, partial methods enable code created by a code generator and code created by a human developer to work together without run-time costs.
A partial method declaration consists of two parts: the definition, and the implementation. These may be in separate parts of a partial class, or in the same part. If there is no implementation declaration, then the compiler optimizes away both the defining declaration and all calls to the method.
Example:
CoOrds1.cs
public partial class CoOrds
{
private int x;
private int y;
public CoOrds(int x, int y)
{
this.x = x;
this.y = y;
}
partial void PrintCoOrds();
}
CoOrds2.cs
public partial class CoOrds
{
partial void PrintCoOrds()
{
System.Console.WriteLine("CoOrds {0},{1}", x, y);
}
public void PrintTheCoOrds()
{
PrintCoOrds();
}
}
CoOrds2.cs
class TestCoOrds
{
static void Main()
{
CoOrds myCoOrds = new CoOrds(100, 150);
myCoOrds.PrintTheCoOrds();
}
}
Refence : Partial Classes and Methods (C# Programming Guide) at MSDN
Hi, I am Ganda Manurung. I am a software developer, enterpreneur, and also an ameteur photographer.
4 comments… read them below or add one
C# make me crazy…
C# makes me happy.
C# makes money come to me.. =))
#Puji, Hahaha.. How bro? How come?