I was mildly surprised when the compiler complained about this:
public class UsefulClass { public const String RatingName = @"Ratings\rating"; } public class OtherClass { public void SomeFunc() { UsefulClass useful = new UsefulClass(); String rating = useful.RatingName; } }
Compiler says, "Static member cannot be accessed with an instance reference; qualify it with a type name instead"
This isn't a problem, String rating = UsefulClass.RatingName;
works fine. I'm just curious what the thinking is behind this? I have an instance of a public class with a public constant on it, why can't I get the data this way?
Because constants just aren't instance members; they're statically bound to their respective types. In the same way you can't invoke static methods using instances, you can't access class constants using instances.
If you need to get a constant off an instance without knowing its type first-hand, I suppose you could do it with reflection based on its type.
If you're trying to add a member that can't be modified but pertains to instances, you probably want read-only fields or properties instead.
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