I was mildly surprised when the compiler complained about this:
public class UsefulClass
{
public const String RatingName = @\"Ratings\\rating\";
}
publ
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.
Because const in c# are implicitly of static type. And As static members can be accessed only on class member and not on instance, const cannot too.
A "variable" marked const
is a compile time construct, not an instance member. You can access it like you would a static variable:
public void SomeFunc()
{
UsefulClass useful = new UsefulClass();
String rating = UsefulClass.RatingName; // Access as if static
}
That being said, I would personally wrap this into a property if it's meant to be used as you described, like so:
public class UsefulClass
{
private const string ratingName = @"Ratings\rating";
public string RatingName { get { return ratingName; } }
}
This would make your syntax work, but also be a better design, IMO, since it doesn't expose your constants publically.