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.
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#.
See more on this question at Stackoverflow