Adam Lee
Adam Lee

Reputation: 25778

why we cannot access static members from instance object?

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.

Upvotes: 3

Views: 1812

Answers (2)

Technovation
Technovation

Reputation: 397

because static members are part of a class, but instance members are associated with instances, thats why when you access static members you should access it through the name of the class, this is one of the reasons behind this.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503429

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#.

Upvotes: 9

Related Questions