Search code examples
c#integerconsole.readline

Why can't you convert Console.ReadLine to int trough Convert.ToInt


so I was just starting to code and found out that this example right here doesn't work, but with int.TryParse() it would work. Otherwise with Convert.Byte() it works too. What is the background of that?

using System;

namespace timezones
{
    class Program
    {
        static void Main(string[] args)
        {
            int timeSwitzerland = Convert.ToInt(Console.ReadLine());

        }
    }
}

Solution

  • As I'm seeing this quite often, I'll post the official string to number conversion guide

    You can convert a string to a number by calling the Parse or TryParse method found on the various numeric types (int, long, double, and so on), or by using methods in the System.Convert class.

    The Convert.ToInt32 method uses Parse internally. The Parse method returns the converted number;

    So effectively in both cases you use Int.Parse

    Now in your case the options are Convert.ToInt{Enter extected integer size}:

    enter image description here