Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-properties with or without backing field - preference?

I know that when using auto-properties, the compiler creates its own backing field behind the screen. However, in many programs I read to learn from, I see people explicitly write

private int _backingField;

public int Property { get { return _backingField; } }

What is the difference between above, and below?

public int Property { get; private set; }

I understand that its obvious to use the property when you actually have side-effects in the getter or setter, but that's often not the case. Also, I understand that you have to explicitly use the backing field in the case of structs, you can't access their members via properties.

The only difference I have been able to find is that the way of calling the value is different inside the class it is defined in. Is it then simple preference, or is there something more to calling a value through its property or by directly accessing the field? Simple conventions?

like image 633
Taelia Avatar asked Mar 10 '12 11:03

Taelia


1 Answers

There's not much difference between those two snippets - you can't pass a property by reference, for example, but that's rarely an issue. However, if you want the field to be readonly, like this:

private readonly int _backingField;    
public int Property { get { return _backingField; } }

then there's a difference. The code I've written above prevents the value from being changed elsewhere within the class, making it clear that this is really meant to be immutable. I'd really like to be able to declare a read-only field with a read-only automatically implement property, settable only within the constructor - but that's not available at the moment.

This is rather confusing, by the way:

Also, I understand that you have to explicitly use the backing field in the case of structs, you can't access their members via properties.

What do you mean? You can definitely use properties within structs. Are you talking about backing fields which are mutable structs, i.e. the difference between:

foo.someField.X = 10;

and

foo.SomeProperty.X = 10;

? If so, I normally avoid that being an issue by making my structs immutable to start with :)

like image 163
Jon Skeet Avatar answered Oct 23 '22 15:10

Jon Skeet