devfreak devfreak - 1 month ago 7
C# Question

How can make a variable (not class member) "read only" in C#

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
}

Answer

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.

Comments