Open In App

Partial Classes in C#

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.

Syntax :  



public partial Clas_name  
{
        // code
}

Important points: 

Example: Here, we are taking a class named Geeks and split the definition of Geeks class into two different files named Geeks1.cs, and Geeks2.cs as shown below:
 



In Geeks1.cs, and Geeks2.cs, a partial class is created using the partial keyword and each file contains different functionality of Geeks class as shown below.

Geeks1.cs




public partial class Geeks {
    private string Author_name;
    private int Total_articles;
 
    public Geeks(string a, int t)
    {
        this.Authour_name = a;
        this.Total_articles = t;
    }
}

Geeks2.cs 




public partial class Geeks {
    public void Display()
    {
        Console.WriteLine("Author's name is : " + Author_name);
        Console.WriteLine("Total number articles is : " + Total_articles);
    }
}

When we execute the above code, the compiler combines Geeks1.cs and Geeks2.cs into a single file, i.e. Geeks as shown below.
Geeks This class may contain the Main Method. For simplicity, here Main() method is not included. 




public class Geeks {
    private string Author_name;
    private int Total_articles;
 
    public Geeks(string a, int t)
    {
        this.Authour_name = a;
        this.Total_articles = t;
    }
 
    public void Display()
    {
        Console.WriteLine("Author's name is : " + Author_name);
        Console.WriteLine("Total number articles is : " + Total_articles);
    }
}

Advantages : 

 


Article Tags :
C#