100 said:
I don't see any reason why c# prohibits calling static method or access
static field using an instance (reference (including *this*) or a name of
the value-type variable)
Because it causes confusion - it makes it appear that it will be called
polymorphically, or have something to do with that particular object,
when in reality it doesn't.
For instance, suppose I could write:
Thread t = new Thread (new ThreadStart(Foo)).Start();
t.Sleep (1000);
What does that second line suggest to you? It would suggest to me that
the author is trying to make the new thread sleep for a second. In
fact, it would make the *current* thread sleep for a second, as
Thread.Sleep is static and *always* applies to the current thread.
Ultimately any variable has exact type at compile time.
I'm not exactly sure what you mean by this, but note that:
Foo x = new Bar();
means that the value of x is a reference to a Bar instance - and
methods called on x may be different to methods called on a Foo
instance - but only when the methods are instance methods. (The
compiler won't actually know that x contains a reference to a Bar.)
In Java you could even do:
Foo x = null;
x.DoSomething();
and it would execute fine - no null pointer exception or anything,
despite the way it *looks* like it's dereferencing x.
AFAIK Managed C++ allows this.
Java allows it to - and it causes confusion. Fortunately Eclipse now
has an optional warning/error to alert you to this.
I was very pleased to see that C# disallows it.