Partial Classes
Sometimes, we programmer need to create a big-may be better if I call it enormous-classes with a large number of class members. It will be difficult if we use single
file to write down all the code.
C# provides
Here's the example, in myEnourmousClass.cs file
Meanwhile in myEnourmousClass2.cs, I write other
In program.cs, I write
All the three code files will result
C# provides
partial
keyword to enables partitioning classes. The declaration of a class can be partitioned among several partial class declarations.
- Each of the partial class declarations contains the declarations of some of the class members.
- The partial class declarations of a class can be in the same file or in different files.
partial class
, in contrast to the single keyword class. The declaration of a partial class looks the same as
the declaration of a normal class, other than the addition of the type modifier partial.
Here's the example, in myEnourmousClass.cs file
using System; namespace partial { partial class myEnormousClass { public int myField1; public void myMethod1() { Console.WriteLine("myField1 = " + myField1); Console.WriteLine("Code written in myEnormousClass.cs"); } } }
Meanwhile in myEnourmousClass2.cs, I write other
myEnormousClass
member, as following:
using System; namespace partial { partial class myEnormousClass { public float myField2; public void myMethod2() { Console.WriteLine("myField2 = " + myField2); Console.WriteLine("Code written in myEnormousClass2.cs"); } } }
In program.cs, I write
Main
method, as follow:
using System; namespace partial { class Program { static void Main(string[] args) { myEnormousClass myEnormousObject = new myEnormousClass() { myField1 = 425, myField2 = 73325.43F }; myEnormousObject.myMethod1(); myEnormousObject.myMethod2(); } } }
All the three code files will result
myField1 = 425
Code written in myEnormousClass.cs
myField2 = 73325,43
Code written in myEnormousClass2.cs
Code written in myEnormousClass.cs
myField2 = 73325,43
Code written in myEnormousClass2.cs
The type modifier
partial
is not a keyword, so in other contexts you can use it as an identifier in your program. But when used immediately
before the keywords class, struct, or interface, it signals the use of a partial type.
Besides partial classes, you can also create two other partial types, those are: Partial structs and Partial interfaces.
0 comments:
Post a Comment