generic newbie: returning TYPE from a method

  • Thread starter Thread starter sklett
  • Start date Start date
S

sklett

I'd like to create a method like this:
private T FindCustomField<T>(string fieldID)
{

}

the compiler doesn't like that very much, I'm not sure if it's even possible
to use a Type parameter as the return type. Anyone know?

Thanks,
Steve
 
ah, looks like it is possible, I had a typo. Sorry for the false alarm.
Now I just need to learn how to tell the method that T is a class so I can
use the 'as' operator to cast a base class down to a T type.
 
You can use a type constraint on generic classes to make sure the type
given is a class. I'm not sure about generic methods.

public class Thing<T> where T new()
{
}

DC
 
ah, looks like it is possible, I had a typo. Sorry for the false alarm.
Now I just need to learn how to tell the method that T is a class so I can
use the 'as' operator to cast a base class down to a T type.

private T FindCustomField<T>(string fieldID) where T : class

Jon
 
You can apply the constraint on the method just like you can on the
class:

private T FindCustomField<T>(string fieldID) where T : class
{

}

Also, to Lee, it should be noted that placing the new() constraint on
the type parameter will not guarantee that it only uses a reference type.
The new() constraint only limits the type to types that have a parameterless
constructor.
 
Thank you all for the help! :0)

I found the MSDN docs on constraints and it makes sense now.
 

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