C# - Static vs. Const

J

JPS

Can someone please refresh my memory here, but what is the difference
between a Static variable (or method) and a Const?
 
B

Ben Voigt [C++ MVP]

Martin said:

Meaning that it's shared between all instances of the class.
const can be applied to members or to variables to indicate that the
value cannot be modified:
http://msdn.microsoft.com/en-us/library/e6w8fe1b(VS.80).aspx

In C# it means both more and less that simply that the value won't be
modified.

More, because it actually has to be a compile-time literal, and the compiler
is allowed to substitute the literal value everywhere the const variable
appears. In essence, the const field exists only in the metadata.

Less, because you can't mark anything as "const" except static fields,
unlike C++ where variables and access through pointers can be marked "const"
(can't modify the value) anywhere they appear, including function arguments
and even the "this" pointer.

C#'s "readonly" comes a lot closer to a simple marker "cannot be modified
after creation".
 
P

puzzlecracker

Less, because you can't mark anything as "const" except static fields,
unlike C++ where variables and access through pointers can be marked "const"
(can't modify the value) anywhere they appear, including function arguments
and even the "this" pointer.

I don't think you have to declare a field static if you specify const.
I believe compilers deduce that automatically.

correct me if I am wrong.
 
B

Ben Voigt [C++ MVP]

puzzlecracker said:
I don't think you have to declare a field static if you specify const.
I believe compilers deduce that automatically.

correct me if I am wrong.

No, in fact you can't use the "static" and "const" keywords together. But
whenever you use "const", you get a static member.
 
B

Ben Voigt [C++ MVP]

Peter said:
[...]
Less, because you can't mark anything as "const" except static
fields, unlike C++ where variables and access through pointers can
be marked "const"
(can't modify the value) anywhere they appear, including function
arguments
and even the "this" pointer.

Small nit: you can mark local variables as "const" as well.

Even smaller nit: they aren't actually variables at that point (I think the
C# compiler will totally remove local constants during the compile process,
not even leaving metadata). The expression has to be a compile-time
literal, which is quite different from C and C++ where const means you can
have a run-time calculation but the variable can't be changed after it is
initialized.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top