Getter and Setter declaration in .NET

C#.NetVisual Studio-2010

C# Problem Overview


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;
}

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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.

Solution 3 - C#

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();

Solution 4 - C#

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.

Solution 5 - C#

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.

Solution 6 - C#

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

Solution 7 - C#

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.

Solution 8 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWizLizView Question on Stackoverflow
Solution 1 - C#Wouter de KortView Answer on Stackoverflow
Solution 2 - C#Mike PerrenoudView Answer on Stackoverflow
Solution 3 - C#Felipe OrianiView Answer on Stackoverflow
Solution 4 - C#Andrew GrotheView Answer on Stackoverflow
Solution 5 - C#OnABauerView Answer on Stackoverflow
Solution 6 - C#NG.View Answer on Stackoverflow
Solution 7 - C#DarthVaderView Answer on Stackoverflow
Solution 8 - C#Christian SauerView Answer on Stackoverflow