Welcome to Darren Sim's Playpans Sign in | Join | Help

Properties Processing in C# 3.0

Many a times when you're writing C# code, you'd be asking yourself "Why on earth do I need to include properties when it's just doing nother more then making my fields public"?

Well, there's actually a very valid reason for keeping fields private.

  1. Encapsulation
  2. Many databinding relation operations actually make use of Properties a whole lot!

However, in C# 3.0, it eliminates the need for you to write a whole lot of those code by introducing this feature called "automatic properties". So what it allows you to do is to write

public class Weather
{
     public string City  { get; set; }
     public double Degree { get; set; }
}

instead of

public class Weather
{
     private string _city;
     private string _degree;

     public string City
     {
          get
          {
               return this._city;
          }
          set
          {
               this._city = value;
          }
     }
     public double Degree
     {
          get
          {
               return this._degree;
          }
          set
          {
               this._degree = value;
          }
     }
}

When the new C# compiler encounters an empty get/set property implementation like above, it will now automatically generate a private field for you within your class, and implement a public getter and setter property implementation to it. 

The benefit of this is that from a type-contract perspective, the class looks exactly like it did with our first (more verbose) implementation above.  This means that, unlike public fields, you can in the future add validation logic within your property setter implementation without having to change any external component that references your class. 

Published Sunday, March 11, 2007 12:53 AM by darren.sim
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
required 
(required)