T
T
TheForgetDragon2016-07-27 18:57:18
C++ / C#
TheForgetDragon, 2016-07-27 18:57:18

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

3 answer(s)
A
Alexey Pavlov, 2016-07-28
@lexxpavlov

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);

I
idShura, 2016-07-27
@idShura

Read here msdn

R
Rou1997, 2016-07-27
@Rou1997

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 question

Ask a Question

731 491 924 answers to any question