I have a .Net C# class where I need to make a variable public. I need to initialize this variable within a method (not within the constructor). However, I don't want the variable to be modifieable by other classes. Is this possible?
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;
}
}
}