Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Convert and Parse?

I could write the following to convert an object to an integer.

Convert.ToInt32(myObject);

But I could also write

Int.Parse(myObject.ToString());
  • Is there any difference?
  • Which one should I be using?

Thanks in advance.

like image 506
Ash Burlaczenko Avatar asked Aug 15 '10 09:08

Ash Burlaczenko


2 Answers

  • Is there any difference?

Yes, Int32.parse(myObject.ToString()); takes a detour to string, that will usually work but it is unnecessary and it might fail or give a different result.

  • Which one should I be using?

In general, Convert.ToInt32(myObject);

But it depends on what type of data you want to convert.

If myObject = '1'; , do you want 1 or 49 ?

If myObject = false; , do you want 0 or an exception ?

etc

like image 128
Henk Holterman Avatar answered Sep 29 '22 07:09

Henk Holterman


This how Convert.ToInt32 method source looks like

public static int ToInt32(object value) {
    return value == null? 0: ((IConvertible)value).ToInt32(null); 
}

As long as your object implement IConvertible interface you should call this method.

like image 30
jethro Avatar answered Sep 29 '22 08:09

jethro