blah blah blah is here! blah blah » Close

up1down
link

Here's a quick and hopefully simple question for a more experienced developer. What's the difference between these two pieces of a class?

Option 1

private string _myVariable;

public string MyVariable
{
get { return _myVariable; }
set { _myVariable = value; }
}

Option 2
public string MyVariable { get; set; }


I thought the main reason one used the private value with the get/set as a property in a class was if some sort of additional code was executed besides just setting the property or if you had public readonly and needed the code within the class to have the ability to modify the value.

last answered 2 years ago

2 answers

link

nothing. when #2 is complied it generates the underlying member variable.

if all you are doing is providing some encapsulation for a member variable, using the property which you create by hand will take longer (as opposed to using the automatic one).

using the automatic property will remove the ability to access the private member variable which it encapsulates, and it prevents you from being able to access the data before and after the property value is set / get.

Codo
84

OK thanks. I didn't think there was a difference. I've been doing #2, but then I got some code that was supposedly done by a more experienced programmer and they had done #1.

MadHatter
2309

automatic properties are a pretty recent addition, so the "more experienced" programmer was probably used to doing it this way (or wrote it before automatic properties were introduced).

up1down
link

The second version is automatic properties which is a new feature in C#.

Keep in mind you can also set accessibility while using C# automatic properties.

examples:

public string FirstName { get; private set; }


or

public string FirstName { get; protected set; }

or

public string FirstName { private get; set; }

Codo
84

Thanks for that tidbit! I wasn't aware that could be done!! So, the first one you've done makes a public string that you can get, but only set from within the class that FirstName is a part of, right?

Feedback