[LINQ via C# series]
As the fundamental of LINQ, This chapter will explain the new language features of C# 3.0, all of which are syntactic sugars.
This part is about the automatic property.
In C# 2.0 a property can be declared like this:
public class Person
{
private string _name;
public string Name
{
get
{
return this._name;
}
set
{
this._name = value;
}
}
}
And in C# 3.0 we can use automatic property:
public class Person
{
public string Name
{
get;
set;
}
}
Then the compiler will generate the field definition and accessor definitions for us. The above code will be compiled into:
public class Person
{
[CompilerGenerated]
private string <Name>k__BackingField;
public string Name
{
[CompilerGenerated]
get
{
string str = this.<Name>k__BackingField;
return str;
}
[CompilerGenerated]
set
{
this.<Name>k__BackingField = value;
}
}
}
It works the same as the first sample. You may noticed:
Another sample is, for the purpose of atomic typing, we can write code like this:
public class Person
{
public Person(string name)
{
// Validates the parameter.
this.Name = name;
}
public string Name
{
get;
private set;
}
}