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:
- setting
property = null
callsset
- which call
property = value;
in turn callsset
- 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
Post a Comment