Why can Array.Length and Array.Count() not be assigned to const values?
I wanted to follow some excellent C++ advice of calculating the array length once and then using a value without having to call a function like so:
Instead of:
for( int i = 0; i < arr.length; ++i )
I write
const int size = arr.length; // or arr.Count()
for( int i = 0;开发者_开发知识库 i < size; ++i )
After reading a different thread (Is it costly to do array.length or list.count in a loop) I noticed that the performance gain is moot and that this is C# and not C++.
The second reason for this was to initialize my array with a value:
const int size = arr.Length;
int[] primes_ = new int[size];
So my question is this:
Why can't I declare this anyway? It spits me the error:
Error 2 The expression being assigned to 'length' must be constant
Which is very confusing because my value IS constant. However, when I remove the const
, poof goes the message. ...What?
The initialization of Length reads:
public int Length {get;}
from MSDN. Which is especially confusing because my last question (Get-Set Accessor functionality differs on existence of get-set keyword) explicitly gave me the answer of "It's not possible to declare only get and leave set absent."
It's not clear to my why I can declare int size = arr.Length
, but not const int size = arr.Length
. Why is this so?
The const
keyword requires the value to be known at compile time - the .Net compiler cannot determine the value of arr.length
when you compile the code, so you can't assign it to a const
.
With regard to your last question about getters and setters - you must declare both only if you use the short cut syntax: i.e. private long n { get; private set; }
. If you use the full, verbose property declaration with a local field, you can declare just a get:
private long _n = 0;
private long N { get { return _n; } }
Definition with const
in C# requires an initializer that can be evaluated at compile time.
Look here.
You can use readonly
精彩评论