Question

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?

Was it helpful?

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

OTHER TIPS

In addition to the other good answers posted so far:

  • it is easy to quickly create a private-setter-public-getter property, which is an arguably better practice than a public readonly field for making an immutable data type.
  1. properties allow you to add encapsulation to your class
  2. properties allow your access to be polymorphic (inheritors can modify access if the property is virtual) if you so choose.
  3. auto-properties are nice when you're dealing with simple get/set operations. if you do more complicated operations inside your get / set, then you can't use the auto-property.

also, reflection doesn't work differently on properties than it does on variables though, you're working with a MemberInfo (FieldInfo, PropertyInfo, or MethodInfo whichever way you choose).

  1. Some sort of standards any programmer may be required to follow for whatever reason
  2. Reflection works differently on properties than on variables
  3. You can't databind against a variable
  4. You have to rebuild all code that used the variable if you ever decide to change it to a property

From msdn:

Properties combine aspects of both fields and methods. To the user of an object, a property appears to be a field, accessing the property requires the same syntax.

You can do something like this:

public class Date
{
private int month = 7;  // Backing store

public int Month
{
    get
    {
        return month;
    }
    set
    {
        if ((value > 0) && (value < 13))
        {
            month = value;
        }
    }
}
}

Simply put properties are a lot more versatile.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top