Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert type 'string' to 'bool' [duplicate]

Tags:

c#

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.

like image 652
user1152722 Avatar asked Jan 17 '12 13:01

user1152722


2 Answers

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;
}
like image 84
KV Prajapati Avatar answered Oct 24 '22 00:10

KV Prajapati


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.

like image 38
BlackBear Avatar answered Oct 23 '22 23:10

BlackBear