C# 3.0 auto-properties — useful or not?

Michael Stum picture Michael Stum · Aug 13, 2008 · Viewed 46.8k times · Source

Note: This was posted when I was starting out C#. With 2014 knowledge, I can truly say that auto-properties are among the best things that ever happened to the C# language.

I am used to create my properties in C# using a private and a public field:

private string title;
public string Title
{
    get { return title;  }
    set { title = value;  }
}

Now, with .NET 3.0, we got auto-properties:

public string Title { get; set; }

I know this is more a philosophical/subjective questions, but is there any reason to use these auto-properties except from saving five lines of code for each field? My personal gripe is that those properties are hiding stuff from me, and I am not a big fan of black magic.

In fact, the hidden private field does not even show up in the debugger, which is OK given the fact that the get/set functions do nothing. But when I want to actually implement some getter/setter logic, I have to use the private/public pair anyway.

I see the benefit that I save a lot of code (one vs six lines) without losing the ability to change the getter/setter logic later, but then again I can already do that by simply declaring a public field "Public string Title" without the need of the { get; set; } block, thus even saving more code.

So, what am I missing here? Why would anyone actually want to use auto-properties?

Answer

Jeff Atwood picture Jeff Atwood · Aug 13, 2008

We use them all the time in Stack Overflow.

You may also be interested in a discussion of Properties vs. Public Variables. IMHO that's really what this is a reaction to, and for that purpose, it's great.