Introduction
In this article, we will learn about how to use partial class in C#. A partial class is an important class in C# This 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 in C#
When the application is compiled, all of these files are integrated into a single class file, giving it the unique ability to implement the functionality of a single class into several files. Using the partial keyword produces a partial class. This keyword can be used to divide a method, interface, or structure's functionality into different files.
public partial Clas_name
{
// code
}
important topic
- Use the partial keyword, and all required files must be present at compilation time in order to create the final file when you want to split the functionality of a class, method, interface, or structure over multiple files.
- Only immediately before terms like struct, class, and interface can the partial modifier appear.
- You can use a different source file name, but each component of the partial class definition should be in the same assembly and namespace.
- Every element of the partially defined class should be equally accessible to everyone as private, protected, etc.
- The entire class is declared to be of the same type if any portion of the partial class is declared as an abstract, sealed, or base.
Example
Here, you can say a class named Country and split the definition of Country class into two different files named Country.cs, and Country1.cs as shown below
public partial class Country
{
private string Country_Name ;
private int TotalNumberofCountry ;
public Country(string a, int t)
{
this.Country_Name = a;
this.TotalNumberofCountry = t;
}
}
When we run the aforementioned code, the compiler merges Class1.cs and Class2.cs into one file, referred to as Country, as illustrated in the example below.
CountryThe Main Method might be present in this class. Here, the Main() method is omitted for simplicity's sake.
internal class Class1
{
}
// readonly variables
// Readonly structure
public class Class2
{
private string Country_Name;
private int CountryCity ;
public Class2 (string a, int t)
{
this.Country_Name = a;
this.CountryCity = t;
}
public void Display()
{
Console.WriteLine("Author's name is : " + Country_Name);
Console.WriteLine("Total number articles is : " + CountryCity);
}
}
}
Santhakumar MunuswamyPosted Jan 13, 2016, 10:45 AM
Thanks for nice share
Rajeesh MenothPosted Jan 12, 2016, 4:37 AM
Welcome to C# Corner..!! Thanks for sharing.
Tapan DubeyPosted Jan 12, 2016, 3:37 AM
Thanks to everyone..
Raja TPosted Jan 11, 2016, 10:45 PM
Nice explanation ,thanks for sharing..
Ehsan SajjadPosted Jan 11, 2016, 1:26 PM
Well written
Ankit SaxenaPosted Jan 11, 2016, 12:49 PM
Good informative post. Thanks for sharing...
Nanddeep NachanPosted Jan 11, 2016, 12:42 PM
Good info to know