C# tutorials > Core C# Fundamentals > Object-Oriented Programming (OOP) > What are partial classes and methods?

What are partial classes and methods?

This tutorial explains partial classes and methods in C#, which allow splitting the definition of a class or method across multiple files. This is useful for code generation, separating concerns, and improving code maintainability. We'll cover syntax, usage scenarios, and best practices.

Introduction to Partial Classes

Partial classes allow you to split the definition of a class, struct, or interface into multiple files. The C# compiler combines these parts into a single type at compile time. This is accomplished using the partial keyword.

Partial Class Syntax

In this example, MyClass is defined in two separate files (or within the same file). The partial keyword indicates that these are parts of the same class. The compiler will merge these definitions into a single MyClass type.

public partial class MyClass
{
    // Part 1: Fields and some methods
    public string Name { get; set; }
}

public partial class MyClass
{
    // Part 2: More methods and properties
    public void DisplayName()
    {
        Console.WriteLine("Name: " + Name);
    }
}

Introduction to Partial Methods

Partial methods are methods that are defined in one part of a partial class but may or may not be implemented in another part. They are implicitly private and can only return void. If a partial method is declared but not implemented, the compiler removes all calls to that method, so there's no performance impact. This is useful for conditional compilation and code generation scenarios.

Partial Method Syntax

Here, OnNameChanged is a partial method. The first part of MyClass declares the method. The second part optionally implements the method. If the second part doesn't exist, the call to OnNameChanged() in the Name property's setter is simply removed by the compiler. If the second part exists, the OnNameChanged method will be executed when Name is changed.

public partial class MyClass
{
    // Declaration (signature) of the partial method
    partial void OnNameChanged();

    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            OnNameChanged(); // Call to the partial method
        }
    }
    private string _name;
}

public partial class MyClass
{
    // Optional implementation of the partial method
    partial void OnNameChanged()
    {
        Console.WriteLine("Name changed!");
    }
}

Concepts Behind the Snippet

Partial classes and methods enable separation of concerns and allow for easier code management, especially in scenarios involving auto-generated code. They facilitate collaboration among developers working on different parts of the same class. Partial methods offer a way to inject code at specific points without requiring implementation everywhere.

Real-Life Use Case Section: Entity Framework and Code Generation

A common use case is with Entity Framework or other ORMs that generate code based on a database schema. The generated code can be placed in one part of a partial class, and your custom logic can be placed in another part, preventing your modifications from being overwritten when the code is regenerated. Partial methods can be used to hook into events triggered by the generated code, allowing for customization without modifying the core generated files.

Best Practices

  • Use partial classes when a class becomes too large and complex to manage in a single file.
  • Use partial methods to provide extensibility points in generated code.
  • Clearly document the purpose of each partial class and method to avoid confusion.
  • Avoid overusing partial classes, as they can make it harder to understand the overall structure of the type.

Interview Tip

Be prepared to explain the difference between partial classes and methods, their use cases, and their limitations. Mention code generation scenarios and the ability to extend auto-generated code without directly modifying it. Also, be ready to explain the implicit private nature and void return type restriction of partial methods.

When to use them

Use partial classes when dealing with large classes, generated code that needs to be extended, or when different developers are working on different parts of the same class. Use partial methods for injecting custom behavior into code (particularly generated code) without the risk of breaking the base functionality.

Memory footprint

Partial classes themselves do not introduce any additional memory overhead at runtime. The compiler merges the different parts into a single class definition. Partial methods, when not implemented, have zero performance or memory overhead because the compiler removes calls to them. When implemented, their memory footprint is the same as any other method.

Alternatives

Alternatives to partial classes include using inheritance, composition, or extension methods. Alternatives to partial methods include using events or virtual methods (with the caveat that virtual methods must always have an implementation, while partial methods can be optionally implemented).

Pros

  • Improved code organization and maintainability.
  • Easier collaboration among developers.
  • Extensibility of generated code without direct modification.
  • Zero overhead for unimplemented partial methods.

Cons

  • Can make code harder to follow if overused.
  • Partial methods are implicitly private and can only return void.
  • Requires careful planning to avoid naming conflicts between different parts of the class.

FAQ

  • Can I have multiple partial classes in the same file?

    Yes, you can define multiple partial classes with the same name within the same file.
  • Can a partial class inherit from another class?

    Yes, a partial class can inherit from another class. The inheritance relationship must be declared in one of the partial definitions, and it applies to the entire class.
  • Can I define properties or fields in different partial class definitions?

    Yes, you can define properties and fields in different parts of the partial class. The compiler will merge all members into a single class definition.
  • What happens if I declare a partial method but don't implement it?

    If you declare a partial method but don't provide an implementation, the compiler removes the declaration and all calls to the method. This means there's no performance impact.
  • Are partial methods virtual?

    No, partial methods are not virtual. They are implicitly private and are either implemented or removed by the compiler. They cannot be overridden.