Immutable local variables in C #

I am new to C # (a C ++ programmer is mostly with Java as a strong second, and some others I use less often); I am using C # with Unity, but I have a question that seems to be related to C #, not Unity.

I made some progress towards programming in a functional style, i.e. instead

// C++ int someFunction(int a) { int someCalculatedValue = a * a; someCalculatedValue /= 2; return someCalculatedValue * 3; } 

I would do something like this

 // Again C++ int someFunction(int a) { const int inputSquared = a * a; const int inputSquaredHalved = inputSquared / 2; return inputSquaredHalved * 3; } 

Now I would like to do it in C #, but I tried this

 // C# const float maxGrowth = GrowthRate * Time.deltaTime; 

But Mono complains, saying that maxGrowth is not assigned a "constant value" - so I assume that the C # const keyword is actually equivalent to the "constexpr" from C ++ 11?

If so, is there a way to do what I want in C #? Preferably without calling some container class (if the compiler can't do this efficiently?).

I assume that with what I read, C # is much closer to Java in general than C ++ in the language; immutable classes, not constant functions?

+6
source share
2 answers

readonly

When a field declaration contains a readonly modifier, assignments to fields entered by the declaration can only be performed as part of the declaration or in the constructor of the same class.

There is no equivalent for local variables. You will need to make this field.

+6
source

You can declare your local variable as an iteration variable. Iteration variables are read-only. Yes, this is ugly.

 foreach (float maxGrowth in new[] { GrowthRate * Time.deltaTime }) { maxGrowth = 0; // won't compile: "error CS1656: Cannot assign to 'maxGrowth' because it is a 'foreach iteration variable'" } 
+10
source

Source: https://habr.com/ru/post/971309/


All Articles