All of these, including the existence of properties in the first place are examples of Syntatic Sugar.
In the earliest OOP, accessors were always
private int myVariable;
public int GetMyVariable()
{
return myVariable;
}
private void SetMyVariable(int value)
{
myVariable = value;
}
Then along came the idea of properties, which have the incredible advantage of, when there is a setter, being able to use the variable in virtually any assignment you can think of.
private int myVariable;
public int MyVariable
{
get
{
return myVariable;
}
private set
{
myVariable = value;
}
}
With this, you can do things like
MyVariable+=someChange;
in code.
A quick note here before I carry on: You’ll note that I used private setters here. You’ll often see programmers who create properties with public getters and setters… if those setters don’t do something besides setting the value of the backing field, then they are just creating getters and setters for the sake of creating getters and setters and should just use public variables (which, IMO, is bad form).
So
private int score;
public int GetScore()
{
return score;
}
public void SetScore(int value)
{
score = value;
}
is just an end run around using public int Score; in the first place.
Now if you did
public void SetScore(int value)
{
if(value<0) return;
if(value > 100) TriggerWinCondition();
score=value;
}
Then this is a different matter, and control over the value is still in the hands of the containing class.
The => operator (in this case, referred to as expression bodied syntax) is used with a getter or a setter, whatever follows must be functionally one line of code. On a getter, or without get;set; at all, it basically functions as “return”
so
private int myVariable;
public int MyVariable => myVariable;
is the exact same as
private int myVariable;
pubic int MyVariable
{
get
{
return myVariable;
}
}
In fact, under the hood, when the compiler converts C# into the CLR or into C++ with IL2CPP, the compiler will create methods to represent the getters (and setters, when applicable).
You can also use => with setters if the method is one line.
public int MyVariable
{
get=>myVariable;
private set=>myVariable = value;
}
In newer versions of C# and Unity, you can use autoproperties. In this case the compiler creates a hidden backing field, and you don’t have to worry about it. This is almost exclusively used for this construction:
public int MyValue {get; private set;}
In this case, a hidden backing field is created, and a generic getter and setter is created. Note that this autoproperty will not work with custom getters and setters, and under the hood is equivalent to the
private int myBackingField;
public int MyValue
{
get=>myBackignField;
set=>myBackingField = value;
}