tags:

views:

234

answers:

5

I see this quiet often in C# documentation. But what does it do?

public class Car
{
   public Name { get; set; }
}
+6  A: 

It's an automatic read-write property. It's a C# 3.0 addition. Something like:

public class Car {
    private string name;
    public string Name { get { return name; } set { name = value; } }
}

except that you can't directly access the backing field.

Mehrdad Afshari
+11  A: 

It is shorthand for:

private string _name;

public string Name
{
    get { return _name; }
    set { _name = value; }
}

The compiler generates the member variable. This is called an automatic property.

Bryan Watts
... although the name of the field is actually an "unspeakable" name (e.g. `<>__name`) which is invalid as a C# identifier. This stops you from directly accessing the field from your code. The specification term is "automatically implemented property" but most people do indeed call it an automatic property :)
Jon Skeet
Ah Jon, your pedantism is greatly appreciated. Thanks for weighing in :-)
Bryan Watts
It's "pedantry" ;)
Coder 42
Either or: http://dictionary.reference.com/browse/pedantism Man us programmers are weird.
Bryan Watts
+1  A: 

It is the equivilent of doing:

private string _Text;

public string Text 
{
    get { return _Text; }
    set { _Text = value; }
}

Except you don't have access to the private variable while inside the class.

Darthg8r
+1  A: 

It's called an Auto-Implemented Property and is new to C# 3.0. It's a cleaner syntax when your access to the property doesn't need any special behavior or validation. It's similar in function to:

public class Car
{
  private string _name;
  public string Name
  {
    get { return _name; }
    set {_name = value; }
  }
}

So it saves a fair amount of code, but leaves you the option later to modify the accessor logic if behavior or rules need to change.

Jeff Donnici
+1  A: 

Auto-Implemented Properties

SUMMARY:In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors.

adatapost