Reputation: 9
I'm trying to write a program that have two classes, and call 2 variables from one to another but i got two errors that saying " 'Area.Circle' does not contain a definition for 'result1' " and " 'Area.Circle' does not contain a definition for 'result2' ". how can i solve this problem?
using System;
namespace Area
{
class Circle
{
public static void Area()
{
Console.WriteLine("Enter the radius of the first circle: ");
int r1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the radius of the second circle: ");
int r2 = Convert.ToInt32(Console.ReadLine());
double pi = Math.PI;
double result1 = pi * r1 * r1;
double result2 = pi * r2 * r2;
Console.WriteLine("The area of the first circle is {0}\nThe area of the second circle is {1}\n", result1, result2);
}
}
class Minimum
{
static void Main(string[] args)
{
Circle.Area();
Circle one = new Circle();
double min = Math.Min(Circle.result1, Circle.result2);
Console.WriteLine("min");
}
}
}
Upvotes: 0
Views: 299
Reputation: 1821
The problem is that you are defining result1
and result2
within the scope of the Area()
method. Declare them at the class level, public and static, and they will be accessible.
As the method Area()
is static the variables will have to also be static in order to be accessed from within it. You are accessing the variables as static from your other class though, so that should work.
Upvotes: 4
Reputation: 203802
When you have a method that computes values it needs to return the values that it computes to the caller. Storing them in a local variable isn't exposing them to the caller of the method. In this case, since you have two values to return, you'll need to encapsulate those two values in another class that can be returned instead. You could make a custom class, or simply use a general purpose class such as Tuple
.
public static Tuple<double, double> Area()
{
Console.WriteLine("Enter the radius of the first circle: ");
int r1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the radius of the second circle: ");
int r2 = Convert.ToInt32(Console.ReadLine());
double pi = Math.PI;
double result1 = pi * r1 * r1;
double result2 = pi * r2 * r2;
Console.WriteLine("The area of the first circle is {0}\nThe area of the second circle is {1}\n", result1, result2);
return Tuple.Create(result1, result2);
}
When you call Area
you can then store the result of the method in a variable and access that data later on.
Upvotes: 0
Reputation: 149518
That's because result1
and result2
are local variables inside your Area
method. You have to make them public
and at the class level (consider turning them into Properties
perhaps):
class Circle
{
public double Result1 { get; set; }
public double Result2 { get; set; }
}
One thing to note is that if you keep Area
declared as a static
method, you wont be able to use instance members inside the calling function.
Upvotes: 2