c# - Auto-properties with or without backing field - preference? -


i know when using auto-properties, compiler creates own backing field behind screen. however, in many programs read learn from, see people explicitly write

private int _backingfield;  public int property { { return _backingfield; } } 

what difference between above, , below?

public int property { get; private set; } 

i understand obvious use property when have side-effects in getter or setter, that's not case. also, understand have explicitly use backing field in case of structs, can't access members via properties.

the difference have been able find way of calling value different inside class defined in. simple preference, or there more calling value through property or directly accessing field? simple conventions?

there's not difference between 2 snippets - can't pass property reference, example, that's issue. however, if want field readonly, this:

private readonly int _backingfield;     public int property { { return _backingfield; } } 

then there's difference. code i've written above prevents value being changed elsewhere within class, making clear meant immutable. i'd able declare read-only field read-only automatically implement property, settable within constructor - that's not available @ moment.

this rather confusing, way:

also, understand have explicitly use backing field in case of structs, can't access members via properties.

what mean? can use properties within structs. talking backing fields are mutable structs, i.e. difference between:

foo.somefield.x = 10; 

and

foo.someproperty.x = 10; 

? if so, avoid being issue making structs immutable start :)


Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -