Reputation: 18600
In C# .NET, why can't I access constants in a class with the 'this' keyword?
Example:
public class MyTest
{
public const string HI = "Hello";
public void TestMethod()
{
string filler;
filler = this.HI; //Won't work.
filler = HI //Works.
}
}
Upvotes: 9
Views: 1181
Reputation: 723498
Because class constants aren't instance members; they're class members. The this
keyword refers to an object, not the class, so you can't use it to refer to class constants.
This applies whether you're accessing the constant within a static or instance method in your class.
Upvotes: 14
Reputation: 100638
Because constants are part of the class, you need to use the class name:
filler = MyTest.HI;
Upvotes: 3
Reputation: 17638
A const item is implicitly static. That means it belongs to the class and not the members of the class.
Upvotes: 2