Why can't structs be declared as const? [duplicate]
Because the value type constructor might do anything -- for example, switch logic based on the time of day. Constant value types makes sense intellectually, but it simply cannot work on custom value types in practice due to the flexibility of constructors to do whatever they please. (Remember that constants are evaluated at compile time, which means your constructor would have to be run at compile time.)
Const in C# means it can be determined at compile time, which is why only very primitive types such as int
and string
can be a const.
If you are coming from a C background, the readonly
keyword might better suit you.
For the C# compiler to produce a const
value of a structure type it must know what values should go in all its fields. The C# compiler intrinsically knows how to initialize the fields of certain types like Decimal
, but for most value types it has no such knowledge.
It would be possible for a compiler to provide a means of declaring constant values of a structure type in contexts where all of the struct
fields were exposed. If a structure's fields were private
, constants of that type could then be declared only within the structure; if the fields were internal
, constants could be declared anywhere within the assembly; if public
, they could be declared anywhere.
Although I would like to see such a feature, I do not expect any mainstream .net languages to implement it. Named constants of types the compiler inherently knows about can participate in other constant expressions, whereas static readonly
variables cannot. If NumRows
is a constant equal to 4, an expression like Arr[3*NumRows+7]
can be replaced by Arr[19]
even if NumRows
is defined in an outside assembly. This gives such constants a substantial advantage over static readonly
variables. If, however, a constant is of a type that a compiler does not intrinsically recognize, it would have very limited ability to participate in any constant expressions, effectively negating the advantage of its being a constant in the first place. If a value-type constant had an exposed field, it would be possible for a compiler to use the value of that field as a constant, but since the creators of .net languages are philosophically opposed to structures with exposed fields, I would not expect them to allow such usage even if they could.
There would be some potential use cases for favoring constants over static readonly
variables, but many such cases can be handled acceptably using existing types. For example, a library might expose a const Int64
to encode information about its version, and use that value as a default parameter value for a GetLinkedVersionInfo
method. The value in question would get "baked into" the calling code when it was compiled, thus allowing the method to report what version of the library the caller was linked with, and possibly identify whether there are any compatibility problems with the version it's running.