127
votes

I saw something like the following somewhere, and was wondering what it meant. I know they are getters and setters, but want to know why the string Type is defined like this. Thanks for helping me.

public string Type { get; set; }
9
This is called an Auto-Property, have a look at this: msdn.microsoft.com/en-us/library/bb384054.aspx - Allov
This is the definition of a property named "Type", the .NET type of which is System.string. There's nothing more to it. - Jon
I think that he might be confusing the naming of the Auto-Property with the Reflection class System.Type. msdn.microsoft.com/en-us/library/system.type.aspx - eandersson

9 Answers

204
votes

Those are Auto-Implemented Properties (Auto Properties for short).

The compiler will auto-generate the equivalent of the following simple implementation:

private string _type;

public string Type
{
    get { return _type; }
    set { _type = value; }
}
38
votes

That is an auto-property and it is the shorthand notation for this:

private string type;
public string Type
{
  get { return this.type; }
  set { this.type = value; }
}
30
votes

In C# 6:

It is now possible to declare the auto-properties just as a field:

public string FirstName { get; set; } = "Ropert";

Read-Only Auto-Properties

public string FirstName { get;} = "Ropert";
15
votes
public string Type { get; set; } 

is no different than doing

private string _Type;

public string Type
{    
  get { return _Type; }
  set { _Type = value; }
}
8
votes

This means that the compiler defines a backing field at runtime. This is the syntax for auto-implemented properties.

More Information: Auto-Implemented Properties

5
votes

It's an automatically backed property, basically equivalent to:

private string type;
public string Type
{
   get{ return type; }
   set{ type = value; }
}
4
votes

These are called auto properties.

http://msdn.microsoft.com/en-us/library/bb384054.aspx

Functionally (and in terms of the compiled IL), they are the same as properties with backing fields.

3
votes

You can also use a lambda expression

public string Type
{
    get => _type;
    set => _type = value;
}
1
votes

With the release of C# 6, you can now do something like this for private properties.

public constructor()
{
   myProp = "some value";
}

public string myProp { get; }