Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why we cannot access static members from instance object?

Tags:

c#

I know that I cannot call static method from instance object

For example

public class A {
  public static int a;
}

A b = new A();
b.a = 5; //which cannot compile

I would like to the know the reason behind this.

like image 763
Adam Lee Avatar asked Feb 21 '26 06:02

Adam Lee


1 Answers

Because it makes no sense, and leads to misleading code. When reading the code, it gives the impression that a is part of the instance referred to by b.

For example, consider:

ClassA a1 = new ClassA();
ClassA a2 = new ClassA();

a1.a = 10;
a2.a = 20;
Console.WriteLine(a1.a);

It would be very weird for that to print 20 instead of 10.

This is allowed in Java, and I've seen it lead to loads of people getting confused by things like:

Thread t = new Thread(...);
t.start();
t.sleep(1000);

... which makes it look like you're making the new thread sleep, when actually Thread.sleep is a static method which makes the existing thread sleep.

I for one am very glad this isn't allowed in C#.

like image 71
Jon Skeet Avatar answered Feb 22 '26 20:02

Jon Skeet