Do we need backing fields in C# properties? -


note: not question auto-implemented properties. auto-implemented properties properties without logic in getters , setters while stated in code there logic. not duplicate since question different, , answer. however, insert specific logic code clearer.


i see lot of this:

private int _age; public object age {         {         if(user.isauthorized)         {             return _age;         }     }     set     {         if(value > 0 && value < 120)         {             _backingfield = value;         }         else         {             console.write("non-valid age");         }     } } 

but why need backing field? why no returning property shown below?

public object age {         {         if(user.isauthorized)         {             return age;         }     }     set     {         if(value > 0 && value < 120)         {             age = value;         }         else         {             console.write("non-valid age");         }     } } 

well, returning property itself leads stack overflow exception:

public object property  {         {         return property;     }     set     {         property = value;     } } 

imagine

  myobject o = new myobject();    // cause stack overflow exception   o.property = null; 

it easy see why:

  1. setting property = null calls set
  2. which call property = value; in turn calls set
  3. which call property = value;... , on.

so if property stores value value should stored in field (you need field), can't use property store itself. if want shorten code, put (auto properties):

  public object property {      get; // let .net create backing field     set;   } 

Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -