Question

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)
  {
    ...
  }
}
Was it helpful?

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>();
}

OTHER TIPS

You can't do such thing, because "Type" is a set of reflected metadata of classes, structures and/or enumerations.

"T" is the type.

You can give the type as argument using reflection:

type.MakeGenericType(type).GetConstructor(Type.EmptyTypes).Invoke(null)

But I'll vote to add a generic parameter "S" instead of input parameter "Type type" in order to avoid the use of reflection, which is useless in this case if you do it right!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top