Partial Classes and Methods
Partial Classes and Methods
EmployeeProps.cs
public partial class Employee
{
public int EmpId { get; set; }
public string Name { get; set; }
}
EmployeeMethods.cs
public partial class Employee
{
//constructor
public Employee(int id, string name){
this.EmpId = id;
this.Name = name;
}
Partial Methods
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.
EmployeeProps.cs
public partial class Employee
{
public Employee() {
GenerateEmpId();
}
public int EmpId { get; set; }
public string Name { get; set; }
}
EmployeeMethods.cs
public partial class Employee
{
partial void GenerateEmployeeId()
{
this.EmpId = random();
}
}
Above, EmployeeProps.cs contains the declaration of the partial
method GenerateEmployeeId() which is being used in the
constructor. EmployeeMethods.cs contains the implementation of
the GenerateEmployeeId() method. Creates an object
the Employee class which used the partial method.
EmployeeMethods.cs
class Program
{
static void Main(string[] args)
{
var emp = new Employee();
Console.WriteLine(emp.EmpId); // prints genereted id
Console.ReadLine();
}
}