A
A
Artem2018-11-07 12:15:17
C++ / C#
Artem, 2018-11-07 12:15:17

What are the differences between Parse and Convert.To?

The Parse() and Convert.To...() methods perform the same function - they convert a value to another data type, but what is the difference between them?
string age = Convert.ToInt16(Console.ReadLine());

string age = "20";
ageSecond = Int16.Parse(age)

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
Michael, 2018-11-07
@NeverGetBurn

Recently answered a similar question
Cast vs Convert vs Parse?

P
Peter, 2018-11-07
@Morpheus_God

Parse will convert the string to int16 like in your example.
Convert converts a value of any type to int, for example boolean, double, float . On an uninitialized string, if you use Parse you will get an exception, Convert will return 0.
Convert can be applied to a class if the class implements the IConvertible interface. That is, if you enter some kind of your own data type, you can convert it into it, it will be enough to implement the above interface.

S
shai_hulud, 2018-11-07
@shai_hulud

And there is also a package that chooses the appropriate conversion method itself.
https://habr.com/post/315352/

A
Alexey Pavlov, 2018-11-07
@lexxpavlov

To understand what the difference is, then see the source - the source code is here (on line 887).
In general, it Parsetakes a string and returns a number (maybe there will be an exception). Convert.ToInt16has many options, depending on the type of the argument. It specifically Convert.ToInt16(string)calls Int16.Parse(value, CultureInfo.CurrentCulture), that is, there is absolutely no difference with Parse(including an exception if the string is not a number).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question