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
invoke func2
invoke func3
}
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
{
public List
{
if (typeof(T) == typeof(Int32)
{
return new List
}
if (typeof(T) == typeof(Double)
{
return new List
}
}
}
The above code can not compile. How can I implement that idea? or I should not use generic in such case?
Thanks
AlanPosted Oct 4, 2008, 5:33 PM
Yes, the alias form of the 'using' directive is the only way to give a type an alias in C# as we don't have C++'s typedef.
Also typeof(T) is the only way I know of to get the runtime type of a type parameter.
The compiler tends to get in the way in generic code and you may need to use an (officially sanctioned) hack when assigning values to generic types. For example, whilst the compiler won't let you assign an Int32 value to a type T variable and won't allow you to cast it to type T either, you can get around this by casting it to Object first and then to type T. So, the following program compiles and runs fine:
using System;
using System.Collections.Generic;
using TestType = System.Double;
class Test mc = new myClass(); list = mc.myfunc();
{
static void Main()
{
myClass
List
Console.WriteLine(list[0]);
Console.ReadKey();
}
}
public class myClass
{
public List myfunc() list = new List();
{
List
if (typeof(T) == typeof(Int32))
{
list.Add((T)(object)2);
}
if (typeof(T) == typeof(Double))
{
list.Add((T)(object)2.5);
}
return list;
}
}
HoverPosted Oct 5, 2008, 3:45 PM
Thanks Alan. The method is neat and works perfect. I was using two different functions for Int32 type and Double type (with different function names). Actually, the difference between the two functions was only one line, which invoked different Random class methods to generate Int32 data and Double data. Although my solution is type-safe, but it has many redundant codes. As a test program, I would like give up some performance and choose type-casting as your sample code.
Thanks.