A short notice about static constant in C#

Alex Tumanoff
1 min readDec 7, 2021

Even if you have a lot of experience with some programming language, it does not mean, that from time to time you will feel a little be amazed. I am not an exception.

Until this moment, if someone asked me: “Hey, I am going to make this const to be static. Is it OK?”. I am obviously said: “If you need it, do it”. Unfortunately, it would be the wrong answer.

Imagine such code:

If you try to compile it, you will get this error:

Error CS0504 The constant ‘minutesPerLayer’ cannot be marked static

It happens because constants can not be static in C#.

We can accept it as a law, but we are developers, and the question “Why?” is our favorite.

An explanation of this behavior is simple. Here is the fragment from “С# language specification”:

Even though constants are considered static members, a
constant-declaration neither requires nor allows a static modifier

(page 282)

You can read the C# specification by this link.

What lessons did I learn from this situation?

If something strange happened in your C# code read the language specification :)

--

--