I'm glad C# doesn't let you access static members 'as though' they were instance members. This avoids a common bug in Java:
Thread t = new Thread(..);
t.sleep(..); //Probably doesn't do what the programmer intended.
On the other hand, it does let you access static members 'through' derived types. Other than operators (where it saves you from writing casts), I can't think of any cases where this is actually helpful. In fact, it actively encourages mistakes such as:
// Nasty surprises ahead - won't throw; does something unintended:
// Creates a HttpWebRequest instead.
var ftpRequest = FtpWebRequest.Create(@"http://www.stackoverflow.com");
// Something seriously wrong here.
var areRefEqual = Dictionary<string, int>.ReferenceEquals(dict1, dict2);
I personally keep committing similar errors over and over when I am searching my way through unfamiliar APIs (I remember starting off with expression trees; I hit BinaryExpression.
in the editor and was wondering why on earth IntelliSense was offering me MakeUnary
as an option).
In my (shortsighted) opinion, this feature:
(IMO, operators are a special case that warrant their own discussion.)
Given that C# is normally a "pit of success" language, why does this feature exist? I can't see its benefits (other than 'discoverability', which could always be solved in the IDE), but I see lots of problems.
Static methods do not use any instance variables of any object of the class they are defined in. Static methods take all the data from parameters and compute something from those parameters, with no reference to variables. We can inherit static methods in Java.
Are static methods inherited? In Java, yes, they are inherited, but you can't override them. If in the child class you provide a new static method with the same signature, you hide the original method.
In Java, static members are those which belongs to the class and you can access these members without instantiating the class. The static keyword can be used with methods, fields, classes (inner/nested), blocks.
Static variables are inherited as long as they're are not hidden by another static variable with the same identifier.
I'd agree this is a misfeature. I don't know how often someone on Stack Overflow has posted code of:
ASCIIEncoding.ASCII
etc... which, while harmless in terms of execution is misleading in terms of reading the code.
Obviously it's too late to remove this "feature" now, although I guess the C# team could introduce a super-verbose warning mode for this and other style issues.
Maybe C#'s successor will improve things...
This is useful in WinForms.
In any control or form, you can write MousePosition
, MouseButtons
, or ModifierKeys
to use the static
members inherited from Control
.
It's still debatable whether it was a good decision.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With