Search code examples
c#coordinatesautomatic-properties

Custom auto properties in C#


I have the following class with auto properties:

class Coordinates
{
    public Coordinates(int x, int y)
    {
        X = x * 10;
        Y = y * 10;
    }

    public int X { get; set; }

    public int Y { get; set; }
}

As you can see from the constructor I need the value to be multiplied by 10. Is there anyway to do it without removing autoproperties?

I tried the following not thinking that it causes recursion and then everything goes fubar

public int X { get {return X;} set{ X *= 10;} }

I would like to assign values to X and Y multiplied by 10.

Coordinates coords = new Coordinates(5, 6); // coords.X = 50 coords.Y = 60
coords.X = 7; // this gives 7 to X but I would like it to be 70.

Solution

  • In order to make setter working like that, you'll need to use backing field:

    class Coordinates
    {
        public Coordinates(int x, int y)
        {
            X = x;
            Y = y;
        }
    
        private int _x;
        public int X
        {
            get { return _x; }
            set { _x = value * 10; }
        }
    
        private int _y;
        public int Y
        {
            get { return _y; }
            set { _y = value * 10; }
        }
    }
    

    Given your example:

    Coordinates coords = new Coordinates(5, 6); // coords.X = 50 coords.Y = 60
    coords.X = 7; // this gives 70
    

    However, I don't recommend you having such setter because it could lead to confusion. It's better to have a dedicated method which will do such multiplication. In the end, your code will be more descriptive and intuitive.