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?
public class Foo
{
public string Bar { get; private set; }
}
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;
}
}
}
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.
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