views:

122

answers:

3

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);
    }
}
+13  A: 

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.

Mehrdad Afshari
Just adding: Try using static const, and your compiler will probably complain ;)
Samuel Carrijo
@Samuel : Yes, siree it does!
Sung Meister
I never thought of const being *implicitly* static... Thanks Mehrdad.
Sung Meister
+1  A: 

I would expect that, since a constant can't change instance-to-instance, that makes them safe to access from a static method.

n8wrl
+2  A: 

Why should it not be possible? Since the value is fixed at compile time, there is no possible inconsistency (as there would be with variables or readonly fields that can be initialized to different values for different instances at runtime)

Michael Borgwardt