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?