Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't read a const in a class instance?

Tags:

c#

constants

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?

like image 341
TomDestry Avatar asked Jul 29 '11 00:07

TomDestry


Video Answer


1 Answers

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.

like image 176
BoltClock Avatar answered Oct 14 '22 14:10

BoltClock