> ## Content Index
> Fetch the complete content index at: https://mishelshaji.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# Static in C# - A Beginner's Guide With Examples
- URL: https://mishelshaji.com/static-in-c-sharp/
- Published: 2026-05-11T05:11:38.000Z
- Updated: 2026-05-11T05:11:38.000Z
- Description: One of the most important concepts in C# and object-oriented programming is the static keyword. Almost every .NET developer uses static members regularly, but many beginners struggle to fully understand what a static variable is, where to use it, when to use it and when not to use it.
- Author: Mishel Shaji
- Tags: C Sharp, .NET

One of the most important concepts in C# and object-oriented programming is the `static` keyword. Almost every .NET developer uses static members regularly, but many beginners struggle to fully understand what a static variable is, where to use it, when to use it and when not to use it.

💡

In C#, the static keyword is a powerful modifier that shifts the "ownership" of a member from an instance (the object) to the type (the class itself).

## What is `static`?

Normally in object-oriented programming, when we create objects, every object gets its own copy of variables and methods. When you mark a variable, method, or class as `static`, you are telling the .NET runtime that this member should exist **only once in the memory**. You do not need to create an object using the `new` keyword to access it.

So, we can say that static members are:

- Shared across all objects.
- Created only once in memory.
- Accessible using the class name.

## Lifetime and Scope

Understanding when a static member "lives" and "dies" is key to avoiding memory leaks.

- **Lifetime:** Static members are initialized the first time the class is referenced. They stay in memory for the **entire life of the application**. They are only destroyed when the program closes.
- **Scope:** Static members are visible based on their access modifier (`public`, `private`, etc.), but they are always accessed through the Class Name.

💡

Static members are initialized the first time the class is referenced. So it is recommended to use a static constructor to initialize static variables.

## **Common Use Cases:**

1. **Counters:** Keeping track of how many objects have been created.
2. **Shared Configuration:** A global settings value like `AppVersion`.
3. **Caching:** Storing data that is expensive to calculate so all objects can reuse it.

### 1\. Static Members

Static variables are used when you need to store data that should be shared across all instances of a class.

Here is an example of static variables.

```csharp
public class Student
{
    public string Name;
    
    // Static variable: Shared by ALL students
    public static int StudentCount = 0;

    public Student(string name)
    {
        Name = name;
        StudentCount++; // Increment the shared counter
    }
}
```

In this example, the `StudentCount` field is a static member. It is shared across the objects.

#### Accessing Static Members: Class Name vs. Object

This is the most common point of confusion for beginners. **Static members belong to the Class, not the Object.**

```csharp
Student s1 = new Student("Alice");
// ❌: Static member 'StudentCount' cannot be accessed with an instance reference
Console.WriteLine(s1.StudentCount);
```

The correct way is:

```csharp
Student p1 = new Student("Alice");
Student p2 = new Student("Bob");

// ✅ ACCESS VIA CLASS NAME
Console.WriteLine(Student.StudentCount); // Output: 2
```

If we want to access the static member from withing the class, we can simply access it with its name.

```csharp
public class Student
{
    public string Name;
    
    // Static variable: Shared by ALL students
    public static int StudentCount = 0;

    public Student(string name)
    {
        Name = name;
        StudentCount++; // Increment the shared counter.

        // ✅ Correct.
        Console.WriteLine("Total Students " + StudentCount);

        // ✅ Correct.
        Console.WriteLine("Total Students " + Student.StudentCount);

        // ❌ Wrong.
        Console.WriteLine("Total Students " + this.StudentCount);
    }
}
```

### 2\. Static Members

A static method is a function that can be called without creating an object. Because it doesn't belong to a specific object, **it cannot access non-static (instance) variables.**

💡

****The Rule of Thumb:** ****Static methods** can only talk to other ****static members**. ****Instance methods** can talk to ****both** static and instance members.

In the below given example, we have a non-static class called Calculator and two member variables:

1. TaxRate - Instance variable (Cannot be accessed from a static method).
2. GlobalDiscount - A static Variable.

```csharp
public class Calculator
{
    public int TaxRate = 10; // Instance variable
    public static int GlobalDiscount = 5; // Static variable

    // CORRECT: Static method using static variable
    public static int GetDiscountedPrice(int price)
    {
        return price - GlobalDiscount;
    }

    // WRONG: Static method trying to use instance variable
    public static int GetTaxedPrice(int price)
    {
        // ERROR: An object reference is required for the non-static field 'TaxRate'
        return price + (price * TaxRate / 100); 
    }
}
```

The `GetTaxedPrice` is a static method. So, it cannot access any Instance variables like `TaxRate`.

### 3\. Static Class

A `static class` is a class that **cannot be instantiated**. You cannot use the `new` keyword with it. Every single member inside a static class **must** also be marked as `static`.

💡

You can also mark a class as static if all the members of a class are static.

**Why use a static class?** They are perfect for "Utility" or "Helper" functions. Examples in .NET include `Console.WriteLine`, `System.Math` or `System.Convert`.

**Example:**

```csharp
public static class TemperatureConverter
{
    public static double CelsiusToFahrenheit(string gelsius)
    {
        double celsius = double.Parse(gelsius);
        return (celsius * 9 / 5) + 32;
    }
}

// Usage:
double f = TemperatureConverter.CelsiusToFahrenheit("30");
```

### Member Comparison Table

| Feature            | Static Member               | Instance Member                |
| ------------------ | --------------------------- | ------------------------------ |
| **Memory**         | One copy for the whole app. | New copy for every new object. |
| **Access**         | ClassName.Member            | objectName.Member              |
| **Initialization** | When class is first loaded. | When new is called.            |
| **Usage**          | Global helpers, counters.   | Unique data (Name, Age, ID).   |

### Practice Questions

**1\. You have a class `DatabaseConnection`. You want to ensure there is a variable that stores the `TotalConnectionsOpened` across the whole app. Should it be static?**

- **Answer:** Yes. Since you want to track the total across all instances, it must be `static`.

**2\. Can a static method call a non-static method directly?**

- **Answer:** No. A static method exists without an object. A non-static method requires an object to function. Therefore, the static method wouldn't know "which" object's method to call.

**3\. What happens if you try to use the `new` keyword on a static class?**

- **Answer:** You will get a compilation error. Static classes are sealed and cannot be instantiated.

**4\. Look at this code. Will it work?**

```csharp
public class User 
{
    public static string SiteName = "MySite";
    
    public void PrintName() 
    {
        Console.WriteLine(SiteName);
    }
}

```

- **Answer:** Yes! Instance methods (like `PrintName`) are allowed to access static variables.