C# Automatic Properties

Having been happily typing out full property declarations for months, I’ve just stumbled upon Automatic Properties. Take the following example:

public class Pet
  private string _Name;
  public string Name
    get { return _Name; }
    set { _Name = value; }

  private int _Age;
  public int Age
    get { return _Age; }
    set { _Age = value; }

We can re-write this class using automatic properties:

public class Pet
  public string Name { get; set; }
  public int Age { get;  set; }

Both classes are identical. In effect this is just syntactic sugar, we just let the compiler do the work for us. For classes with many properties, this can significantly reduce the amount of code.

A word of warning – this only applies for properties that have both ‘get’ and ‘set’ methods, so you couldn’t do this for a read-only property.

UPDATE: Actually, you can. Just add ‘private’ before either ‘get’ or ‘set’:

public string Name { get; private set; }
This entry was posted in Tips and Tricks and tagged , . Bookmark the permalink.

1 Response to C# Automatic Properties

  1. Dan K says:

    This is neat – it’s also worth pointing out that this is a feature of .Net 3.0 onwards.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s