I'm new to the C# world and I can't find a method to declare read only variable in C# (something like declaring "const" variable in c++). Is there one?
I'll give you an example:
...
int f() { return x; } // x is not const member
...
void g() {
int readOnlyVar = f(); // is there a method to declare readOnlyVar as read only or const
// Some code in which I want to restrict access to readOnlyVar to read only
}
The square brackets around =value mean that the assignment of a value is not always necessary. For instance, if the variable had previously been created and assigned a value, and you now want to make it read-only (and not change its current value), do not use =value.
Points to Remember while working with Read-Only Variable in C#: The variable which is created by using the readonly keyword is known as a read-only variable in C#. The read-only variable's value cannot be modified once after its initialization.
In C#, a readonly keyword is a modifier which is used in the following ways: 1. Readonly Fields: In C#, you are allowed to declare a field using readonly modifier. It indicates that the assignment to the fields is only the part of the declaration or in a constructor to the same class.
There isn't an identical analogue.
The readonly
keyword allows the variable value to be mutated, but only in a constructor.
The const
keyword means the value cannot mutate and needs to be a compile time constant and can only be one of the following types: sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, an enum-type, or a reference-type. (C# 4.0 spec §10.4).
And in c#, readonly
only applies to fields and cannot be applied to local variables.
No, there exists no solution for your code-example.
const
in C# is for compile-time constants and since your variable gets its value from a function, it's not known at compile-time.
The readonly
keyword does kind of what you're looking for, but that's only for member variables in classes (and only allows variables to be set in the constructor of the class).
But, on the other hand, why would you ever need it? If your function is very long, it should be refactored into smaller functions. If it's not very long, then why would you need to enforce a rule like this? Just don't assign to readOnlyVar
is probably my best suggestion for you I'm afraid.
There are two ways to set a variable as read only.
public class ClassA
{
private const int I = 5;
private readonly int J = 5;
}
The const keyword will set the value at compile time. The readonly keyword will set the value at construction. So, if you need different values for each instance, use readonly. Otherwise use const.
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