C# public variable as writeable inside the class but readonly outside the class
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;
}
}
}
public class Foo
{
public string Bar { get; private set; }
}
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.