← Back to C# Course | Chapter 6: OOP Basics | Lesson 6 of 7

Static Members

Static members belong to the whole class instead of one object, like the school bell that rings for everyone. You use them through the class name without making an object.

In this page:

  1. Static Members
Syntax
csharp
class ClassName
{
    public static type Field;
    public static ReturnType MethodName() { }
}

ClassName.Field;
ClassName.MethodName();   // no object needed

Static Members

static fields and methods belong to the class itself, not to any individual object, and are shared across every instance. You call them through the class name rather than an object reference.

Static members are useful for counters, utility methods, and shared configuration.

Note: A static field is a good way to count how many instances of a class have been created.

Example: Static Members

markup
using System;

class Counter
{
    public static int InstanceCount = 0;

    public Counter()
    {
        InstanceCount++;
    }

    public static int Double(int n) => n * 2;
}

class Program
{
    static void Main(string[] args)
    {
        new Counter();
        new Counter();
        new Counter();

        Console.WriteLine(Counter.InstanceCount);
        Console.WriteLine(Counter.Double(21));
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Trying to access an instance member from a static method without an object.
  2. Expecting each object to have its own copy of a static field, when it is shared by all.
  3. Using static everywhere, which makes code hard to test.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.