views:

160

answers:

1

I have the following extension method

public static T Field<T>(this DataRow row, string columnName)
{
    return (T)Convert.ChangeType(row[columnName], typeof(T));
}

It works, but I'm trying to speed it up. Is there a way to speed that up? With a case statement and then type specific conversions? I've tried a few things like using int.Parse, but even though I know I want an int returned, I have to use ChangeType to get it to compile.

 return (T)Convert.ChangeType(intVal, typeof(T));
+2  A: 

Do you actually need to perform a conversion, or are you just casting?

If you just need a cast then a simple return (T)row[columnName]; should do the trick.

(By the way, is using Convert.ChangeType really causing performance problems? This sounds like unnecessary micro-optimisation to me. Having said that, I'd probably prefer the plain cast for readability reasons, assuming that it meets your requirements.)

LukeH
@Luke, plain cast doesn't always work, whereas Convert.ChangeType seems to always be returning the correct value no matter the type I throw at it.
Chad
@Chad: Can you give some examples of where casting doesn't work but `ChangeType` does? eg, What's the underlying type/value of the column and what type are you trying to convert it to?
LukeH
@Luke, the underlying types vary, but they should always be convertible to one of the following: string, int, bool, DateTime, byte, float, decimal.
Chad
@Chad: Understood. In that case I'd stick with `ChangeType`. Is it really creating any performance problems?
LukeH
@Luke, it looked like it, but I don't think the performance analyzer is showing me everything...
Chad