The “partial” keyword allows you to define a class, struct or interface across multiple files.
As you learned above, each class will be placed in individual files.
But in some situations in future, you may require to define a class within multiple files. In other words, the class definition can be split into multiple files.
For example, if multiple programmers need to develop a class simultaneously, this may be required. In the same way, in windows applications, the automatic code generator generates some design part code for your own form class. In this case also, “partial classes” are required.
Implementation:
MyClassPart1.cs
partial class myclass
{
//some members
}
MyClassPart2.cs
partial class myclass
{
}
//some more members
Partial Classes
SampleClassPart1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PartialClasses
{
partial class SampleClass
{
public void FirstMethod()
{
Console.WriteLine("This is first method.");
}
}
}
SampleClassPart2.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PartialClasses
{
partial class SampleClass
{
public void SecondMethod()
{
Console.WriteLine("This is second method.");
}
}
}
SampleClassPart3.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PartialClasses
{
partial class SampleClass
{
public void ThirdMethod()
{
Console.WriteLine("This is third method.");
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PartialClasses
{
class Program
{
static void Main(string[] args)
{
SampleClass sc = new SampleClass();
sc.FirstMethod();
sc.SecondMethod();
sc.ThirdMethod();
Console.Read();
}
}
}