C# 3.0 automatic properties…
I am a firm believer in encapsulation so I do not like to have public fields instead of public property gets and sets in my code. So here is how I used to write classes in C# 2.0.
public class Person {
private string _firstName;
private string _lastName;
private int _age;
public string FirstName {
get {
return _firstName;
}
set {
_firstName = value;
}
}
public string LastName {
get {
return _lastName;
}
set {
_lastName = value;
}
}
public int Age {
get {
return _age;
}
set {
_age = value;
}
}
}
Now C# 3.0 has automatic properties so I can just write…
public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
Man is that cool! Great for the lazy coder in all of us. For more details see Scott Guthrie’s blog post
Filed under: Esoterica





Looks like another name for public fields to me and more typing. What’s the advantage?
Well it really does generate the same code as a property let or get. When the code is compiled by the to IL the private member variable is genreated automatically. This member variable truly does not exist until the code is compiled so even code local to the class mus go through the set/get routines. I can’t count how many times I have had code that accessed the meber variable directly and had to chase it down. This is gauranted encapsulation and keeps you honest.