Partial class in C#.Net

This C#.Net tutorial explains, partial class in C#.Net. What is the advantage of using partial class and how to implement the partial class in c#.net?

Partial class in C#.Net

Let us first understand what is a partial class in C#.Net.

We can split the definition of a class or a struct or an interface over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled.

Advantages of Partial Class in C#.Net

This is very much helpful while working with large projects, where multiple developers can work in the same class file.

When working with the automatically generated source, a code can be added to the class without having to recreate the source file. Visual Studio uses this approach when it creates Windows Forms, Web service wrapper code, and so on. You can create code that uses these classes without having to modify the file created by Visual Studio.

Create Partial Class and Interface in C#.Net

We have to use keyword partial to implement the partial class.

public partial class MyClass
{
    public void MyMethod1()
    {
    }
}
public partial class MyClass
{
    public void MyMethod2()
    {
    }
}

Similarly, we can define a C#.Net partial interface too like below:

partial interface IMyInterface
{
    void myMethod1();
}
partial interface IMyInterface
{
    void myMethod2();
}

Some points to remember while working with a partial class, interface or structure.

  • All partial-type definitions meant to be parts of the same type must be modified with partial.
  • The partial modifier can only appear immediately before the keywords class, struct, or interface.
  • Nested partial types are allowed in partial-type definitions.
  • All partial-type definitions meant to be parts of the same type must be defined in the same assembly and the same module (.exe or .dll file). Partial definitions cannot span multiple modules.
  • The class name and generic-type parameters must match on all partial-type definitions. Generic types can be partial. Each partial declaration must use the same parameter names in the same order.

For more information follow this link.

You may like following asp.net and c#.net tutorials:

Hope this C#.net tutorial explains, what is a partial class in c#.net and what are the advantages of using partial class in C#.Net?

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

>