2
Answers

How to determine Generic Types in run-time

Hover

Hover

16y
7.7k
1

I wrote a test program which test many generic functions with the same type T.
I want to set the specific type in run-time in one place to facilitate the job, thus I don't need to change everywhere when I use these generic functions.

// Use TestType here, define TestType to specific types such as Int32, Double...

class myprogram
{

   invoke func1<TestType>;
   invoke func2<TestType>;
   invoke func3<TestType>;

}
Currently I am using "using TestType = Int32" at the beginning of the file to solve that problem. I am not sure if this is the only way to do that?

Another question is about determine the real type of a generic type. In my generic function, I have to determine the real type of the generic type T, thus I can use different code to process it.

public class myClass<T>
{

      public List<T> myfunc()
     {
         if (typeof(T) == typeof(Int32)
         {

               return  new List<Int32>();

         }     

         if (typeof(T) == typeof(Double)
         {

               return  new List<Double>();

         }  

     }

}

 

The above code can not compile. How can I implement that idea? or I should not use generic in such case?

 

Thanks

 

Answers (2)