Reputation: 95
I've trying to learn c# but keep coming across a problem. Essentially, I'm trying to learn how to create a class that does some function and is called to perform that function by the application.
the error I have ended up with (there have been loads of others but I've tried to play around to 'fix' them) is
is a 'type' but is used like a variable
the code I've put together so far is;
namespace FirstConsoleApplication
{
class Program
{
public class checkConvertValue
{
public string formula1(string x)
{
Int32 isnumber = 0;
bool canConvert = Int32.TryParse(x, out isnumber);
string returnValue;
if (canConvert == true)
{
int val3 = Int32.Parse(x);
switch (val3)
{
case 50:
returnValue = "yep its 50";
break;
case 51:
returnValue = "hmmm.... its 51... what are you gonna do about that??";
break;
case 52:
returnValue = "lets not get sloppy now...";
break;
default:
returnValue = "nope, its definately something else";
break;
};
}
else
{
returnValue = "Thats not a number";
};
return returnValue;
}
}
static void Main(string[] args)
{
string num;
string result1;
do
{
Console.WriteLine("Guess what the value is, hint... its integer and between 1 and 100");
num = Console.ReadLine();
result1 = checkConvertValue(num);
Console.WriteLine(result1);
} while (result1 != "yep its 50");
Console.ReadLine();
}
}
}
can someone let me know where I'm going wrong?
Upvotes: 0
Views: 119
Reputation: 477
You are trying to call the class checkConvertValue as if it were a method. To actually call the method you need to call the formula1 method from an instance of class checkConvert value. Try this:
num = Console.ReadLine();
checkConvertValue classReference = new checkConvertValue();
result1 = classReference.formula1(num);
Console.WriteLine(result1);
Upvotes: 1
Reputation: 263733
object checkConvertValue
is a class but you are using it as a method.
you need to declare an instance of it before you can use the method formula1
num = Console.ReadLine();
checkConvertValue chkVal = new checkConvertValue();
result1 = checkConvertValue.formula1(num);
Console.WriteLine(result1);
Upvotes: 0
Reputation: 2562
You are trying to access the function by class name, which is wrong. You have to do like this
result1 = new checkConvertValue().formula1(num);
Upvotes: 0
Reputation: 14618
There are a couple things wrong here.
checkConvertValue
doesn't contain a constructor which takes num (assuming its a string), i think you meant to call formula(...)
You need to create an instance of checkConvertValue
and then call the formula
method from that or make the class and method static and call it like checkConvertValue.formula1
etc...
Upvotes: 0
Reputation: 1062885
You presumably mean:
result1 = new checkConvertValue().formula1(num);
or if you make it (formula1
) a static
method:
result1 = checkConvertValue.formula1(num);
btw; there's no point in parsing x
twice; if the TryParse
succeeds, the integer value is stored in isnumber
.
Upvotes: 1