Is it possible to pass a type as a generic parameter to a function and return an instance of that ty

  • Thread starter Thread starter foolmelon
  • Start date Start date
F

foolmelon

It is something like

Public T myFunc<T>(Type type_Of_T, other params but none is for type
T...)
{
// create an instance of T
// do some other initialization for the instance of T
// return the instance of T
}
 
It is something like

Public T myFunc<T>(Type type_Of_T, other params but none is for type
T...)
{
// create an instance of T
// do some other initialization for the instance of T
// return the instance of T

}

Yes, but you don't need the type parameter. Try this:
public T myFunct<T>( params ) where T : new() {
T result;
result = new T();
return result;
}
 
Yes, but there are some caveats. First, you have to put the new
constraint on the function, like so:

public T MyFunction<T>(...) where T : new()
{
}

That will allow you to put code like this in your function:

public T MyFunction<T>(...) where T : new()
{
return new T();
}

In this case, T must have a parameterless (default) constructor.

Now, if you want to set values on T, you have to have some idea in the
function what T is. T will have to implement an interface and you have to
put the constraint on T in the function, like so:

public T MyFunction<T>(...) where T : IMyInterface, new()
{
}

Then, you can access instances of T as if they defined IMyInterface.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top