January 28, 2021
Hot Topics:

What Are Partial Types in C#?

  • By Bradley L. Jones
  • Send Email »
  • More Articles »

What Are Partial Types in C#?

Partial types are another construct that Microsoft has proposed be added to the C# language in order to allow a single class to be defined in more than one file. Although it is recommended that a class be stored in a single source file, sometimes it is just not practical. While you can rewrite a class to inherit some of the code from a subclass, this also is not always practical.

Partial types resolve this by allowing multiple files to be used to declare a single class. When compiled, the classes can be combined so that a single class is created. One of the most notable benefits of using partial types is when you also use a code generator. If you use a tool to generate some of your code, you can use partial types to combine the generated code with your own additions to the class. You can keep both pieces in separate files. You won't have to worry about inadvertently changing some of the generated code.

Implementing Partial Types

Partial types are implemented using a proposed new C# keyword, partial. The partial keyword is added to the class declaration in each file that will be combined. For example, the following declares a class named MyClass within parts in two different source files named FileOne.cs and FileTwo.cs:

Listing 1—FileOne.cs—Not a Complete Listing

public class partial MyClass{   // Class stuff...   public void FunctionInMyClass()   {      // Logic...   }   // more stuff...}

Listing 2—FileTwo.cs—Not a Complete Listing

public class partial MyClass{   // Class stuff...   public void AntherFunctionInMyClass()   {      // Logic...   }   // more stuff...}

When these listings are compiled together, the logic is combined into a single class as though a single listing were being used.

About the Author

Bradley Jones is the Executive Editor for Earthweb's Software Development channel, which includes sites such as Developer.com, Codeguru, and Gamelan. He is also the author of the book Sams Teach Yourself the C# Language in 21 Days.

# # #

This article was originally published on July 8, 2003

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date