CaffGeek
CaffGeek

Reputation: 22054

Casting/Type Conversion Performance

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));

Upvotes: 2

Views: 3330

Answers (1)

LukeH
LukeH

Reputation: 269328

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.)

Upvotes: 4

Related Questions