0

Consider the following code :

   public class Order
    {
        public int OrderID { get; set; }
        public DateTime OrderDate { get; set; }
        public decimal Total { get; set; }
    }

I don't understand what does the { get; set; } means .

I usually use get and set like this :

class Person
{
    private string name;  // the name field 
    public string Name    // the Name property
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
        }
    }
}

So, what does the { get; set; } means ?

Thanx

JAN
  • 21,236
  • 66
  • 181
  • 318

2 Answers2

7

Using { get; set; } by itself translates exactly to what you usually use.. its just shorthand for it.

The compiler creates an automatic backing field.

So this:

public string FirstName { get; set; }

..is compiled to this:

private string _firstName;

public string FirstName {
    get {
        return _firstName;
    }
    set {
        _firstName = value;
    }
}

This all happens at compile time, therefore you cannot directly access the backing field (because it isn't actually available until the code is compiled).

After the compiler converts the above.. automatic properties are actually turned into methods.

So the above is turned into this:

public void set_FirstName(string value) {
    _firstName = value;
}

public string get_FirstName() {
    return _firstName;
}

Then some IL is produced to notify tools like Visual Studio that they are properties and not methods.. somewhat like this:

.property instance string FirstName() {
    .get instance string YourClass::get_FirstName()
    .set instance void YourClass::set_FirstName(System.String)
}
Kyle
  • 6,500
  • 2
  • 31
  • 41
Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
6

These are auto implemented properties.

Compiler will extend it with a backing field for you. However, you can't access that field directly.

In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects. When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.

Read more on MSDN: Auto-Implemented Properties (C# Programming Guide)

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263