You'll get different results for the different methods depending on whether you compile with optimisations on. You basically have a few options:
object o;
//checking with is
o is int
//check type
o.GetType() != typeof( int )
//cast and catch exception
try{ int j = (int) o; }
catch {}
//use the tryparse
int.TryParse( Convert.ToString( o ), out j )
You can easily set up a console app that tries each of these 10,000 times and returns durations for each (test when o is an int and when it's something else).
The try-catch
method is the quickest if the object does hold an int, and by far the slowest if it doesn't (even slower than GetType
). int.TryParse
is pretty quick if you have a string, but if you have an unknown object it's slower.
Interestingly, with .Net 3.5 and optimisations turned on the o is int
check takes the same time as try-catch
when o actually is an int. o is int
is only slightly slower if o actually is something else.
Annoyingly FxCop will throw up warnings if you do something like:
if( o is int )
int j = (int) o;
But I think that's a bug in FxCop - it doesn't know int is a value type and recommends you to use o as int
instead.
If your input is always a string int.TryParse
is best, otherwise the is
operator is quickest.
As you have a string I'd look at whether you need to know that it's an int, rather than a double. If int.TryParse
passes then so will double.TryParse
so you could half the number of checks - return either double or string and floor the doubles when you expect an int.