0
0
C Sharp (C#)programming~5 mins

Static members vs instance members in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Static members belong to the class itself, while instance members belong to each object made from the class. This helps organize data and actions that are shared or unique.

When you want a value or method shared by all objects, like a counter for how many objects were created.
When each object needs its own separate data, like a name or age for each person.
When you want to call a method without making an object, like a helper function.
When you want to keep track of something common to all objects, like a setting or limit.
Syntax
C Sharp (C#)
class ClassName {
    static int staticMember; // shared by all
    int instanceMember;      // unique to each object

    static void StaticMethod() { }
    void InstanceMethod() { }
}

Static members use the static keyword.

Instance members do not use static and require an object to access.

Examples
This class counts how many cars are made using a static variable, while each car has its own color.
C Sharp (C#)
class Car {
    public static int numberOfCars = 0; // shared count
    public string color;                // unique color

    public Car(string c) {
        color = c;
        numberOfCars++;
    }
}
Static members are accessed by the class name. Instance members need an object.
C Sharp (C#)
Car.numberOfCars = 5; // Access static member without object
Car myCar = new Car("red");
string carColor = myCar.color; // Access instance member via object
Sample Program

This program shows how static and instance members work. The static dogCount counts all dogs made. Each dog has its own name and can bark.

C Sharp (C#)
using System;

class Dog {
    public static int dogCount = 0;
    public string name;

    public Dog(string dogName) {
        name = dogName;
        dogCount++;
    }

    public static void ShowDogCount() {
        Console.WriteLine($"Total dogs: {dogCount}");
    }

    public void Bark() {
        Console.WriteLine($"{name} says: Woof!");
    }
}

class Program {
    static void Main() {
        Dog.ShowDogCount();
        Dog dog1 = new Dog("Buddy");
        Dog dog2 = new Dog("Max");
        Dog.ShowDogCount();
        dog1.Bark();
        dog2.Bark();
    }
}
OutputSuccess
Important Notes

Static members exist once per class, not per object.

Instance members need an object to be used.

Use static for shared data or helpers, instance for unique object data.

Summary

Static members belong to the class and are shared by all objects.

Instance members belong to each object and hold unique data.

Access static members with the class name; access instance members with an object.