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);
    }
}
                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
staticmembers, a constant-declaration neither requires nor allows astaticmodifier. It is an error for the same modifier to appear multiple times in a constant declaration.
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