c# using field with get and set methods vs using property

时间:2015-07-28 22:33:37

标签: c# properties field

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."

4 个答案:

答案 0 :(得分:3)

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.

答案 1 :(得分: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.

答案 2 :(得分: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.

答案 3 :(得分: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.

相关问题