Answer the question
In order to leave comments, you need to log in
Convert.ToXXXX() vs. XXX.Parse()?
Convert.ToXXXX() vs. What is the difference between XXX.Parse()? And which one is better to use?
Answer the question
In order to leave comments, you need to log in
Neither, it's better to use TryParse. Because both Parse and Convert.ToXXX will throw an exception, and you will have to use try catch, and in TryParse it is enough to use if.
Numeric example:
int x;
string str = Console.ReadLine();
// Вариант с Parse
try
{
x = int.Parse(str);
}
catch (Exception)
{
x = 0;
Console.WriteLine("Неверные данные");
}
// Вариант с Convert
try
{
x = Convert.ToInt32(str);
}
catch (Exception)
{
x = 0;
Console.WriteLine("Неверные данные");
}
// Вариант с TryParse
if (!int.TryParse(str, out x))
{
Console.WriteLine("Неверные данные");
}
// Вариант с TryParse, если ноль устраивает
int.TryParse(str, out x);
There is no difference at runtime, Parse and ToString are "wrappers" for Convert, in terms of conciseness and readability of the code for numbers it is better than Parse, for strings ToString, and Convert.ToString makes sense only in C ++ / CLI, in both cases the choice is due to the principles of OOP , options other than strings and numbers are extremely rare.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question