skm
skm

Reputation: 5649

C# Create and initialize (with non-default value) a readonly flaot array?

I need to create a readonly float array and initialize all of its elements with the value 1.0f. I am trying to use the following syntax but it is showing an error, "The modifier readonly is not valid for this item".

int nRows = SomeData.Rows;
int nCols = SomeData.Cols;
readonly float[] myFloatArray = Enumerable.Repeat(1.0f, nRows * nCols).ToArray();

Upvotes: 0

Views: 130

Answers (1)

If you want the content of the array to be readonly, which wouldn't be the case even if you could use the readonly modifier, the closest thing to a readonly array you'll find is a ReadOnlyCollection.

int nRows = SomeData.Rows;
int nCols = SomeData.Cols;
var myFloatArray = Array.AsReadOnly(Enumerable.Repeat(1.0f, nRows * nCols).ToArray());
// var is System.Collections.ObjectModel.ReadOnlyCollection<float>

Upvotes: 1

Related Questions