Search code examples
c#type-parameter

Typeparameter set from type argument


How do I convert my argument to a proper type declaration. Ie. how do I go from type to T in the following

class Foo<T>
{  
  Foo<??> MakeFoo(Type type)
  {
    return new Foo<??>();
  }

  Void Get(T aFoo)
  {
    ...
  }
}

Solution

  • You cannot.

    Generic parameters are used and applied by compiler while Type is a part of Reflections that are designed to work with type information in run-time. So you just cannot define which type compiler should use if you have only System.Type.

    However you can do the opposite:

    public void Foo<T>()
    {
      Type t = typeof(T);
    }
    

    So if you really do not need to use Type as a parameter you can do the following:

    Foo<FooParam> MakeFoo<FooParam>()
    {
      return new Foo<FooParam>();
    }