Partial class:
A partial class is a special feature of C#. It provides a special ability to implement the functionality of a single class into multiple files and all these files are combined into a single class file when the application is compiled. A partial class is created by using a partial keyword. This keyword is also useful to split the functionality of methods, interfaces, or structure into multiple files.
Rules for Partial Classes
- All the partial class definitions must be in the same assembly and namespace.
- All the parts must have the same accessibility like public or private, etc.
- If any part is declared abstract, sealed or base type then the whole class is declared of the same type.
- The user is also allowed to use nested partial types.
- With the help of partial classes, multiple developers can work simultaneously in the same class in different files.
- With the help of a partial class concept, you can split the UI of the design code and the business logic code to read and understand the code.
- When you were working with automatically generated code, the code can be added to the class without having to recreate the source file like in Visual studio.
- You can also maintain your application in an efficient manner by compressing large classes into small ones.
Partial Method:
Partial classes or structs can contain a method that split into two separate .cs
files of the partial class or struct. One of the two .cs
files must contain a signature of the method, and other file can contain an optional implementation of the partial method. Both declaration and implementation of a method must have the partial
keyword.
Rules for Partial Methods
- Partial methods must use the partial keyword and must return void.
- Partial methods can have in or ref but not out parameters.
- Partial methods are implicitly private methods, so cannot be virtual.
- Partial methods can be static methods.
- Partial methods can be generic.
Example:
EmployeeProps.cspublic partial class Employee { public Employee() { GenerateEmpId(); } public int EmpId { get; set; } public string Name { get; set; } partial void GenerateEmployeeId(); }
EmployeeMethods.cspublic partial class Employee { partial void GenerateEmployeeId() { this.EmpId = random(); } }
EmployeeMethods.csclass Program { static void Main(string[] args) { var emp = new Employee(); Console.WriteLine(emp.EmpId); // prints genereted id Console.ReadLine(); } }
No comments:
Post a Comment