-2

Example 1:

class Class1
{
    public static int A = 1;
}

Example 2:

class Class2
{
    private static int _A = 1;
    public static int A
    {
        get
        {
            return _A;
        }
        set
        {
            _A = value;
        }
    }
}

Assuming that I don't want to do any validation and perform any extra functions. I just want to hold the plain data. Both Class1.A and Class2.A have the same result. New number can be assigned to both too. So what is the different for doing this? Is there any benefits? Why and When should I use them?

If there is no difference between them, I should use Example 1, as Example 1 only requires 1 line of code and Example 2 requires 6-10 lines. Do you agree?

mjb
  • 7,649
  • 8
  • 44
  • 60
  • 2
    Re: your last paragraph: you can write a property as in example 2 shorthand like this: `public static int A { get; set; }` which is only one line, same as example 1. As long as you need access elsewhere to the private backer and don't want to add additional actions to get or set, just use this syntax. – Esoteric Screen Name Aug 09 '13 at 16:13
  • 1
    Standard nomenclature is Field and Property, rather than Value and Property. – Michael Aug 09 '13 at 16:15
  • I assume if you'd do dome research you'd find that there are the same reasons to go for the second solution as there are with instance variables and properties. – oddparity Aug 09 '13 at 16:16
  • This has been asked before. http://stackoverflow.com/questions/4142867/what-is-difference-between-property-and-variable-in-c-sharp –  Aug 09 '13 at 16:16
  • 1
    @EsotericScreenName No, you cannot. That would not allow you to use an initialiser. You could set it in a static constructor, but that is not the same thing, since the runtime has more leeway in determining when to evaluate a field initialiser. –  Aug 09 '13 at 16:20
  • @hvd Good point, I missed the initializer value. – Esoteric Screen Name Aug 09 '13 at 16:24

1 Answers1

1

The technical difference is the presence of get and set accessors. You can customize either or both to do more that just get or set the value.

The practical difference is that many data-binding methods (including most if not all of the .NET controls) use reflection to bind to properties only - they do not support binding to fields directly.

If you plan to bind the properties of your class to a UI control (DataGrid, TextBox, etc.), or if there's the slightest chance that you might customize the get/set accessors in the future, then make the properties. It is a breaking change to change a field to a property.

Many coding standards (including FxCop) hold that you should use properties instead of fields for public data.

If lines of code are a concern you can use auto-implemented properties:

class Class2
{
    public static int A {get; set; }
}

You can later add logic to the get/set accessors without breaking users of your class.

D Stanley
  • 149,601
  • 11
  • 178
  • 240