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.
}
}
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.
Constants are implicitly static
.
Because constants are part of the class, you need to use the class name:
filler = MyTest.HI;
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