C# public variable as writeable inside the class but readonly outside the class
Solution 1:
Don't use a field - use a property:
class Foo
{
public string Bar { get; private set; }
}
In this example Foo.Bar
is readable everywhere and writable only by members of Foo
itself.
As a side note, this example is using a C# feature introduced in version 3 called automatically implemented properties. This is syntactical sugar that the compiler will transform into a regular property that has a private backing field like this:
class Foo
{
[CompilerGenerated]
private string <Bar>k__BackingField;
public string Bar
{
[CompilerGenerated]
get
{
return this.<Bar>k__BackingField;
}
[CompilerGenerated]
private set
{
this.<Bar>k__BackingField = value;
}
}
}
Solution 2:
public class Foo
{
public string Bar { get; private set; }
}
Solution 3:
You have to use a property for this. If you are fine with an automatic getter/setter implementation, this will work:
public string SomeProperty { get; private set; }
Note that you should not expose fields as public anyway, except in some limited circumstances. Use a property instead.
Solution 4:
Sure. Make it a property, and make the setter private:
public Int32 SomeVariable { get; private set; }
Then to set it (from within some method in the class):
SomeVariable = 5;