404 Not Found

404 Not Found


nginx

Static Members and Extension Methods

static Fields and Methods

static members belong to the type itself rather than to any instance. All instances share the same static field. Static methods are called via ClassName.Member without creating an object.

Example

CSHARP
class Counter
{
    public static int TotalCount = 0;
    public int InstanceId;

    public Counter(int id)
    {
        InstanceId = id;
        TotalCount++;
    }

    public static void Report()
    {
        Console.WriteLine($"{TotalCount} instances created");
    }
}

Counter a = new Counter(1);
Counter b = new Counter(2);
Counter.Report();
Console.WriteLine(Counter.TotalCount);
▶ Try it Yourself
TEXT
2 instances created
2
💡 static methods cannot use this and cannot directly access instance members — they can only access other static members.

Static Constructors

A static constructor runs automatically once when the class is first accessed, and only once. It cannot have access modifiers or parameters, and is commonly used to initialize static fields.

Example

CSHARP
class Config
{
    public static readonly DateTime StartTime;

    static Config()
    {
        StartTime = DateTime.Now;
        Console.WriteLine("Static constructor executed");
    }
}

Console.WriteLine("Preparing to access Config");
Console.WriteLine(Config.StartTime);
Console.WriteLine(Config.StartTime);
▶ Try it Yourself
TEXT
Preparing to access Config
Static constructor executed
2026/06/28 10:00:00
2026/06/28 10:00:00
⚠️ A static constructor is triggered only once — accessing the class's static members multiple times will not cause it to execute again.

static Classes (Utility Class Pattern)

A class declared with static class cannot be instantiated or inherited. All members must be static, making it suitable for encapsulating utility methods.

Example

CSHARP
static class MathHelper
{
    public static double Square(double x) => x * x;
    public static double Hypotenuse(double a, double b) => Math.Sqrt(Square(a) + Square(b));
}

Console.WriteLine(MathHelper.Square(3));
Console.WriteLine(MathHelper.Hypotenuse(3, 4));
▶ Try it Yourself
TEXT
9
5
📌 Attempting new MathHelper() causes a compile error — static classes cannot be instantiated.

const vs static readonly

Feature const static readonly
When assigned Compile time Runtime
Value types Built-in types only Any type
Mutability Immutable Immutable after assignment in constructor

Example

CSHARP
class Settings
{
    public const int MaxRetry = 3;
    public static readonly DateTime LaunchTime;

    static Settings()
    {
        LaunchTime = DateTime.Now;
    }
}

Console.WriteLine(Settings.MaxRetry);
Console.WriteLine(Settings.LaunchTime);
▶ Try it Yourself
TEXT
3
2026/06/28 10:00:00
⚠️ const values are embedded in the caller's assembly at compile time. If a const is modified, all referencing assemblies must be recompiled. static readonly is read at runtime, making it safer.

Extension Methods

Extension methods "add" methods to an existing type without modifying it. They are defined in a static class, and the first parameter is prefixed with the this keyword, allowing them to be called as if they were instance methods.

Example

CSHARP
static class StringExt
{
    public static bool IsEmpty(this string s) => s.Length == 0;
    public static string Repeat(this string s, int count)
    {
        var sb = new StringBuilder();
        for (int i = 0; i < count; i++) sb.Append(s);
        return sb.ToString();
    }
}

Console.WriteLine("hello".IsEmpty());
Console.WriteLine("ab".Repeat(3));
▶ Try it Yourself
TEXT
False
ababab
💡 Extension methods are essentially static method calls — the compiler translates s.IsEmpty() into StringExt.IsEmpty(s). Instance methods take precedence over extension methods.

Extension Methods in Practice (LINQ Fundamentals)

LINQ's fluent syntax is built on extension methods. Where, Select, OrderBy, and others in System.Linq.Enumerable are all extension methods on IEnumerable<T>.

Example

CSHARP
static class EnumerableExt
{
    public static IEnumerable<T> MyWhere<T>(this IEnumerable<T> source, Func<T, bool> predicate)
    {
        foreach (var item in source)
        {
            if (predicate(item)) yield return item;
        }
    }
}

int[] nums = { 1, 2, 3, 4, 5, 6 };
var even = nums.MyWhere(n => n % 2 == 0);
Console.WriteLine(string.Join(", ", even));
▶ Try it Yourself
TEXT
2, 4, 6
🚀 Once you understand how extension methods work, reading LINQ source code becomes straightforward — it's simply a well-designed collection of extension methods.

partial Classes

The partial keyword allows a class definition to be split across multiple files, which are merged into a single complete class at compile time. This is commonly used to separate auto-generated code from hand-written code.

Example

CSHARP
partial class User
{
    public string Name { get; set; }
    public User(string name) => Name = name;
}

partial class User
{
    public void Greet() => Console.WriteLine($"Hello, {Name}");
}

var u = new User("Alice");
u.Greet();
▶ Try it Yourself
TEXT
Hello, Alice
📌 Frameworks like WinForms, WPF, and EF Core make extensive use of partial classes to separate designer-generated code from business logic.

partial Methods

A partial method is declared in one part of a partial class and optionally implemented in another part. If not implemented, the compiler removes the call site — zero overhead. Starting with C# 9, partial methods no longer have signature restrictions.

Example

CSHARP
partial class Order
{
    public int Amount { get; set; }
    partial void OnCreated();

    public Order(int amount)
    {
        Amount = amount;
        OnCreated();
    }
}

partial class Order
{
    partial void OnCreated() => Console.WriteLine("Order created");
}

var o = new Order(100);
Console.WriteLine(o.Amount);
▶ Try it Yourself
TEXT
Order created
100
💡 If you remove the OnCreated implementation from the second partial class, the program still compiles, and the call site is automatically removed by the compiler.

❓ FAQ

Q Can static methods access instance fields?
A No. Static methods are not associated with any instance — you must use an object reference to access instance members.
Q Should I use const or static readonly?
A Use const for simple constants known at compile time; use static readonly for values determined at runtime or for reference types.
Q Can extension methods access private members?
A No. Extension methods are essentially static methods and can only access public members.
Q Must all parts of a partial class be in the same assembly?
A Yes, all parts of a partial class must be in the same assembly and the same namespace.

📖 Summary

📝 Exercises

  1. Write a static class ArrayHelper with Max(int[] arr) and Average(int[] arr) static methods, and test them in Main
  2. Write an extension method MySum for IEnumerable<int> that calculates the sum of an integer sequence without using LINQ
  3. Create a partial class Logger — in one part, declare partial void OnLog(string message) and a Log(string msg) method (which calls OnLog internally); in the other part, implement OnLog to write to the console
  4. Define a const field and a static readonly field, and write code to verify that const is replaced at compile time while static readonly is read at runtime (hint: reference them from another assembly and observe the behavior after modification)
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏