|
-
Dec 28th, 2003, 11:33 PM
#1
Thread Starter
Addicted Member
Dynamic Type Handling [Resolved]
Hi guys,
How do you do dynamic type switching? What I need to be able to do is change the type of an object based on a string.
For example
VB Code:
myObject = CType(passedObject, "System.String")
I've tried something along the lines of.
VB Code:
Dim myType As Type
Dim strType As String = "System.String"
Dim myObject As Object
myType = System.Type.GetType(strType)
myObject = CType(passedObject, myType)
Where strType could obviously be anything.
.Net is complaining that it cannot find the type of myType. So how do I accomplish doing type conversions when I don't know the type I want to convert to until runtime. (I know I could do a large select case, but I'd rather avoid this.)
Last edited by Carnifex; Dec 29th, 2003 at 07:20 PM.
-
Dec 29th, 2003, 01:55 AM
#2
yay gay
Do you really only know at run-time which type of data you want? You could put a 'select case' thing
otherwise i think you'll have to use reflection
\m/  \m/
-
Dec 29th, 2003, 02:31 AM
#3
Thread Starter
Addicted Member
Yea, I shoulda clicked about reflection, will play with it @ work tommorow.
Select case will work, it just seems like messy code for something that should be relatively simple. (Messy because there are about 20 possible data types, so to do a select case for all of them would be alot of lines of code, for what I would consider a simple higher level operation)
-
Dec 29th, 2003, 02:46 AM
#4
Frenzied Member
I still wonder how it can be done by reflection or activator. You can create an instance of desired object with its type name as string, but how you may change type of another object to the type of this new object or any other object?
Last edited by Lunatic3; Dec 29th, 2003 at 03:11 AM.
'Heading for the automatic overload'
Marillion, Brave, The Great Escape, 1994
'How will WE stand the FIRE TOMORROW?'
Eloy, Silent Cries and Mighty Echoes, The Vision - Burning, 1979
-
Dec 29th, 2003, 03:07 AM
#5
Maybe the thing you should be asking is if you really need to convert it at all. I mean why wont the generic object type work? You really can't code for its string type anyway since you wont know what it is at designtime.
You can also look at the ConvertTo function of the System.ComponentModel.TypeConverter object if you still need to convert it.
-
Dec 29th, 2003, 07:19 PM
#6
Thread Starter
Addicted Member
Thanks Edeenis.
System.ComponentModel.TypeConverter was exactly what I was after.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|