C# - Difference between Automatic Property and returning a backing field?
Simple question I imagine, but what is the difference between 开发者_JAVA技巧these lines of code:
Code 1
public int Temp { get; set; }
and
Code 2
private int temp;
public int Temp { get { return temp; } }
My understand was that an automatic property as per Code 1 would perform the exact same function as Code 2?
I'm reading Head First C# and I'm finding it hard to understand why it's using two different ways of doing the same thing?
The primary difference between your Code1 and Code2 is that in #1, the property is settable.
You can achieve the same thing using automatic properties, because the setter can be private:
public int Temp { get; private set; }
Automatic properties was added in C#3, and is really just syntactic sugar for the longer version using a field. If you don't need to access the field directly, there is no reason not to use automatic properties. Automatic properties are equivalent to using a field - the compiler generates the field for you, it is just not accessible in code.
The first one is a writable property.
It's equivalent to
private int temp;
public int Temp {
get { return temp; }
set { temp = value; }
}
(except that you can't use the backingfield directly), but it requires 1 line of code instead of five.
When writing classes with 5 or 6 simple properties, auto-properties can make the classes much shorter.
You can make read-only auto-properties by writing
public int Temp { get; private set; }
The "automagic" property is just a "short-hand" notation:
public int Temp { get; set; }
is just a lot simpler to type than
public int Temp
{
get { return _temp; }
set { _temp = value; }
}
but functionally equivalent. Just a nice "shorthand" to improve your productivity, but no additional or magic functionality, really.
If your second example had both a getter and a setter, they would be functionally equivalent.
As it stands now, the first is publicly gett-able but can't be set publicly. You could also achieve the same thing using auto properties:
public int Temp { get; private set; }
And in case you're curious, automatic properties still get a backing private field. That bit is just handled by the compiler for you so that life is easier.
As for the reason why I would use property with a backing field is when I want to do something else when getting or setting the property. For example, a validation routine embedded into the property itself, or caching, etc...
Otherwise, for simple get and set, I'd use the automatic property format. It's more compact and involves less coding which I think it's a good thing.
精彩评论