VC++ MVP 2006, C# MVP 2007 Ravi Bhavnani's .NET bits
A compendium of scribblings, hacks, and things .NET

Linkworthy
  • The CodeProject
  • CodePlex
  • Channel 9
  • The Lab with Leo Laporte
  •  
    C# 3.0 - Automatic properties
    Much ado about nothing?
    by Ravi Bhavnani, 14 Jan 2008
    Home  All articles

    C# 3.0 introduces the concept of automatic (or more correctly, auto-implemented) properties.  Being that the restrictions on this feature make it applicable to only few situations, I'm left wondering why the good folks at Redmond chose to make this a feature of the language (i.e. the compiler) instead of the IDE.

    An automatic property looks like this:

      1   public int Id {
      2     get;
      3     set;
      4   }

    Behind the scenes, the C# compiler converts this to something like:

      1   public int Id {
      2     get { return _id; }
      3     set { _id = value; }
      4   }
      5 
      6   // Compiler generated field
      7   private int _id;

    Except that:

    • The generated field isn't called _id; it has an internal name that you don't know.
    • The generated field can't be accessed by your code.
    • Automatic properties can't have attributes.

    I understand the need for relieving the developer from manually writing hundreds of lines of code that look like this:

      1   // Public property
      2   public int Prop1 {
      3     get { return _prop1; }
      4     set { _prop1 = value; }
      5   }
      6   // Private field
      7   private int _prop1;
      8 
      9   // Public property
     10   public string Prop2 {
     11     get { return _prop2; }
     12     set { _prop2 = value; }
     13   }
     14   // Private field
     15   private string _prop2;
     16 
     17   ... etc ...

    but the restrictions on automated properties make them less useful than I'd like.  Perhaps this generation of code could have been better purposed by the IDE?

     

    Most of the drivel at this site is copyright Ravi Bhavnani.
    Questions or comments?  Send mail to ravib@ravib.com