views:

38

answers:

1

I figured this would be a quick google, but extensive searching hasnt yielded any results. Everything about type conversion seems to dance around this concept.

I want to get the type of variable "a", and make a new variable named "b" of that type. Otherwise I could have "a" as a type already declared and "b" simply as an Object, then try to cast "b" to the type of "a".

Dim a As Integer  
Dim b As Whatever a Is  

OR

TryCast(b, Whatever a Is)

I would also like to make the conversion using a variable representation of the type, but cant find info on how to do that either.

Sorta like:

Dim a As Integer  
Dim b As Object  
Dim t As Type  

t = a.GetType()

TryCast(b, t)

Realizing I'm completely misusing TryCast here, I'm mostly trying to get my goal across. I figured it would be an easy quick thing to do but I cant really find any specific info on it. Any ideas?

A: 

Someone posted the correct answer but then erased it so I'll repost:

    Dim a As Integer
    Dim b = Activator.CreateInstance(a.GetType())

b will be an Object from the IDE's perspective because reflection happens at runtime. But if you call GetType on b you'll get System.Int32.

I'm still curious as to why you'd ever want to do this though.

Chris Haas
Long story short, Its for receiving column schema data from an MS SQL database, and creating run-time controls with parameters to properly represent their values. I.E. I read a column of type "nvarchar". nvarchar should have a "textbox" control. So I'll create a "textbox" control at run-time to represent that column. The reason for the type conversion: I had originally thought of mapping different SQL types to the control they should have in a multi-dimensional array. Array("nvarchar", TextBox) Now I question that though...simply because the multitude of different SQL types out there.
instantmusic
Awesome, it works! Thanks
instantmusic
Thanks @user337501, seems like you had a valid reason for it. Most people that I see going down this path are usually not getting something and thus end up doing things the hard way so I had to ask.
Chris Haas