Reputation: 3292
Here is my Circle class code.
class Circle
{
private double radius;
private double area;
public Circle(double radius)
{
this.radius = radius;
}
public double Area
{
set { area = Math.PI * Math.Pow(radius, 2); }
get { return area; }
}
}
This is test code.
Circle circle1 = new Circle(3);
MessageBox.Show("Circle 1 Area: " + circle1.Area);
So for some reason, when I use the MessageBox.Show(), it seems to give me values of zero instead. I gave the circle a value of 3 so shouldn't my constructor set the value of the radius that?
Upvotes: 3
Views: 335
Reputation: 32576
Your Area
property should be:
public double Area
{
get { return Math.PI * Math.Pow(radius, 2); }
}
and you don't need the area
field.
Upvotes: 6
Reputation: 7303
I'm not sure you need a set
in this instance (You didn't use it)
try
get { return Math.PI * Math.Pow(radius, 2); }
Upvotes: 1
Reputation: 24156
Because you haven't ever called the setter on Area. Perhaps you want something like this instead?
class Circle
{
private double radius;
public Circle(double radius)
{
this.radius = radius;
}
public double Area
{
get { return Math.PI * Math.Pow(radius, 2); }
}
}
This will compute the Area every time it is requested.
Upvotes: 6