Why do I need a private field that is exposed via public property?

前端 未结 11 738
天涯浪人
天涯浪人 2020-12-11 11:41

I\'m comming from Java world mainly. So, C# properties do look nice.

I know that with C# 3.0 or above I can use Automatic Properties. I like it even more :).

11条回答
  •  青春惊慌失措
    2020-12-11 11:57

    In the simple case nothing. However you are making it easier to maintain the interface to the class should the implementation of either of those two methods require additional code.

    Take for instance if you need to add a changing event to the setter.

       public int Age {
    
         get { return age; }
         set { 
              if ( age != value) {
                  age = value; 
                  OnAgeChanged();
              }
          }     
       }
    

    You can do this with a property and not break client code. A field does not have this advantage.

提交回复
热议问题