Skip to main content
Published on

partial in C#

Share:

Introduction

When working on large or collaborative projects in C#, we often encounter the need to split the implementation of a class or method across multiple files for better organisation or collaboration. This is where the partial modifier comes in.

What is the partial modifier?

The partial modifier in C# is used to split the definition of a class, struct, or interface across multiple files. Each file contains a section of the class definition, and all parts are combined when the application is compiled.

Advantages of partial

  1. Organisation: Allows for better code organisation, especially useful in very large classes.
  2. Teamwork: Facilitates collaborative work, as different team members can work on different parts of the same class simultaneously.
  3. Separation of Generated and Manual Code: Often, in applications that use graphical designers (such as Windows Forms or WPF), code is generated automatically. With partial, we can separate the automatically generated code from the manually written code.
  4. Flexibility: Allows greater flexibility when structuring code, enabling a more logical organisation.

Limitations

  • All files that contain a part of the partial class must be compiled together.
  • If a class member is declared as private, it will remain private to that specific part of the class. The other partial files of the same class will not have access to it.
  • You cannot define access modifiers for partial methods.

Practical Example

The example below demonstrates the use of partial in two parts of a Person class:

using System;

namespace Base {
  class Partial {
    public void Run() {
      var person = new Person();
      person.Info();

      /*
        Name: Nelson Silva
        Age: 28
      */
    }
  }

  partial class Person {
    private string firstName = "Nelson";
    partial void _Info();

    public void Info() {
      _Info();
    }
  }

  partial class Person {
    private string lastName = "Silva";
    private int age = 28;

    partial void _Info() {
      Console.WriteLine($"Name: {firstName} {lastName}");
      Console.WriteLine($"Age: {age}");
    }
  }
}

Conclusion

The partial modifier is a valuable tool in C#, offering a flexible way to organise and structure code in larger projects or when collaborating as a team. We hope this article has clarified how and when to use this modifier in your code.

Happy coding!