Can we have static constants in C# ?

Can we have constants defined as static ? Is the below line of code valid ?

[sourcecode language=”csharp”]

public static const string NAME = “Yasser”;


Well the answer is a BIG NO !

Try pasting the above code into your visual studio, and it throws the following error.

Explanation : Constants inherently means static. If you have any constant, it’s already static, and therefore you need not ( or rather you CANNOT ) specify it to be static.

const is dealt with at the compile time. Every reference to that constant is replaced by the constant value.

static is very different. It is a variable which exists only once but belongs to all instances of that class. It can be edited unless marked as readonly. It is handled at runtime and not by the compiler.