Search code examples
c#fieldautomatic-properties

C# - Difference between Automatic Property and returning a backing field?


Simple question I imagine, but what is the difference between 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?


Solution

  • 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.