Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Duplicated) Difference between 'public int x;' and 'public int x { get; set; }

What is the difference, if any, between

public int x;

and

public int x { get; set; }

?

like image 350
valentin Avatar asked Nov 09 '13 20:11

valentin


1 Answers

The first one is called a field. The second one is a property, in this case an auto-implemented property.

Properties act like fields but use a getter and a setter function to retrive and set the value. Another way of writing the above property is as follows:

private int _x;
public int X
{
    get
    {
        return _x;
    }
    set
    {
        _x = value;
    }
}

The variable _x in this case is called a backing field. With an auto-implemented property you can't access the backing field or customize code in the getter/setter, but if you don't need to than it's shorter and more succinct.

As a rule in C# most of the time any public member should be exposed as a property instead of a field.

like image 182
Trevor Elliott Avatar answered Oct 17 '22 17:10

Trevor Elliott