How to implement partial class in C#
Implement partial class in C#
In this article we are going to discuss one beautiful
feature of C# , Partial Class. Using partial class concept we can split a single class in various small sections and each section (definition)
will share same name.
If you closely observe any web page then you
will find that by default main class is qualify as partial class like below.

Implementation of partial class
Let’s see how to define partial class in our own. We have to
use partial keyword in front of class definition.
using System;
using System.Collections;
using System.Data;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Test1
{
partial class A
{
public void Partial_A()
{
Console.WriteLine("I am partial A");
}
}
partial class A
{
public void Partial_B()
{
Console.WriteLine("I am other part of A");
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
a.Partial_A();
Console.ReadLine();
}
}
}
In this
example we have defined “A” class as partial class. So that, we are allowed to define
“A” class more than one. But in behind (in IL code) .NET compiler combines both
definitions in a single class. Below is the screen of IL code.

This is
output screen of this code.

Is it needed
to define all class in same file?
No, we can
define partial class anywhere in project/application. It is not necessary to
define in same file. In below example we will implement partial class in different
.CS file but they must be in same namespace like below.

Code implementation
is here.
In first
.CS file
using System;
using System.Collections;
using Test1;
namespace Test1
{
partial class A
{
public void Partial_A()
{
Console.WriteLine("First Part");
}
}
partial class A
{
public void Partial_B()
{
Console.WriteLine("Second Part");
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
a.Partial_A();
a.Partial_B();
a.Partial_C();
Console.ReadLine();
}
}
}
In second
.CS file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test1
{
partial class A
{
public void Partial_C()
{
Console.WriteLine("Second Part");
}
}
}
Here is
output screen.

Conclusion:
This is the example of partial class in C#. Hope you have understood the concept and enjoyed the article.