How to know <T> of generic type

I know <T> is instance type, but I can't to know which type is T.  The following code will get a compile error ('T' is a 'type parameter' but is used like a 'variable')

Please help me!!Tongue Tied

public class Test<T>
{
   public Test(){}
   public void DoSomething()
   {
         if (T is INullableValue)
            Do Case 1
         elseif (T is ISomeInterface)
            Do Case 2
   }

}




Answer this question

How to know <T> of generic type

  • ASP.Confused

    Or, in the case where you don't have a variable of type T you could do...



    if( typeof(T).GetInterface("System.INullableValue") != null
    )
       ;
     // Do something
    else
       ; // Do something

     


    Don't be tempted (as I was, if you read this before I corrected it) to replace this with "if typeof(T) is INullableValue", it won't work since then you would be checking if the class Type implements INullableValue (which it doesn't).



  • Vincent Fournier

    That's because T is actually a type parameter.

    What you want in your function:

    public void DoSomething(T MyVariable)
    {
        if (MyVariable is INullableValue)
           ; // Do something
        else
           ; // Do something else.
    }


  • How to know <T> of generic type