Rob P.
Rob P.

Reputation: 15071

How Do I Create Something 'OF' a Variable's Type?

I have some code like:

Lookup(Of String)("Testing")
Lookup(Of Integer)("Testing")

And both of those Lookups work great. What I'm trying to is call the appropriate LookUp based on the type of another variable. Something that would look like...

Lookup(Of GetType(MyStringVariable))("Testing")

I've tried to Google this but I'm having a hard time coming up with an appropriate search. Can anyone tell me how to do what I want?

Upvotes: 2

Views: 2697

Answers (4)

Pavel Minaev
Pavel Minaev

Reputation: 101555

You do not specify the full signature for the method that you're calling, but my psychic powers tell me that it is this:

Function Lookup(Of T)(key As String) As T

And you want to avoid having to repeat Integer twice as in the example below:

Dim x As Integer
x = Lookup(Of Integer)("foo");

The problem is that type parameters are only deduced when they're used in argument context, but never in return value context. So, you need a helper function with a ByRef argument to do the trick:

Sub Lookup(Of T)(key As String, ByRef result As T)
    T = Lookup(Of T)(key)
End Sub

With that, you can write:

Dim x As Integer
Lookup("foo", x);

Upvotes: 5

eidylon
eidylon

Reputation: 7238

The VB.NET compiler in VS2008 actually uses type-inference. That means if you are using a generic method, and one of the parameters is of the generic type, then you don't need to specify the generic type in your call.

Take the following definition...

Function DoSomething(Of T)(Target As T) As Boolean 

If you call it with a strongly-typed String for Target, and don't specify the generic parameter, it will infer T as String.
If you call it with a strongly-typed Integer for Target, and don't specify the generic parameter, it will infer T as Integer.

So you could call this function as follows:

Dim myResult As Boolean = DoSomething("my new string")

And it will automatically infer the type of T as String.

EDIT:
NOTE: This works for single or multiple generic parameters.
NOTE: This works also for variables in the argument list, not just literals.

Upvotes: 1

Guffa
Guffa

Reputation: 700152

You can't use a dynamic type unless you do runtime compiling, which of course is really inefficient.

Although generics allows you to use different types, the type still has to be known at compile time so that the compiler can generate the specific code for that type.

This is not the way to go. You should ask about what problem you are trying to solve, instead of asking about the way that you think that it should be solved. Even if it might be possible to do something close to what you are asking, it's most likely that the best solution is something completely different.

Upvotes: 1

scott
scott

Reputation: 746

One solution to this is to use reflection. See this question for details.

Upvotes: 1

Related Questions