0
0
CsharpConceptBeginner · 3 min read

What is static keyword in C#: Explanation and Examples

In C#, the static keyword means a member or class belongs to the type itself, not to any object instance. This means you can access static members without creating an object of the class.
⚙️

How It Works

Imagine a class as a blueprint for making many houses. Normally, each house has its own doors and windows. But if you have a mailbox that is shared by all houses on the street, that mailbox is like a static member—it belongs to the whole street, not just one house.

In C#, when you mark a class member as static, it means this member is shared by all instances of the class. You don't need to create an object to use it; you can access it directly through the class name. This saves memory and keeps data or behavior common to all objects in one place.

Static members are initialized once and live for the entire program run. This is different from instance members, which exist separately for each object.

💻

Example

This example shows a class with a static field and a static method. You can use them without creating an object.

csharp
using System;

class Counter
{
    public static int count = 0;

    public static void Increment()
    {
        count++;
    }
}

class Program
{
    static void Main()
    {
        Counter.Increment();
        Counter.Increment();
        Console.WriteLine("Count: " + Counter.count);
    }
}
Output
Count: 2
🎯

When to Use

Use static when you want to share data or behavior across all objects of a class or when the member logically belongs to the class itself, not any single object.

Common uses include:

  • Utility or helper methods that don't need object data, like math functions.
  • Keeping track of information shared by all instances, like counting how many objects were created.
  • Defining constants or configuration values that never change.

For example, a Math class with static methods like Math.Sqrt() lets you calculate square roots without making a math object.

Key Points

  • Static members belong to the class, not instances.
  • You access static members using the class name, not an object.
  • Static members are initialized once and shared by all instances.
  • Static classes can only contain static members.
  • Use static for shared data, utility methods, or constants.

Key Takeaways

The static keyword makes members belong to the class itself, not objects.
You can access static members without creating an instance of the class.
Static members are shared and initialized once for the entire program.
Use static for shared data, utility methods, or constants.
Static classes can only have static members.