What is Partial Class in C#?

Partial Class is a cool feature in C# which enables you to split you implementation of a class, struct or an interface over two or more source files.

When do you want to use a Partial Class?

You might want to use Partial class in following scenarios:

·         When working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously.

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

 

You create a partial class using  the keyword partial as shown in the following example

public partial class Employee

{

    public void DoWork()

    {

    }

}

 

public partial class Employee

{

    public void GoToLunch()

    {

    }

}

 

Nested types can be partial, even if the type they are nested within is not partial itself. For example:

class Container

{

    partial class Nested

    {

        void Test() { }

    }

    partial class Nested

    {

        void Test2() { }

    }

}

 

There are some constraints when you are using partial classes:

1.       All partial-type definitions meant to be parts of the same type must be modified with partial

2.       The partial modifier can only appear immediately before the keywords class, struct, or interface

3.       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.

4.       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.

5.       The following keywords on a partial-type definition are optional, but if present on one partial-type definition, cannot conflict with the keywords specified on another partial definition for the same type:

·         public

·         private

·         protected

·         internal

·         abstract

·         sealed

·         base class

·         new modifier (nested parts)

 

 

References:

1.       Partial Class Definition