c# - Why do we create a private variable inside a class and then set property? -
why create private variable inside class , make public property out of on following lines in c#? not concept of getting , setting property.
i mean why
public class myclass { private string _myproperty; public string myproperty { { return _myproperty; } set { _myproperty = value; } }
or
public class myclass { public string myproperty {get;set;} }
my question similar one: why need create class variables , set property?
the above thread didn't seem solve problem. somebody, please elaborate on :
- why create private variables first , make public properties out of it? why not single step?
- what need 'get' , 'set'? why 2 approaches use it, differences?
the question's answer might long. if spend valuable time explain single point properly, i'll more obliged. in advance :)
why create private variables first , make properties out of it? why not single step?
you use private variable when want sort of validation before setting property, or abstract away happening inside class regards property. example, if want given variable in range:
private int foo; public int foo { { return foo; } set { if (value < 0 || value > 10) { throw new argumentoutofrangeexception(value); } foo = value; } }
what need 'get' , 'set' , why 2 approaches use it?
c#-3.0 brought auto-properties, because msft saw alot of people use properties "possibility 1 day i'll want validate variables or change internal implementation". exposing property instead of variable allows add code validation later, without breaking existing "contract" caller of property.
@jonskeet spells nicely, flat out in c# in depth (thanks @sriram):
- there's more fine-grained access control properties.
- need publicly gettable want set protected access? no problem (from c# 2 onwards, @ least).
- want break debugger whenever value changes? add breakpoint in setter.
- want log access? add logging getter.
- properties used data binding; fields aren't.
Comments
Post a Comment