3

What is the difference in functionality between using a field with get and set methods versus using a property to attribute a value to an object through a class? For example, when setting up a value val in a class, are there any reasons to choose one of the two classes below over the other (other than length of code written and interface compatibility):

class FieldTest
{
    public FieldTest()
    {
    }

    private string val;

    public void SetVal(string temp)
    {
        val = temp;
    }

    public string GetVal()
    {
        return val;
    }
}

Versus

class PropertyTest
{
    public PropertyTest()
    {

    }

    public string val { get; set; }
}

Tested Usage in Visual Studio 2010:

class TestFunctions
{
    static void Main(string[] args)
    {
        FieldTest Test_Fields = new FieldTest();
        Test_Fields.SetVal("Test");
        string temp_str = Test_Fields.GetVal();
        

        PropertyTest Test_Property = new PropertyTest();
        Test_Property.val = "test";
        string temp_str_prop = Test_Property.val;

        System.Windows.Forms.MessageBox.Show("Field: " + temp_str + "\n\nProperty: " + temp_str_prop);
    }
}

I know only a field can use ref and out keywords, but the other advantages usually attributed to a property--encapsulation, versioning, etc-- seem to be the same with these two setups.

I've checked articles such as Difference between Property and Field in C# 3.0+ and What is the difference between a Field and a Property in C#?. Though they give good descriptions of the ideas behind properties and fields, I have not been able to find a specific answer to my question.

Thanks in advance for clarification.



EDIT 2015-07-29:

I believe this to be a separate question from other StackOverflow answers, such as those found here, as these answers did not seem to specifically address using fields with their own get and set methods as a replacement for a property.

My statement above, "I know only a field can use ref and out keywords..." comes from answers similar to the following (found here):

      "Fields may be used for out / ref parameters, properties may not. Properties support additional
       logic – this could be used to implement lazy loading among other things."

Community
  • 1
  • 1
Doug B
  • 347
  • 1
  • 2
  • 8
  • I believe I asked a similar question and got some really good answers on reddit several months back. You can find that thread [here](http://www.reddit.com/r/learnprogramming/comments/2wa60h/c_confusion_about_get_set_autoimplemented/). You may want to ask this on reddit, as it has already been covered on stackoverflow, and there are so many minor facets that you might be confused about, having a discussion can often help more than stackoverflow's QA format. – James G. Jul 28 '15 at 22:39
  • possible duplicate of [What is the difference between a Field and a Property in C#?](http://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property-in-c) – Murilo Jul 28 '15 at 22:42
  • @James G - Thanks for the link and feedback. I usually go to SO for answers, and didn't think of other message boards to try. Also, a discussion would be very beneficial. – Doug B Jul 29 '15 at 13:21
  • @Murilo - Edited question to address my belief in why the question is unique from the link you provided. – Doug B Jul 29 '15 at 13:22

4 Answers4

4

The functionality is almost identical. For "normal" code use-cases, these snippets will act exactly the same, as a property is in effect just a hidden field with two hidden methods (get and set).

However, there is a difference when it comes to reflection. Properties show up as PropertyInfo, and methods MethodInfo. You also can only bind to properties (in WPF/WinRT). Serialization also only works against properties. Both of these (and doubtlessly others) fail because they use reflection to find the members to act against.

So depending on your use case, they are the same. Generally speaking, I would stick with properties.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
  • Thanks for the info, the middle paragraph depicts more along the lines of what I am looking for. More food for thought! – Doug B Jul 29 '15 at 13:34
2

In the .NET world properties are how you attribute data to objects. Methods are typically actions associated with the objects. Fields usually store internal (private) object instance state.

Under the hood, read/write property accessors get compiled to get and set methods.

Additionally, many technologies do not work with methods. Data Annotations, Entity Framework, and serialization are a few that pop instantly to mind.

Sam Axe
  • 33,313
  • 9
  • 55
  • 89
  • More instances of differences, thanks for the info. One followup question that may need another SO question: if the property accessors get compiled to get and set methods, and many technologies do not work with methods, why can these technologies (such as serialization) be used with properties and not the get and set methods in the question classes? – Doug B Jul 29 '15 at 13:42
  • Because a `property` is more than just its accessors. In addition to the accessors a property also has (optionally) attribute decorations. Serializers operate on properties because that's what makes sense in the .NET world. There is absolutely nothing stopping you or anyone else from writing a serializer that operated on methods instead of properties. But you will most likely not get very many people to use it since it flies in the face of .NET convention. – Sam Axe Jul 29 '15 at 23:35
2

I would always vote for properties rather than getter and setter.

  1. First of all - using Property is neat and clean. The code is more clear, less junky and easy to understand.

  2. If you use Automatic Property you just need one line of code for one Property where you need at least 6 for a getter and setter approach. So if your class has 20 attributes then total 120 lines of codes? Oh Man!!!

  3. but the other advantages usually attributed to a property--encapsulation, versioning, etc-- seem to be the same with these two setups. => I disagree, consider a scenario where you want to force all implementation of an interface with an attribute to be readonly. That is easily doable with a readonly property in the interface. Now try that with getter and setter. Frankly you can't.

  4. Then there comes Serialization. You cannot serialize a computed value unless that is a property. Methods are never serialized.

brainless coder
  • 6,310
  • 1
  • 20
  • 36
  • This is more along the lines of what I am looking for, thanks for the information. I am not sure I agree with _always_ choosing anything over another, but my experience is too lacking to make that call in this case. – Doug B Jul 29 '15 at 13:33
  • Of course everyone has their own preferences, but to me, 1 line of code is always better than 3,4,5 lines of code. – brainless coder Jul 29 '15 at 22:33
0

Let's take a look at your second code:

class PropertyTest
{
    public PropertyTest()
    {

    }

    public string val { get; set; }
}

As said in the Auto-Implemented Properties page on MSDN, when you declare an auto-implemented property like in your example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.

In other words, it would be like writing this code:

public class PropertyTest
{
    public PropertyTest()
    {

    }

    private string _val;

    public string val
    {
        get { return _val; }
        set { val = value; }
    }
}

So, properties are a way to encapsulate fields. As you can see on MSDN, too:

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

In my opinion, you should always prefer to use the property implementation than the getter/setter methods. Not because it seems cleaner and flexible to make things like compute values, but it is actually easier to implement (you write less code on auto-implemented properties).

We could say that there are almost no difference from the properties than the getter/setter methods too, if we look at the part where MSDN says "but they are actually special methods called accessors". But again, we have the example of brainless coder above, we have Framework behaviours that encourages us to use properties: methods can not be serialized, while properties can.

Ismael
  • 622
  • 6
  • 11