Sobes.tech
Junior — Middle

How does a class with static methods and fields differ from a regular class with non-static ones?

sobes.tech AI

Answer from AI

A class with static methods and fields differs from a regular class in that its members belong to the class itself, not to a specific object. This means:

  • Static fields and methods are accessible without creating an instance of the class.
  • They are shared among all users of the class — one value of the field is shared by all.
  • You cannot use the this keyword inside static methods, as there is no specific object.

A regular class with non-static members requires creating an object, and each object has its own field values.

Example:

class Counter {
    public static int TotalCount = 0; // shared among all
    public int InstanceCount = 0;     // unique to each object

    public void Increment() {
        InstanceCount++;
        TotalCount++;
    }
}

// Usage:
Counter c1 = new Counter();
c1.Increment();
Counter c2 = new Counter();
c2.Increment();

Console.WriteLine(Counter.TotalCount); // 2
Console.WriteLine(c1.InstanceCount);    // 1
Console.WriteLine(c2.InstanceCount);    // 1