Results 1 to 2 of 2

Thread: Type safe generic conversion from string?

  1. #1

    Thread Starter
    PowerPoster
    Join Date
    Jul 2002
    Location
    Dublin, Ireland
    Posts
    2,148

    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:
    1. Public Shared Function FromString(Of TReturn)(ByVal stringValue As String) As TReturn
    2.  
    3.         If (String.IsNullOrWhiteSpace(stringValue)) Then
    4.             If GetType(TReturn).IsPrimitive Then
    5.                 'get the default
    6.  
    7.             Else
    8.                 Return Nothing
    9.             End If
    10.         Else
    11.             If GetType(TReturn).IsPrimitive Then
    12.  
    13.  
    14.             Else
    15.  
    16.  
    17.             End If
    18.         End If
    19.  
    20.  
    21.     End Function

    Anyone got some good ideas on filling in those blanks?

  2. #2
    PowerPoster
    Join Date
    Oct 2010
    Posts
    2,141

    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
  •  



Click Here to Expand Forum to Full Width