Reputation: 289
I have a constructor I am trying to build with the header public KsuPoint(double x0, double y0)
now i also have properties in the class as shown below
private double x;
public double X
{
get { return x; }
}
private double y;
public double Y
{
get { return y; }
}
This constructor is suppose to initialize the properties X and Y ...
is this correct? or am i off?
public KsuPoint(double x0, double y0)
{
new KsuPoint(x0, y0);
}
Upvotes: 1
Views: 178
Reputation: 10221
You need to add setters, like this:
public double X
{
get { return x; }
set { x = value; }
}
If you just want simple getters and setters, this syntax is shorter, and easier to read in my opinion:
public double x0 { get; set; }
public double y0 { get; set; }
Then you simply assign the parameter to the field, like many of the other answers show.
Upvotes: 0
Reputation: 65116
No, that would result in a bad case of infinite recursion. Just assign the values normally, i.e.
x = x0;
y = y0;
Upvotes: 0
Reputation: 347196
No you only use new when you want to create a new object of the class typically outside the class.
public KsuPoint(double x0, double y0)
{
x = x0;
y = y0;
}
Somewhere else in your code you would have:
KsuPoint point = new KsuPoint(3, 4);
If you are using C# 3.0 you can also do this:
class KsuPoint
{
public double X { get; private set; }
public double Y { get; private set; }
public KsuPoint(double x0, double y0)
{
X = x0;
Y = y0;
}
}
Upvotes: 0
Reputation: 351456
The constructor needs to map it's parameters to the private fields of the class - here is what your class should look like:
class KsuPoint
{
private double x;
private double y;
public double X { get { return x; } }
public double Y { get { return y; } }
public KsuPoint(double x0, double y0)
{
this.x = x0;
this.y = y0;
}
}
If you want to be more concise you could do this:
class KsuPoint
{
public double X { get; private set; }
public double Y { get; private set; }
public KsuPoint(double x0, double y0)
{
this.X = x0;
this.Y = y0;
}
}
Upvotes: 4