5. Static Constructor, Partial Classes

Static Constructors

A static constructor in C# is a special constructor that is called exactly once, before any object of the class is created or any static members are accessed. Even if you create 1000 objects, the static constructor runs only a single time.

Partial Classes

A partial class allows you to split the definition of a class across multiple files or separate parts of the same file. Each part must declare the class as partial, and they must reside in the same namespace (or use using statements to reference it).

Why Use Partial Classes?

Partial Methods

In C#, a partial method is a special kind of method that:

Example structure:

// File1.cs
public partial class Example
{
    partial void OnSomethingHappened();
}

// File2.cs
public partial class Example
{
    partial void OnSomethingHappened()
    {
        // Implementation
    }
}

If OnSomethingHappened() has no implementation, calls to it are compiled away.

Reference

The content in this document is based on the original notes provided in Azerbaijani. For further details, you can refer to the original document using the following link:

Original Note - Azerbaijani Version