class Counter { public static int count = 0; public int instanceCount = 0; public Counter() { count++; instanceCount++; } } class Program { static void Main() { Counter a = new Counter(); Counter b = new Counter(); System.Console.WriteLine($"Static count: {Counter.count}"); System.Console.WriteLine($"a.instanceCount: {a.instanceCount}"); System.Console.WriteLine($"b.instanceCount: {b.instanceCount}"); } }
The static variable count is shared by all instances, so it increments twice.
The instance variable instanceCount is unique to each object, so each has value 1.
Static members belong to the class itself, so you can access them directly using the class name without creating an object.
class Example { public static int value; static Example() { value = 10; System.Console.WriteLine("Static constructor called"); } public Example() { value += 5; System.Console.WriteLine("Instance constructor called"); } } class Program { static void Main() { System.Console.WriteLine(Example.value); Example e = new Example(); System.Console.WriteLine(Example.value); } }
The static constructor runs first and sets value to 10 and prints a message.
Then Main prints 10.
Creating an instance calls the instance constructor, adds 5 to value, and prints a message.
Finally, value is 15.
class Sample { public int number = 5; public static void ShowNumber() { System.Console.WriteLine(number); } }
The static method ShowNumber tries to access the instance field number without an object.
This causes a compile-time error requiring an object reference.
class Tracker { public static int totalCount = 0; public int instanceCount = 0; public Tracker() { totalCount++; instanceCount++; } public void Increment() { totalCount++; instanceCount++; } } class Program { static void Main() { Tracker t1 = new Tracker(); Tracker t2 = new Tracker(); t1.Increment(); t2.Increment(); System.Console.WriteLine($"Total count: {Tracker.totalCount}"); System.Console.WriteLine($"t1 instance count: {t1.instanceCount}"); System.Console.WriteLine($"t2 instance count: {t2.instanceCount}"); } }
Each constructor call increments totalCount and instanceCount by 1.
Two objects created: totalCount = 2, each instanceCount = 1.
Each Increment call adds 1 to both counts.
Two increments called: totalCount +2, each instanceCount +1.
Final totalCount = 4 (2 from constructors + 2 from increments), each instanceCount = 1 + 1 = 2.