Immutable local 'variables' in C#

asked11 years ago
last updated8 years ago
viewed9.6k times
Up Vote18Down Vote

I'm new to C# (C++ programmer mainly, with Java as a strong second, and some others I use less often); I'm using C# with Unity, but I have a question that seems to be C# related rather than Unity.

I've been moving somewhat towards functional-style programming, i.e. instead of

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

I'd 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'd like to do that in C#, but I've tried this

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

But Mono complains, saying maxGrowth isn't being assigned a 'constant value' - so I'm assuming C#'s const keyword is actually equivalent to 'constexpr' from C++11?

If so, is there a way of doing what I want in C#? Preferably without invoking some container class (unless the compiler is good at making that efficient?).

I assume from what I've read C# is much closer to Java overall than C++ in language; immutable classes rather than const-member functions?