Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can't a static member be reached through an instance name?

say I have:

 class Test
 {
      public static int Hello = 5;
 }

This obviously works:

 int j = Test.Hello;

But why should this not work?

 Test test = new Test();
 int j = test.Hello;

The instance could not have a member equally named, so I don't see how this could be ambiguous or unresolvable for a compiler.

Anyone any idea why this is?

EDIT: Is there any other technical reason why this should be OTHER than the language designers choosing this for readability/clarity/aesthetics/etc?

like image 934
Toad Avatar asked Mar 19 '10 12:03

Toad


1 Answers

Another angle:

Suppose this were possible. What would you then like the result to be when a static member is accessed through an instance variable which is null ? Would you like a null reference exception (but why, since no instance should be required to obtain a static member)? Or would you like it to work (in which case you would have the odd situation that some invocations on this instance variable worked, but some didn't)? Either way has problems.

like image 148
AakashM Avatar answered Nov 09 '22 00:11

AakashM