I'm pretty new to C# and have am entirely self-taught with trial and (a lot of) error, so apologies in advance if this is a stupid question.
So far, when creating classes, I have pretty much just made every variable public so I can do what I want with them.
After reading a lot about why this is a bad idea (not that I fully understand it), I now tend to write:
public string name { get; set; }
Instead of what I used previously:
public string name;
I understand the shorthand when it is this simple (and I can see why it's useful for inserting break points, and using things like: public string name { get; private set; }.
However, what is the shorthand for the following:
private double _grip;
public double grip
{
get
{
return _grip;
}
set
{
if (value > 100) { _grip = 100; }
else if (value < 0) { _grip = 0; }
else { _grip = value; }
}
}
It seems a bit clumsy to have to declare a private variable every time I want to put conditions on the variable.
What I want to write is something like this:
public double grip
{
get;
set
{
if (value > 100) { grip = 100; }
else if (value < 0) { grip = 0; }
else { grip = value; }
}
}
And have it neatly on one line once the get and set are minimised. However that doesn't work (though I did get my first ever stack overflow error, which was fun).
So - is there a short hand for the above? I have tried to search and read a lot of info on getters
and setters
and couldn't find something that does this.