Reputation: 7223
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; }
Upvotes: 145
Views: 335957
Reputation: 1979
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; }
Upvotes: 1
Reputation: 2548
public string Type { get; set; }
is no different than doing
private string _Type;
public string Type
{
get { return _Type; }
set { _Type = value; }
}
Upvotes: 21
Reputation: 5681
This means that the compiler defines a backing field at runtime. This is the syntax for auto-implemented properties.
More Information: Auto-Implemented Properties
Upvotes: 8
Reputation: 136174
It's an automatically backed property, basically equivalent to:
private string type;
public string Type
{
get{ return type; }
set{ type = value; }
}
Upvotes: 5
Reputation: 17131
You can also use a lambda expression
public string Type
{
get => _type;
set => _type = value;
}
Upvotes: 5
Reputation: 11072
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";
Upvotes: 36
Reputation: 25742
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; }
}
Upvotes: 42
Reputation: 245479
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; }
}
Upvotes: 227
Reputation: 36583
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.
Upvotes: 4