Partial Classes
Partial classes allows you to define a class in multiple seperate files. For example, you can place all the fields, properties, and constructors inside a file, and place all the methods in another file. To define a class as partial, simply use the partial keyword. The following shows you a partial classdifined inside twoseperate files.
namespace PartialClassesDemo
{
public partial class Sample
{
private int sampleField;
public int SampleProperty
{
get { return sampleField; }
set { sample = value; }
}
}
}
Example 1 – First Partial Class
namespace PartialClassesDemo
{
public partial class Sample
{
public void DoSomething()
{
//Do something here
}
}
}
Example 2 – Second Partial Class
Partial classes are defined using the partial keyword. These separate files will define one class named Sample. A field and a property were defined on the first one, and a method was defined on the other one. Note that the compiler requires the partial classes that will be combined to be inside the same namespace. As you can see in Example 1 and 2, both partial classes are inside the PartialClassesDemo namespace.
When inheriting classes or implementing interfaces, only one part of the partial class needs to do the inheritance. If the first part implements IInterface1 and the second part implements IInterface2, then the final combined class implements both IInterface1and IInterface2.
public partial class Sample : IInterface1
{
}
public partial class Sample : IInterface2
{
}
The combined class will look like this:
public class Sample : IInterface1, IInterface2
{
}
Partial classes are used in windows forms and in web forms to seperate the code files from the files that handle the overall design of those forms.