---
# System prepended metadata

title: C# - partial keyword
tags: [C#, partial]

---

# C# - partial keyword

###### tags: `C#` `partial`

C# partial keyword 能讓一個很大的 class file,
變成能拆解成許多小部份來分開實作,
但最後在編譯時會合併

C#'s partial class feature allows developer to implement the functionality of a single class  into multiple files. 
All the relevant files are combined into a single class file when the application is compiled. 
With the help of partial classes, multiple developers can work simultaneously in the same class in different files.

# [Partial Classes in C#](https://www.geeksforgeeks.org/partial-classes-in-c-sharp/)

A ``partial`` class is a special feature of C#. 
It provides a special ability to __implement the functionality of a single class 
into multiple files and all these files are combined into a single class file__ 
when the application is compiled. 
A ``partial`` class is created by using a ``partial`` keyword. 
This keyword is also useful to __split the functionality of 
methods, interfaces, or structure into multiple files__.

Syntax :  
```
public partial Clas_name  
{
        // code
}
```

### Important points: 

* When you want to chop the functionality of 
the class, method, interface, or structure into multiple files, 
then you should use ``partial`` keyword and 
all the files are mandatory to be available at compile time 
for creating the final file.
* The ``partial`` modifier can only present instantly 
__before the keywords__ like ``struct``, ``class``, and ``interface``.
* Every part of the partial class definition 
__should be in the same assembly and namespace__, 
but you __can use a different source file name__.
* Every part of the partial class definition 
__should have the same accessibility__ as ``private``, ``protected``, etc.
* If any part of the partial class is declared as an abstract, sealed, or base, then the whole class is declared of the same type.
* The user is also allowed to use __nested partial types__.
* Dissimilar parts may have dissimilar base types, but the final type must inherit all the base types.

### Example: 

Here, we are taking a class named ``Geeks`` and 
split the definition of ``Geeks`` class into two different files 
named ``Geeks1.cs``, and ``Geeks2.cs`` as shown below:


In ``Geeks1.cs``, and ``Geeks2.cs``, 
a partial class is created using the partial keyword and 
__each file contains different functionality of ``Geeks`` class__ as shown below.

``Geeks1.cs``:

```
public partial class Geeks 
{
    private string Author_name;
    private int Total_articles;
 
    public Geeks(string a, int t)
    {
        this.Authour_name = a;
        this.Total_articles = t;
    }
}
```

``Geeks2.cs``:

```
public partial class Geeks 
{
    public void Display()
    {
        Console.WriteLine("Author's name is : " + Author_name);
        Console.WriteLine("Total number articles is : " + Total_articles);
    }
}
```

When we execute the above code, 
the compiler combines ``Geeks1.cs`` and ``Geeks2.cs`` into a single file, 
i.e. Geeks as shown below.
``Geeks`` This class may contain the Main Method. 
For simplicity, here ``Main()`` method is not included. 

```
public class Geeks 
{
    private string Author_name;
    private int Total_articles;
 
    public Geeks(string a, int t)
    {
        this.Authour_name = a;
        this.Total_articles = t;
    }
 
    public void Display()
    {
        Console.WriteLine("Author's name is : " + Author_name);
        Console.WriteLine("Total number articles is : " + Total_articles);
    }
}
```

Another example:

```
partial class MyClass : IF3
{
    // main implementation of MyClass
}

partial class MyClass : IF1
{
    // implementation of IF1
}

partial class MyClass : IF2
{
    // implementation of IF2
}
```


### Advantages : 

* With the help of partial classes, 
__multiple developers can work simultaneously in the same class in different files__.
* With the help of a partial class concept, 
you can __split the UI of the design code and the business logic code__ 
to read and understand the code.
* When you were working with automatically generated code, 
the code can be added to the class without 
having to recreate the source file like in Visual studio.
* You can also maintain your application in an efficient manner 
by compressing large classes into small ones.


---

# [Why use partial classes?](https://softwareengineering.stackexchange.com/questions/71494/why-use-partial-classes)

In my understanding, the ``partial`` keyword does nothing 
but __allow a class to be split between several source files__. 
Is there any reason to do this other than for code organization? 
I've seen it used for that in __generated UI classes__.

It seems a poor reason to create a whole keyword. 
If a class is big enough to require multiple files, 
it probably is doing too much. 
I thought that perhaps you could use it to partially define a class 
for another programmer somewhere to complete, 
but it would be better to make an abstract class.

### 114

It is very useful in every scenario 
where one part of class is generated by some custom tool 
because it allows you to adding custom logic 
to __generated code without inheriting the generated class__. 
Btw. there are also ``partial`` methods for the same reason.

It is not only about UI but also other technologies 
like Linq-To-Sql or Entity Framework use this quite heavily.

### 26
As you say, it is often used to separate generated code. It is often nothing to do with the size of classes/files.

The benefit of separating generated code is one of style. Generated code can be pretty ugly and unreadable and would fail many coding standards (and StyleCop checks), but that's OK, no one has to read it or maintain it directly. So, if you "hide" it in another file you can focus on making sure the rest of the class is up to standard, passes StyleCop checks and so on.

Another area where I've used it is where 
__a class implements multiple interfaces, 
it can be quite nice __to separate the implementation in to separate files__, 
although this is more a matter of personal preference, 
I've never seen any coding standards require (or prevent) this.

### 23

I can think of a few useful scenarios where partials make sense, most of them I am using myself in my projects:

    To separate Tool/IDE/Designer generated code from the code you are maintaining. A good example is the Form.Designer.cs file that contains the designer generated code for windows forms applications. Many other .NET formats also have some tool generated code, which can be potentially regenerated when you build your project, and thus all your custom changes will be swiped out. The separation will help you keep your code and changes safe from such automated modifications.

    When you are implementing multiple interfaces with a lot of code in the implementation. I tend to use a separate partial file for each such interface, naming it like this: {Class}.{Interface}.cs. It is easy for me to see in the IDE which interfaces the {Class} is implementing and how.

    When the class must contain one or more nested classes, especially with enough code in them to be put into a separate file. I would stick to the above pattern and use the {Class}.{NestedClass}.cs naming convention for each nested class. Similar practice is already mentioned by Virtlink's answer.

    When I write static classes which will hold extension methods. It will often be the case to provide the same extension method logic to similar classes or interfaces - like for instance Reverse on generic and non-generic collections. I would put all the extension methods for a single class or interface in a separate partial of the static class. For instance, I'd have all extension methods for the IList interface in one place, and the same methods that are for IList<T> in another file. Another approach would be to put the same method (all of its overloads) in the same partial, with all possible classes for the this parameter - like having all the Reverse implementations in one file. It depends which one would better justify the separation in terms of code volume, or some internal conventions you or your organization might be sticking to.

    I do not use this, but I've seen some C/C++ folks to like the approach I will describe here: create a partial for the class with partial methods only. This resembles the C/C++ way to define interfaces and separate the method declaration from the implementation.

    Separation by purely logical concerns. If you happen to work with a large class that combines more than one logical set of operations in itself, then you could separate each logically-related code into a separate partial. Usually existence of such classes is against the separation of concerns principle, but it is oftenly observed real-life case, especially for older codebases. Fellow user Steve Evers has mentioned them in his answer to this question, referring to them by the name god objects. I'd personally use the approach of partial classes to split the code before any refactoring of such really large files takes place, in order to ease my work and make the refactoring more transparent. This will also reduce the conflicts I will potentially cause when versioning systems like SVN are involved.

### 19

One of the developers where I work 
came up for a pretty good use for them a couple of weeks ago 
in the __refactoring of huge God classes__ that 
have __spiralled out of control__ and have __lots of public methods__: 
__by separating the logical functions__ of each bit of the class 
__into a separate partial classes__ you can physically separate the class 
into the more atomic units that should be the classes 
__without breaking any existing functionality__, 
allowing you to see what is common and what is not. 
With this as a first stage you can then more easily 
break the partials out into their own independent classes and 
implement them throughout the code base. I thought this was a nice idea.

However, in general I think that they should only be used 
to augment machine generated classes when writing new code.

---

# [When is it appropriate to use C# partial classes?](https://stackoverflow.com/questions/3601901/when-is-it-appropriate-to-use-c-sharp-partial-classes)

I was wondering if someone could give me an overview of why I would use them and what advantage I would gain in the process.

### 446

The biggest use of partial classes is to make life easier for code generators / designers. Partial classes allow the generator to simply emit the code they need to emit and they do not have to deal with user edits to the file. Users are likewise free to annotate the class with new members by having a second partial class. This provides a very clean framework for separation of concerns.

A better way to look at it is to see how designers functioned before partial classes. The WinForms designer would spit out all of the code inside of a region with strongly worded comments about not modifying the code. It had to insert all sorts of heuristics to find the generated code for later processing. Now it can simply open the designer.cs file and have a high degree of confidence that it contains only code relevant to the designer.

### 292

Another use is to __split the implementation of different interfaces__, e.g:

```
partial class MyClass : IF3
{
    // main implementation of MyClass
}

partial class MyClass : IF1
{
    // implementation of IF1
}

partial class MyClass : IF2
{
    // implementation of IF2
}
```
