public (int or someting else) value {get; set;};
Isn’t it same as just
public (int or someting else) value;
?
Why use that structure?
What’s the difference?
public (int or someting else) value {get; set;};
Isn’t it same as just
public (int or someting else) value;
?
Why use that structure?
What’s the difference?
It’s definitely not the same.
public int Value { get; set; }
Is actually more like this (incredibly roughly speaking):
private int _value;
public int Value
{
get => _value;
set => _value = value;
}
And this has a lot of ramifications. For example, if you need to change the underlying means of how Value
is calculated, you can do that without having to refactor any users of the property.
You can also apply validation to the setter, preventing invalid values from being assigned.
Not to mention you do stuff like this:
public int Value { get; private set; }
// OR
public int Value { get; protected set; }
Making the value read-only to outside consumers, but mutable only internally, or also to inherited types with the protected set
setter.
I would say you’d probably will only use a straight get; set
auto-property fairly rarely, though it is good to do to allow easy refactoring. Personally, probably 99% of my properties are get-only properties.
Ergo:
private int _value;
public int Value => _value;
Because I generally want values to be read only. As you can serialise the backing field, and a lot of the Unity workflow is editing serialized values, it goes hand-in-hand with the general Unity work flow.
A lot of this is covered by Microsoft themselves: Using Properties - C# | Microsoft Learn