Partial Methods
Partial methods are methods that are declared in different parts of a partial class. The different parts of the partial method can be declared in different parts
of the partial class or in the same part. The two parts of the partial method are the following:
Make
Now change the
Our modified code will be resulting:
- The definition of partial method declaration
- Lists the signature and return type.
- There's no implementation code in declaration part.
- The implementation of partial method declaration
- Lists the signature and return type.
- The implementation is in the normal format, which, as you know, is a statement block.
- The definition and implementation of methods must match in signature and return type. The signature and return type have the following characteristics:
- The return type must be
void
. - The signature cannot include access modifiers, making partial methods implicitly
private
. - The parameter list cannot contain
out
parameters. - The contextual keyword partial must be included in both the definition and implementation of methods immediately before the keyword
void
.
- The return type must be
- You can have a defining partial method without an implementing partial method. In this case, the compiler removes the declaration and any calls to the method made inside the class. You cannot have an implementing partial method without a defining partial method.
myEnormousClass
. myEnourmousClass.cs file:
using System; namespace partial { partial class myEnormousClass { public int myField1; partial void incMyFields(); //partial method definition public void myMethod1() { Console.WriteLine("myField1 = " + myField1); Console.WriteLine("Code written in myEnormousClass.cs"); } } }
Make
incMyFields
implementation in myEnourmousClass2.cs file.
using System; namespace partial { partial class myEnormousClass { public float myField2; partial void incMyFields() //incMyFields implementation { ++myField1; } public void myMethod2() { Console.WriteLine("myField2 = " + myField2); Console.WriteLine("Code written in myEnormousClass2.cs"); incMyFields(); //Call incMyFields function } } }
Now change the
Main
method, to check whether partial method works or not.
using System; namespace partial { class Program { static void Main(string[] args) { myEnormousClass myEnormousObject = new myEnormousClass() { myField1 = 425, myField2 = 73325.43F }; myEnormousObject.myMethod1(); myEnormousObject.myMethod2(); myEnormousObject.myMethod1(); //check if partial method already works Console.Read(); } } }
Our modified code will be resulting:
myField1 = 425
Code written in myEnormousClass.cs
myField2 = 73325,43
Code written in myEnormousClass2.cs
myField1 = 426
Code written in myEnormousClass.cs
Code written in myEnormousClass.cs
myField2 = 73325,43
Code written in myEnormousClass2.cs
myField1 = 426
Code written in myEnormousClass.cs
0 comments:
Post a Comment