Reputation: 36985
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);
}
}
Upvotes: 7
Views: 2210
Reputation: 422320
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 astatic
modifier. It is an error for the same modifier to appear multiple times in a constant declaration.
Upvotes: 19
Reputation: 346566
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)
Upvotes: 2
Reputation: 19765
I would expect that, since a constant can't change instance-to-instance, that makes them safe to access from a static method.
Upvotes: 1