Answer the question
In order to leave comments, you need to log in
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
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.
And there is also a package that chooses the appropriate conversion method itself.
https://habr.com/post/315352/
To understand what the difference is, then see the source - the source code is here (on line 887).
In general, it Parse
takes a string and returns a number (maybe there will be an exception). Convert.ToInt16
has 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 questionAsk a Question
731 491 924 answers to any question