Type Conversion in C #

I am trying to create a generic method for type conversions that gets an object and the type of an object that needs to be distinguished.

Using Convert.ChangeType() , I can do what I want, but it takes too much time at runtime. What is the best way to make a general class the way I want.

My old code looks like this:

 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 fulfilled my request and returned a DataRow. And there is a column that is typed as a decimal, which I want to postpone to the end. If I call this method, it will take a long time to postpone the decimal.

And the type T of this method can only be a value type. I mean "T: struct"

+4
source share
1 answer

I still doubt your performance statements. Here is the 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)); } } 

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

In other words, I strongly suspect that the problem is not where you think.

+3
source

All Articles