Another way of generating generic types

26Jul10

Kick post on Types, nothing outrageous, but this was just a construct that I never used too much.

The other day a collegue and we got stuck on a method similar to this

void DoStuff(Type type)
{
var iInterface = typeof(ISomethingAmazing);
Type genericType = //how to get ISomethingAmazing<type>

//do more things
}

and well I didn’t know but you can do this

void DoStuff(Type type)
{
var iInterface = typeof(ISomethingAmazing);
Type genericType = iInterface.MakeGenericType(new Type[] { type });

//do more things
}

Why would you want this?
well say for example, you are working with a container and need to get all the ISomethingAmazing of whatever your type is
Particularly handy if you are using a handlers or factories a lot.

What happened?

Basically we just had information about the types we wanted but at compile type we didnt know the types, this is a away to return a runtime type even when you dont know what that type is.

I hope this is helpful for someone

Cheers

Advertisements


No Responses Yet to “Another way of generating generic types”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: