Home > Back-end >  The constructor of the struct
The constructor of the struct

Time:11-01

I still don't know why the constructor of this struct is giving an error. I went to the Internet to look for a lot of information about that, but I still didn't understand.

public struct Coord
{
    private double _x;
    private double _y;
    
    public double X
    {
        get { return _x; }
        set { _x = value; }
    }
    public double Y
    {
        get { return _y; }
        set { _y = value; }
    }

    public Coord(double x, double y)
    {
        // error here
        X = x;
        Y = y;
    }
}

CodePudding user response:

You need to initialize the variables, not the properties. The compiler doesn't know that your properties X and Y are just simple setters (there could be any code in them). Change your constructor to

public Coord(double x, double y)
    {
        _x = x;
        _y = y;
    }

An alternative would be to change your properties to automatic properties (remove the fields). Then your code would work, too.

CodePudding user response:

You can change the constructor to this:

public Coord(double x, double y) : this()
{
   X = x;
   Y = y;
}

By explicitly calling the default constructor (the added : this() part), all fields are initialized properly to their default value (0.0 for double).

  • Related