c# generic method return type code example

Example 1: c# reflection create generic type

Type generic = typeof(Dictionary<,>);

// Create an array of types to substitute for the type parameters of Dictionary. The key is of type string, and the type to be contained in the Dictionary is Test.
Type[] typeArgs = { typeof(string), typeof(Test) };

// Create a Type object representing the constructed generic type.
Type constructed = generic.MakeGenericType(typeArgs);

var instance = Activator.CreateInstance(constructedType);

Example 2: java return new instance of generic type

public static <E> void append(List<E> list, Class<E> cls) throws Exception {
    E elem = cls.newInstance();   // OK
    list.add(elem);
}
//You can invoke the append method as follows:
List<String> ls = new ArrayList<>();
append(ls, String.class);

Example 3: c# generic return type in interface

public interface IExample
{
  int GetInteger();
  T GetAnything<T>();
}