About
In this code snippet, we will found out what partial classes are in C#.
If a class is marked with the partial keyword a class with the same name can be declared in another file. Both of the classes will now share everything between them and act as one. The partial keyword basically allows us to split up a class into different parts that can be put into different files.
Let’s look at the code below to see how to make a partial class.
Code:
First file
using System; namespace PartialClass { class Program { static void Main(string[] args) { MyPartialClass MPC = new MyPartialClass(10); MPC.myMethod(); Console.ReadLine(); //As you can see we were able to call the method from the other file just as if it was in this file. } } //The partial keyword is used so a class can be split into more physcial files. public partial class MyPartialClass { public MyPartialClass(int number) { MyProperty = number; } public int MyProperty { get; set; } } }
Second file
using System; namespace PartialClass { public partial class MyPartialClass { public void myMethod() { Console.WriteLine(MyProperty); } } }