The concept of partial class was introduce in c# 2.0 and later was extended in c# 3.0
Partial class used to improve code maintainability.
Syntax:
partial class Admin { //body of partial class }
In class library developer, there is a amount of functionality within a single class. What happens if it has lots of functionality? And there would be two or four developer in team want to use same class with different aspect. Obviously it will make many problems to change something and it takes time to handle those things once done.
So the solution, you can break down that class into different partial class.
Let’s take an example:
We have an Admin class and we need to partial admin class into two different aspects so we will add two partial classes with the name as Master Admin class and Sub Admin class.
using System; class Program { static void Main() { Admin ad = new Admin(); ad.MasterAdmin(1, "Master-Admin"); ad.Print(); ad.SubAdmin(2, "Sub-Admin"); ad.Print(); } } interface IAdmin { void Print(); } partial class Admin: IAdmin { public int Id; public string Name; //Master Admin body public void MasterAdmin(int id,string name) { Console.WriteLine("I called master admin method."); this.Id = id; this.Name = name; } public void Print() { Console.WriteLine("Id: {0}", this.Id); Console.WriteLine("Name: {0}", this.Name); Console.WriteLine("-------------------------------"); } } partial class Admin:IAdmin { //Sub Admin body public void SubAdmin(int id, string name) { Console.WriteLine("I called sub admin method"); this.Id = id; this.Name = name; } }
Output:
I called master admin method.
Id: 1
Name: Master-Admin
------------------------------------------------------------
I called sub admin method.
Id: 2
Name: Sub-Admin
------------------------------------------------------------
press any key to continue...
In the above example we have created very simple example for two partial classes of admin and then we have created method for master-admin and sub-admin which takes two arguments one for id and second for name.
And we also created admin interface to print id and name of respected partial class.
you can also visit: www.mybook-lang.com
No comments:
Post a Comment