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

后端 未结 9 1727
说谎
说谎 2020-12-09 14:52

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

9条回答
  •  旧时难觅i
    2020-12-09 15:17

    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 k__BackingField;
    
        public string Bar
        {
            [CompilerGenerated]
            get
            {
                return this.k__BackingField;
            }
            [CompilerGenerated]
            private set
            {
                this.k__BackingField = value;
            }
        }
    }
    

提交回复
热议问题