views:

124

answers:

4

Hi

I could write the following to convert a object to and 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.

+3  A: 
* 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

Henk Holterman
A: 

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.

jethro
If the object did implement IConvertable is there anything stopping me just using (IConvertible)myObject therefore cutting out a function call.
Ash Burlaczenko
If you sure that it isn't null you should call this method directly but note that in this form it can be opitmized by compiler so the method get inlined.
jethro
A: 

According to the documentation, it would depend on the object and whether or not it implements the IConvertible interface. There are a number of reasons that make these approaches different. Notably, if the string representation doesn't represent the corresponding integer value (e.g., "{ Value = 123 }") or the object isn't IConvertible. I would choose using Convert.ToInt32() as the conversion is defined by the type and not relying on some observed property that could change in the future.

Jeff M
A: 

As far as I know, Convert and Parse do differ in so many ways:

To convert means to cast an object from its original type to another type (if possible).However both objects are somehow equal in their own context for example "32" is the string version of 32 (as an integer).In some languages like Visual Basic this kind of conversion can happen implicitly.

To parse means to accept an input (usually in the form of an string) and to translate it to an object which can be a totally different thing. Take date as an example:We can parse "20 July 2010" which is a string to a date. It means that we have to translate the provided string into a date object that has 20 as its day,7 as its month and 2010 as it year. It is obvious that this task is not a straightforward one and a logic should be in place to parse the string.

Beatles1692