Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamic creation of objects of a given type with a given value

Status
Not open for further replies.

aitor

Programmer
May 15, 2001
18
ES
Let´s suppose I have an string representation of a type (i.e, "System.Int32") and an string representation of a value (i.e, "33").

What I wanna do is to create an object of that type with that value, without using an obvious function like this:

Private Function CreateObject(ByVal strType As String, ByVal strValue As String) As Object

Select Case strType

Case "System.Boolean"
Return CBool(strValue)
Case "System.Byte"
Return CByte(strValue)
Case "System.Char"
Return CChar(strValue)
Case "System.DateTime"
Return CDate(strValue)
Case "System.Double"
Return CDbl(strValue)
Case "System.Decimal"
Return CDec(strValue)
Case "System.Int32"
Return CInt(strValue)
Case "System.Int64"
Return CLng(strValue)
Case "System.Int16"
Return CShort(strValue)
Case "System.Single"
Return CSng(strValue)
Case "System.String"
Return CStr(strValue)
Case Else
Return CObj(strValue)
End Select

End Function

Is there any native .NET way to do it??. I have tried with ctype, but it doesn´t allow to specify a type given in string format, neither can I find a way using Reflection.

Thanks,

Aitor.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top