Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# public variable as writeable inside the class but readonly outside the class

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?

like image 939
MikeTWebb Avatar asked Jan 11 '11 20:01

MikeTWebb


3 Answers

public class Foo
{
  public string Bar { get; private set; } 
}
like image 45
3Dave Avatar answered Nov 15 '22 15:11

3Dave


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;
        }
    }
}
like image 158
Andrew Hare Avatar answered Nov 15 '22 15:11

Andrew Hare


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.

like image 7
cdhowie Avatar answered Nov 15 '22 14:11

cdhowie