简体   繁体   中英

When to use int.Parse?

May I know why we need to use int.Parse in the first example but not the second one?

1st Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Test
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string name = Console.ReadLine();
            int age= int.Parse(Console.ReadLine());
            Console.WriteLine("Name:"+ name);
            Console.WriteLine("Age:"+ age);
        }
    }
}

2nd Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Test
{
    public class Program
    {
        public static void Main(string[] args)
        {
             int age = 20;
             Console.Write(age);
        }
    }
}

Thank you for all your answers.

in the first part you have to convert the input from the command line, which is string, into an INTEGER. In the second one, you already declared an integer and therefore no need to parse it.

While Kektuto's answer is correct, I'd say that the call to int.Parse is redundant in the first code snippet too. You use it to convert the inputted string to an int , and then convert it back to a string when you concatenate it. Had you actually done some calculation with the inputted age, the parsing would indeed be required.

In the first example you are receiving a string as console input. Because there is no implicit conversion from int to string you have to explicitly parse the string to int to be able to assign it to a variable of type integer .
In the second example you don't need to parse anything explicitly because C# is internally calling the ToString() method of int . So internally there is an conversion happening as well but you don't have to do it explicitly. It would be the same as calling

Console.Write(age.ToString());

Like @Damien_The_Unbeliever stated in the comments. When parsing console input you want to use int.TryParse() to avoid any exceptions when receiving non-integer values as input. This would look something like this:

int age;
if(!int.TryParse(Console.ReadLine()), out age)
{
   Console.WriteLine("Wrong input format");
}
else
{
   // Do something
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM