Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why define the getter before the setter (coding convention)

I appreciate this question is a little silly, so I apologise in advance if this is off topic or non constructive.

Why, in C# is it standard convention* to define properties with the getter before the setter? For properties with both you're almost always going to use the setter before the getter so it's in a valid state. Therefore, it seems a little backward to me that we define the getter first.

Also, the setter would typically have some validation logic, which the getter doesn't need. Would it not be tidier to have this logic ahead of the getter to make it clearer how the property should behave. For example:

public decimal Price
{
    get { return _price; }
    set
    {
        if(value < 0m)
        {
            throw new ArgumentOutOfRangeException();
        }

        _price = value;
        OnPropertyChanged("Price");
    }
}

The code in the setter is far more interesting than the getter, should it not take precedence and be defined first?

*I know there are no rules with these things, but practically every example ever, ever of properties defines the getter before the setter.

like image 730
RichK Avatar asked Nov 27 '22 09:11

RichK


1 Answers

Because it is better to give than to receive.

On a more serious note, I'm guessing because whoever wrote the snippet (or whatever it is that auto-gens the property code in VS) subconsciously chose this order.

Then as the rest of us are just sheep to this pioneering shepherd, we followed without question.

Until you.

You question our once great shepherd, anarchy can only ensue. Commit your code and run for the hills.

like image 79
Adam Houldsworth Avatar answered Dec 16 '22 01:12

Adam Houldsworth