contactmatt
contactmatt

Reputation: 18600

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

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

Answers (4)

BoltClock
BoltClock

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

Ferruccio
Ferruccio

Reputation: 100638

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

filler = MyTest.HI;

Upvotes: 3

Daniel Rose
Daniel Rose

Reputation: 17638

A const item is implicitly static. That means it belongs to the class and not the members of the class.

Upvotes: 2

Dan Puzey
Dan Puzey

Reputation: 34200

Constants are implicitly static.

Upvotes: 4

Related Questions