Neil Tomlinson
Neil Tomlinson

Reputation: 11

The best overloaded method match for int.Parse(string)' has some invalid arguments. What does this mean?

Been trying for over 4 hours now, I'm no expert in the slightest I definitely need help with this. Any idea what is going wrong?

    // Declare variables 
    int inches = 0;
    double centimetres = 0;
    string input;

    //Ask for input
    Console.Write("Enter Number of centimetres to be converted: ");
    input = Console.ReadLine();

    //Convert string to int
    centimetres = double.Parse(input);

    inches = int.Parse(input);

    inches = int.Parse(centimetres / 2.54);

    //Output result
    Console.WriteLine("Inches = " + inches + "inches.");
}

}

Upvotes: 1

Views: 2014

Answers (3)

thescottknight
thescottknight

Reputation: 31

The problem is most like this line: inches = int.Parse(centimetres / 2.54);

int.Parse takes a string and centimetres / 2.54 is a double. to convert a double to an int use Convert.ToInt32 instead.

Upvotes: 1

Damith
Damith

Reputation: 63105

the result of centimetres / 2.54 is double, there is nor overload accept double as parameter in int.Parse

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174397

The "conversion" inches = int.Parse(centimetres / 2.54); makes no sense. int.Parse is used to transform a string that represents a number into an int. But you pass it a double.

To make it work, your code would need to look like this:

//Ask for input
Console.Write("Enter Number of centimetres to be converted: ");
double input = Console.ReadLine();

//Convert string to int
double centimetres = double.Parse(input);

double inches = centimetres / 2.54;

//Output result
Console.WriteLine("Inches = " + inches + "inches.");

Some points:

  1. Declare variables when used, not at the beginning of a method. This is a relict from old languages that required variables to be defined first.
  2. Remove the inches = int.Parse(input); completely, because the result is never used as it is overwritten in the very next line.
  3. Declare inches as double not as int. Otherwise you would be unable to have fractional inches.
  4. Simply assign the result of the division to inches. There is no need for parsing here.

Upvotes: 1

Related Questions