Wednesday, March 12, 2008

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

No comments: