Is it possible to only specify one action (get/set) of an Automatic Property and have the other implemented?

StackOverflow https://stackoverflow.com/questions/22799315

  •  25-06-2023
  •  | 
  •  

Question

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.

Was it helpful?

Solution

No, if you provide a custom implementation for one of your methods (getter or setter) your property is no longer an auto-implemented property.So you need to keep using this version:

private double _grip;
public double grip
{
    get
    {
        return _grip;
    }
    set
    {
        if (value > 100) { _grip = 100; }
        else if (value < 0) { _grip = 0; }
        else { _grip = value; }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top