Home
C#
partial Keyword
Updated Dec 8, 2022
Dot Net Perls
Partial. Partial classes span multiple files. With the partial keyword in the C# language, you can physically separate a class into multiple files.
Notes, partial. This keyword is often used by code generators (like Visual Studio). But we can sometimes benefit from directly using partial on a C# class declaration.
class
An example. Normally you cannot declare a class in 2 separate files. But with the partial modifier, you can. This is useful if one file is commonly edited and the other is not.
Here If you remove the partial modifier, you will get an error at compile time.
Detail The namespace "global namespace" already contains a definition for "A."
namespace
Tip To fix this, you can either use the partial keyword, or change one of the class names.
class Program { static void Main() { A.A1(); A.A2(); } }
// A1.cs using System; partial class A { public static void A1() { Console.WriteLine("A1"); } }
// A2.cs using System; partial class A { public static void A2() { Console.WriteLine("A2"); } }
A1 A2
Compiler. How does the C# compiler deal with partial classes? If you disassemble the above program, you will see that the files A1.cs and A2.cs are eliminated.
And You will find that the class A is present. Class A will contain the methods A1 and A2 in the same code block.
Thus Partial classes are precisely equivalent to a single class with all the members.
internal class A { // Methods public static void A1() { Console.WriteLine("A1"); } public static void A2() { Console.WriteLine("A2"); } }
A review. Partial classes can simplify certain situations. They are often used in Visual Studio when creating Windows Forms programs. The machine-generated C# code is separate.
Some uses. Partial classes separate commonly-edited code from rarely-edited code. This can reduce confusion and the possibility that code that isn't supposed to be edited is changed.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 8, 2022 (edit).
Home
Changes
© 2007-2025 Sam Allen