mardi 29 novembre 2016

Get Type of nested Generic, create new Object of that Type

Is there a good way to achieve the following? Basic idea is have a generic method that may take a List as T, get the Type of J and create a new List within the method. And further create an instance of J

public static void foo<T>(T obj)
{
    // i checked that T is of type IList
    // Create new List of T underlying Type
    List<nestedType> = new List<nestedType>();
    nestedType o = new nestedType();
}

What i have achieved so far

public static void foo<T>(T obj)
{
   var t = typeof(T); 
   if(t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IList<>)))
        {
            Type underlyingType = t.GetGenericArguments().Single();
            dynamic varOfUnderlyingType = Convert.ChangeType(??, underlyingType);
        }
}





Aucun commentaire:

Enregistrer un commentaire