Should I use the Convert class?

For example, in the following scenario

Convert.Int64(string somstring)

or

long.Parse(string somstring);

seem to do the same job. Which one is better?

thank

+3
source share
4 answers

If you look at the source, it Convert.ToInt64(string)just calls long.Parse, but first checks that the string is not null.

I would recommend calls long.Parsebecause it makes clarity (parsing strings) clearer.

I recommend using a class Convertif the type you are converting from may change. (Or if you go from object)

+4
source

long.TryParse, , , , .

+2

Convert.Int64calls long.Parseinternally, just performs a null check. Here are the guts:

if (value == null)
{
    return 0L;
}
return long.Parse(value, CultureInfo.CurrentCulture);

If you need a null check, Convert.Int64 is the safest thing, otherwise there is no difference.

+1
source

Convert.Int64 actually calls long.Parse with CultureInfo.CurrentCulture after the first execution of a null string check. So as long as you know that the string will not be empty, you can save this step and call long.Parse

0
source

Source: https://habr.com/ru/post/1734960/


All Articles