Search code examples
c#automatic-properties

What's the point of an auto property?


This might sound naive, but...

class Widget
{
    public int Foo { get; set; }
}

That's cool, and saves some boilerplate against using a backing field, but at that point, isn't it equivalent to simply:

class Widget
{
    public int Foo;
}

Seems like it's little more than a public field, though I suppose it looks different under the hood. From a design point, though, what's the advantage of using a property if it doesn't aid encapsulation?


Solution

  • Because it gives you the potential to add encapsulated logic later without changing the metadata of the class.

    Using properties is considered a best practice - automatically implemented properties were designed to take away the tediousness of writing properties to encourage developers to adhere to this best practice