Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a const variable available within a static method?

I have been writing code without realizing WHY I can access constant values within static methods.

Why is it possible to access const values without declaring it as static?

E.g.) It's legal to call IMAGE_FILE_EXTENSION within AddImageToDocument(...)

public abstract class ImageDocumentReplacer : DocumentReplacer
{
    private const string IMAGE_FILE_EXTENSION = ".tif";

    private static void AddImageToDocument(int documentId, string separatedPath)
    {
        Console.WriteLine(IMAGE_FILE_EXTENSION);
    }
}
like image 508
dance2die Avatar asked Aug 11 '09 15:08

dance2die


1 Answers

const members are implicitly static. They belong to the class rather than a specific instance. As a consequence, you can't use this.myConstant but MyClass.myConstant.

Quoting the C# 3.0 specification (section §10.4 Constants):

Even though constants are considered static members, a constant-declaration neither requires nor allows a static modifier. It is an error for the same modifier to appear multiple times in a constant declaration.

like image 169
mmx Avatar answered Sep 19 '22 21:09

mmx