3

In C#,I have a public function that can pass a List parameter, with T is a custom class. The function can pass with different T class. The problem that how to verify the type of T in every case?

public static List<T> ConvertData(List<T> oldDatas)
{
  //I will analyze the object T, 
  //but now i don't know how to verify the type of T, 
  //with T  can change,
  //example maybe T is T1 class,or T2 class..
}

Thanks for my stupid question.

VMAtm
  • 27,943
  • 17
  • 79
  • 125
phamminh05
  • 51
  • 5
  • 4
    Which language ? `C#`, `Java`? Tag the question with correct programming language you are using. – Naveen May 31 '11 at 09:41

4 Answers4

2

this is for C#

Type gt = typeof(T);

check this for java : Get generic type of java.util.List

Community
  • 1
  • 1
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
2

Do you need to make different converting depends on or just want to check for specific classes? In second case you can try to specify right types for T something like:

public static List<string> ConvertData(List<string> data)
{
    return PrivateConvertData<string>(data);
}

public static List<int> ConvertData(List<int> data)
{
    return PrivateConvertData<int>(data);
}

private static List<T> PrivateConvertData<T>(List<T> data)
{
    // code here
}

This code will check type of T during compilation.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
chopikadze
  • 4,219
  • 26
  • 30
2

just do :

public static class Test<T> 
    where T : class, new()
{
    public static List<T> ConvertData(List<T> oldDatas)
    {
        T instanceOfT = new T();
        Type typeOfT = typeof(T); // or instanceOfT.GetType();

        if(instanceOfT is string)
        {
            // T is a string
        }
        else if(instanceOfT is int)
        {
            // T is an int
        }
        // ...
    }
}

But that isn't productive and break the generic concept... Explain what you're trying to do.

Arnaud F.
  • 8,252
  • 11
  • 53
  • 102
1

You can use the typeof(T) keyword or use some check (if you are expecting some types to be passed via parameters):

 public static List<T> ConvertData(List<T> oldDatas)
 {
     foreach (var itemList in oldDatas)
     {
         if (itemList is LinqType)
         {
             var linqTypeItem = (LinqType) itemList;
             Console.WriteLine(linqTypeItem.PROPERTY_YOU_NEED);
         }
         // or
         var linqTypeItem = itemList as LinqType;
         if (linqTypeItem != null)
         {
             Console.WriteLine(linqTypeItem.PROPERTY_YOU_NEED);
         }
     }
 }

Also you can use the Cast() method. More information here

Community
  • 1
  • 1
VMAtm
  • 27,943
  • 17
  • 79
  • 125