C
C#2y ago
Hugh

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
Thinker
Thinker2y ago
The first is a field, the second is a property
ero
ero2y ago
we don't usually do public fields
Hugh
Hugh2y ago
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"
Thinker
Thinker2y ago
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.
ero
ero2y ago
as you have written it in the post, no, there is no difference no functional one, anyway
Hugh
Hugh2y ago
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 helpful
ero
ero2y ago
that's what Thinker was talking about with validation;
private bool _dirty;

private string? _myValue;
public string? MyValue
{
get => _myValue;
set
{
_dirty = true;
_myValue = value;
}
}
private bool _dirty;

private string? _myValue;
public string? MyValue
{
get => _myValue;
set
{
_dirty = true;
_myValue = value;
}
}