Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use 'this.' in C# to access my class constant?

Tags:

c#

.net

constants

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.
    }
}
like image 526
contactmatt Avatar asked Apr 05 '11 14:04

contactmatt


3 Answers

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.

like image 179
BoltClock Avatar answered Nov 15 '22 21:11

BoltClock


Constants are implicitly static.

like image 4
Dan Puzey Avatar answered Nov 15 '22 20:11

Dan Puzey


Because constants are part of the class, you need to use the class name:

filler = MyTest.HI;
like image 3
Ferruccio Avatar answered Nov 15 '22 21:11

Ferruccio