Automatic Properties in VS 2008 and C# 3.0

.NET Musings

Wandering thoughts of a developer, architect, speaker, and trainer


Automatic Properties in VS 2008 and C# 3.0

There are a lot of new features in C# that aren't new to the .Net Framework.  Automatic properties is one of these features that are indeed very nice, but under the covers is really the compiler "catching up".  The see the IL side, check out this post.

Automatic properties are all about saving typing (along with Object Initialization and Implicitly Type local variables).  Most of the time, this new construct will be very handy.

Instead of writing this for a property:

  1: private string _testString;
  2: public string TestString
  3: {
  4:    get { return _testString; }
  5:    set { _testString = value;}

  6: }

We can shorten it to this:

  1: public string TestString { get; set; }

There are two main limitations:

  • You can not have read-only or write-only properties.  There must be a "get" and a "set".
  • You can not do any initialization (or have any other code) in the get/set methods.  So, if you need to initialize the property (e.g. when the property is a heap variable such as a custom object) you will have to do it somewhere else (like the constructor).

When accessing the property from within your class, you would use the PropertyName, and not the backing field (which is a better practice anyway).

  1: public Class1(string testString)
  2: {
  3:      TestString = testString;
  4: }

We do have some control over access modifiers.  For example, we can mimic a read only property (for classes outside of the containing class) like this:

  1: public string TestString { get; private set; }

With these limitations, are they that much of a boon?  I say yes.  I always start with auto prop format when I'm coding up classes, then go back and change them if I need to.  I am all about getting into a rhythm, and the less typing, the better.

Enjoy less typing, and as always, Happy Coding!

Comments are closed
Managed Windows Shared Hosting by OrcsWeb