Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C# not allow const and static on the same line?

Why does C# not allow const and static on the same line? In Java, you must declare a field as 'static' and 'final' to act as a constant. Why does C# not let you declare const's as final?

I make the further distinction that in Java, every interface is public and abstract, whether this is explicitly declared or not. Aren't const's effectively static in nature? WHy does C# balk at this?

like image 463
Cuga Avatar asked Sep 07 '25 14:09

Cuga


1 Answers

const and static really do mean different things, different storage mechanism, different initialisation. static is read/write, therefore must have memory allocated for storage and must be initialised at runtime. A static can be initialised with a literal value or an expression. In contrast, a const is immutable and must be initialised with a compile time constant (typically a literal value, or an expression that can be fully evaluated at compile time). The value is known at compile time so it can be embedded directly in the generated code, therefore requires no storage to be allocated at runtime.

like image 161
Tim Long Avatar answered Sep 09 '25 03:09

Tim Long