Checking the type of a custom class in a function

In C #, I have an open function that can pass a List parameter, and T is a custom class. A function may pass with another T-class. The problem is, how to check type T in each 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.

+3
source share
4 answers

this is for c #

Type gt = typeof(T);

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

+2
source

Do you need to do another conversion, depends on or just wants to test certain classes? In the second case, you can try to specify the correct types for T, for example:

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 for type T at compile time.

+2
source

:

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
        }
        // ...
    }
}

... , .

+2

You can use the keyword typeof(T)or use some checking (if you expect some types to be passed through 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);
         }
     }
 }

You can also use the method Cast(). More here

+1
source

All Articles