Reputation: 170489
With a lot of C++ background I've got used to writing the following:
const int count = ...; //some non-trivial stuff here
for( int i = 0; i < count; i++ ) {
...
}
and I expected that the same would work fine in C#. However...
byte[] buffer = new byte[4];
const int count = buffer.Length;
produces error CS0133: The expression being assigned to 'count' must be constant.
I don't get it. Why is that invalid? int
is a value type, isn't it? Why can't I assign a value and make the variable unchangeable this way?
Upvotes: 28
Views: 18298
Reputation: 69
Also note that in C#, the modifier readonly
is only available for member variables, not for local variables (i.e. defined inside a method).
Microsoft probably should have been more specific in the C# reference guide:
http://msdn.microsoft.com/en-us/library/acdd6hb7.aspx
Upvotes: 2
Reputation: 247909
Because const
in C# is a lot more const
than const
in C++. ;)
In C#, const
is used to denote a compile-time constant expression. It'd be similar to this C++ code:
enum {
count = buffer.Length;
}
Because buffer.Length
is evaluated at runtime, it is not a constant expression, and so this would produce a compile error.
C# has a readonly
keyword which is a bit more similar to C++'s const
. (It's still much more limited though, and there is no such thing as const-correctness in C#)
Upvotes: 30
Reputation: 1500055
const
is meant to represent a compile-time constant... not just a read-only value.
You can't specify read-only but non-compile-time-constant local variables in C#, I'm afraid. Some local variables are inherently read-only - such as the iteration variable in a foreach
loop and any variables declared in the fisrt part of a using
statement. However, you can't create your own read-only variables.
If you use const
within a method, that effectively replaces any usage of that identifier with the compile-time constant value. Personally I've rarely seen this used in real C# code.
Upvotes: 12