views:

566

answers:

1

I'm trying to make a generic method for type conversions which gets an object and the type of object to be cast.

By using Convert.ChangeType() I can do what I want, but it takes too much time on run time. What is the best method to make a generic class like I want.

My old code looks like that;

public static ConvertTo<T>(object data) where T : struct // yes the worst variable name!
{
  // do some controls...

  return Convert.ChangeType(data, typeof(T));
}

Edit: To clarify...

For Ex; I've executed my query and it returned a DataRow. And there is a column which typed as decimal which I want to cast to long. If I call this method, it takes so much time to cast decimal to long.

And T type of this method could be only value type. I mean "T : struct"

+3  A: 

I still doubt your performance claims. Here's evidence. Compile and run the program below (in release mode):

using System;
using System.Diagnostics;

class Test
{
    const int Iterations = 100000000;

    static void Main()
    {
        Stopwatch sw = Stopwatch.StartNew();
        decimal d = 1.0m;
        long total = 0;
        for (int i=0; i < Iterations; i++)
        {
            long x = ConvertTo<long>(d);
            total += x;
        }
        sw.Stop();
        Console.WriteLine("Time: {0}ms", sw.ElapsedMilliseconds);
        Console.WriteLine("Total: {0}", total);
    }

    public static T ConvertTo<T>(object data) where T : struct
    {
        return (T) Convert.ChangeType(data, typeof(T));
    }
}

That takes 20 seconds on my laptop - to execute 100,000,000 iterations. It's hard to believe that it takes 8 seconds on your computer to execute 40 iterations.

In other words, I strongly suspect that the problem isn't where you think it is.

Jon Skeet
Actually, I saw the elapsed time on another machine and maybe I missed something. When I tried I didn't take this much time. I'll check the code on that machine and I'll be right back to you.
yapiskan