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?
By default, all variables and references are immutable. Mutable variables and references are explicitly created with the mut keyword. Constant items in Rust are always immutable.
An immutable object is defined as an object that cannot be changed after it has been created. For many use cases, such as Data Transfer Objects, immutability is a desirable feature. This article discusses why we might want to take advantage of immutability and how we can implement immutability in C#.
All built-in value types like int, double, etc., are mutable types and can be made immutable by adding the modifier "readonly" before the variables. If a mutable reference type is specified with a readonly modifier, the C# compiler generates a warning.
Immutability of stringsString objects are immutable: they can't be changed after they've been created. All of the String methods and C# operators that appear to modify a string actually return the results in a new string object.
You can declare your local variable as an iteration variable. Iteration variables are readonly. Yes, it 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'"
}
readonly
When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.
There's no equivalent for local variables. You'll have to make it a field.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With