Possible Duplicate:
Help converting type - cannot implicitly convert type 'string' to 'bool'
I've got this code:
private double Price;
private bool Food;
private int count;
private decimal finalprice;
public void Readinput()
{
Console.Write("Unit price: ");
Price = Console.ReadLine();
Console.Write("Food item y/n: ");
Food = Console.ReadLine();
Console.Write("Count: ");
count = Console.ReadLine();
}
private void calculateValues()
{
finalprice = Price * count;
}
and get the following errors:
Cannot implicitly convert type 'string' to 'bool'
Cannot implicitly convert type 'string' to 'double'
Cannot implicitly convert type 'string' to 'int'
Cannot implicitly convert type 'double' to 'decimal'. An explicit conversion exists (are you missing a cast?)
I know what it means but I don't know how to fix it.
Use bool.Parse
or bool.TryParse
method to convert string value to boolean
.
Price = double.Parse(Console.ReadLine());
Food =bool.Parse(Console.ReadLine());
count = int.Parse(Console.ReadLine());
You can't convert "y" or "n" value to boolean instead your have to receive value as a string and if it is "y" then store true
, false
otherwise.
Console.Write("Food item y/n: ");
string answer = Console.ReadLine();
if(answer=="y")
Food=true;
else
Food=false;
Or (suggestion of @Mr-Happy)
Food = answer == "y"
You need to specify explicit cast while calculating finalprice
.
private void calculateValues()
{
// convert double result into decimal.
finalprice =(decimal) Price * count;
}
You have to convert what you read from the console (which is a string) to the actual type using the static class Convert. For example:
Console.Write("Count: ");
count = Convert.ToInt32(Console.ReadLine());
This crashes if the argument given can't be converted, but this is not your primary problem right now, so let's keep it simple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With