-
Aug 9th, 2016, 03:20 PM
#1
Type safe generic conversion from string?
Has anyone got a good bit of code to turn a string into a given type in a type-safe manner
i.e.
VB Code:
Public Shared Function FromString(Of TReturn)(ByVal stringValue As String) As TReturn
If (String.IsNullOrWhiteSpace(stringValue)) Then
If GetType(TReturn).IsPrimitive Then
'get the default
Else
Return Nothing
End If
Else
If GetType(TReturn).IsPrimitive Then
Else
End If
End If
End Function
Anyone got some good ideas on filling in those blanks?
-
Aug 9th, 2016, 05:04 PM
#2
Re: Type safe generic conversion from string?
Perhaps something like this:
Code:
Public Shared Function FromString(Of TReturn)(ByVal stringValue As String) As TReturn
If (String.IsNullOrWhiteSpace(stringValue)) Then
Return CType(Nothing, TReturn)
Else
Return CTypeDynamic(Of TReturn)(stringValue)
End If
End Function
Edit: After reviewing the CTypeDynamic code, I am withdrawing my previous recommendation to perform a check for IConvertible as: 1) the code I presented was a bogus implementation even-though it worked and 2) the CTypeDynamic method includes those checks with the proper implementation for the intrinsic types (Single, Integer, Boolean, etc.).
For non-intrinsic (i.e. User-code defined classes) you could add addition checks for specific type information to determine a proper conversion route.
Last edited by TnTinMN; Aug 10th, 2016 at 10:32 AM.
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
|