170

I was wondering what were the differences between those declaration of getters and setters and if there is a preferred method (and why). The first one can be generated automaticly by Visual Studio. How about the others ? Thanks

1st

string _myProperty { get; set; }

2nd

string _myProperty;

public string myProperty
{
    get { return _myProperty; }
    set { _myProperty = value; }
}

3rd

string _myProperty;

public string getMyProperty()
{
  return this._myProperty;
}

public void setMyProperty(string value)
{
  this._myProperty = value;
}
Davide Pizzolato
  • 679
  • 8
  • 25
WizLiz
  • 2,068
  • 5
  • 25
  • 39
  • 16
    @Steve this isn't a duplicate of that question, as that asks, "why" and this one asks "whats the difference". Once someone knows why to use properties, the next obvious question is "why is there more than one implementation of it?" – Andrew Grothe Jul 26 '13 at 12:36
  • 2
    Then have some more possible duplicates: [here](http://stackoverflow.com/questions/4923630/c-sharp-getters-setters-declaration), [here](http://stackoverflow.com/questions/9304/c-sharp-3-0-auto-properties-useful-or-not) and [here](http://stackoverflow.com/questions/6655465/property-accessors). 9 answers in about 5 minutes to a question which must inevitably have been asked, more than once :P – anton.burger Jul 26 '13 at 12:50
  • 3
    All questions on this topic are either marked as duplicates or a different topic. Where is the original one? – Argeman Jan 18 '16 at 10:33

8 Answers8

232

Properties are used to encapsulate some data. You could use a plain field:

public string MyField

But this field can be accessed by all outside users of your class. People can insert illegal values or change the value in ways you didn't expect.

By using a property, you can encapsulate the way your data is accessed. C# has a nice syntax for turning a field into a property:

string MyProperty { get; set; }

This is called an auto-implemented property. When the need arises you can expand your property to:

string _myProperty;

public string MyProperty
{
    get { return _myProperty; }
    set { _myProperty = value; }
}

Now you can add code that validates the value in your setter:

set
{
    if (string.IsNullOrWhiteSpace(value))
        throw new ArgumentNullException();

    _myProperty = value;
}

Properties can also have different accessors for the getter and the setter:

public string MyProperty { get; private set; }

This way you create a property that can be read by everyone but can only be modified by the class itself.

You can also add a completely custom implementation for your getter:

public string MyProperty
{
    get
    {
        return DateTime.Now.Second.ToString();
    }
}

When C# compiles your auto-implemented property, it generates Intermediate Language (IL). In your IL you will see a get_MyProperty and set_MyProperty method. It also creates a backing field called <MyProperty>k_BackingField (normally this would be an illegal name in C# but in IL it's valid. This way you won't get any conflicts between generated types and your own code). However, you should use the official property syntax in C#. This creates a nicer experience in C# (for example with IntelliSense).

By convention, you shouldn't use properties for operations that take a long time.

Wouter de Kort
  • 39,090
  • 12
  • 84
  • 103
  • 3
    +1. Just to be clear, though, the `get_MyProperty` and `set_MyProperty` will be there for any property with a getter and/or setter (respectively), whether it's an auto property or not. The only difference between auto properties is the auto-generated (and inaccessible in code) backing field. – Adam Robinson Jul 26 '13 at 12:53
15

Well, the first and second both generate something like the third in the end. However, don't use the third when you have a syntax for properties.

Finally, if you have no work to do in the get or set, then use the first.

In the end, the first and second are just some form of syntactic sugar, but why code more than what's necessary.

// more code == more bugs

And just to have a little fun, consider this:

public string A { get; private set; }

Now that's a lot more straight forward isn't it? The public modifier is implied on both the get and the set, but it can be overriden. This would of course be the same rule for any modifier used when defining the property itself.

Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
  • 3
    if you comment out everything, then you will have no bugs! Problem solved. Also, to add clarification: The second code block (and the third, but let's not use that) allows you to do some stuff before you actually get the value of the variable. For instance, you could set a flag: `isAccessed = true;` – Russell Uhl Jul 26 '13 at 12:22
  • 1
    @RussellUhl, yes, that's true. And that's exactly why I stated **if you have no work to do in the `get` or `set`, then use the first.** – Mike Perrenoud Jul 26 '13 at 12:23
  • 2
    @RussellUhl: I think the "more lines of code == more bugs" operates under the assumption that you can still accomplish what you're after with fewer lines. If you can comment out your entire program and still accomplish your goals, it might be a good idea to do so ;) – Adam Robinson Jul 26 '13 at 12:25
  • 1
    @AdamRobinson, I've run into programs I maintained where I'd like to comment out every line of code. I just didn't feel that it would perform any worse. :D – Mike Perrenoud Jul 26 '13 at 12:27
  • @TheSolution I was expanding that because I felt you glossed over it too quickly. chillax. – Russell Uhl Jul 26 '13 at 15:29
14

With this, you can perform some code in the get or set scope.

private string _myProperty;
public string myProperty
{
    get { return _myProperty; }
    set { _myProperty = value; }
}

You also can use automatic properties:

public string myProperty
{
    get;
    set;
}

And .Net Framework will manage for you. It was create because it is a good pratice and make it easy to do.

You also can control the visibility of these scopes, for sample:

public string myProperty
{
    get;
    private set;
}

public string myProperty2
{
    get;
    protected set;
}

public string myProperty3
{
    get; 
}

Update

Now in C# you can initialize the value of a property. For sample:

public int Property { get; set; } = 1;

If also can define it and make it readonly, without a set.

public int Property { get; } = 1;

And finally, you can define an arrow function.

public int Property => GetValue();
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
9

1st

string _myProperty { get; set; }

This is called an Auto Property in the .NET world. It's just syntactic sugar for #2.

2nd

string _myProperty;

public string myProperty
{
    get { return _myProperty; }
    set { _myProperty = value; }
}

This is the usual way to do it, which is required if you need to do any validation or extra code in your property. For example, in WPF if you need to fire a Property Changed Event. If you don't, just use the auto property, it's pretty much standard.

3

string _myProperty;

public string getMyProperty()
{
    return this._myProperty;
}

public string setMyProperty(string value)
{
    this._myProperty = value;
}

The this keyword here is redundant. Not needed at all. These are just Methods that get and set as opposed to properties, like the Java way of doing things.

Raijinili
  • 13
  • 3
Andrew Grothe
  • 2,562
  • 1
  • 32
  • 48
3

Just to clarify, in your 3rd example _myProperty isn't actually a property. It's a field with get and set methods (and as has already been mentioned the get and set methods should specify return types).

In C# the 3rd method should be avoided in most situations. You'd only really use it if the type you wanted to return was an array, or if the get method did a lot of work rather than just returning a value. The latter isn't really necessary but for the purpose of clarity a property's get method that does a lot of work is misleading.

OnABauer
  • 609
  • 4
  • 18
0

The 1st one is default, when there is nothing special to return or write. 2nd and 3rd are basically the same where 3rd is a bit more expanded version of 2nd

NG.
  • 5,695
  • 2
  • 19
  • 30
0

Lets start with 3. That wouldnt work. public getMyProperty() has no return typ.

And number 1 and 2 are actually same things. 2 is what number 1 becomes after compilation.

So 1 and 2 are same things. with two you can have some validation or caching in your model.

other than that they become same.

DarthVader
  • 52,984
  • 76
  • 209
  • 300
0

The first one is the "short" form - you use it, when you do not want to do something fancy with your getters and setters. It is not possible to execute a method or something like that in this form.

The second and third form are almost identical, albeit the second one is compressed to one line. This form is discouraged by stylecop because it looks somewhat weird and does not conform to C' Stylguides.

I would use the third form if I expectd to use my getters / setters for something special, e.g. use a lazy construct or so.

Christian Sauer
  • 10,351
  • 10
  • 53
  • 85