I have a list of types (System.Type) which need te be queried on the database.
For each of this types, I need to call the following extensionmethod (which is part of LinqToNhibernate):
Session.Linq<MyType>()
However I do not have MyType, but I want to use a Type instead.
What I have is:
System.Type typeOne;
But I cannot perform the following:
Session.Linq<typeOne>()
How can I use a Type as a Generic parameter?
You can’t, directly. The point of generics is to provide compile-time type safety, where you know the type you’re interested in at compile-time, and can work with instances of that type. In your case, you only know the
Typeso you can’t get any compile-time checks that any objects you have are instances of that type.You’ll need to call the method via reflection – something like this:
If you need to use this type a lot, you might find it more convenient to write your own generic method which calls whatever other generic methods it needs, and then call your method with reflection.