Difference between using { get; set; } and not
I'm pretty new to C# (experienced in C++ and Python), and I was wondering if someone could clarify the following for me:
What is the difference between these two lines:
public string MyValue;
public string MyValue { get; set; }
I understand when you might want to define a getter and setter, but I've seen the second line above a lot, and I don't understand the difference.7 Replies
The first is a field, the second is a property
we don't usually do public fields
So the first one should just not be done? I can certainly do that.
If I did do the first, is there any difference in how it works from the second?
Ah - I've just found a SO post that talks about an "auto property"
Yes
Essentially what the second does is that it creates a backing field and an automatic getter and setter for that field.
Why is this useful? Because you can change what that property actually does. You may eventually realize you want to perform some validation in the setter, or return something completely different from the getter. With just a field you can't do that, but a property allows you to easily swap out the implementation.
as you have written it in the post, no, there is no difference
no functional one, anyway
Yeah - I get that - that's great to know. In C++ in the past I've initially created a
setValue(type value)
and getValue()
function for a field that don't do anything other than set and get. It's more extra boilerplate, but it's useful to be able to add stuff (like setting a dirty flag) later on down the line
Thanks both - this has been helpfulthat's what Thinker was talking about with validation;