How to use generic try-parse in VB.NET

1 Answer

0 votes
Imports System

Public Class MonoParserUtility

    ' Define a delegate matching the exact signature of standard TryParse methods in .NET
    Public Delegate Function TryParseHandler(Of T)(input As String, ByRef result As T) As Boolean

    ''' <summary>
    ''' Generic TryParse helper function optimized for Mono and .NET environments without static abstract interfaces.
    ''' </summary>
    ''' <typeparam name="T">The target type to parse into.</typeparam>
    ''' <param name="input">The raw string input.</param>
    ''' <param name="parser">The specific type's TryParse method delegate (e.g., AddressOf Integer.TryParse).</param>
    ''' <param name="result">The resulting parsed value if successful; otherwise, the default value.</param>
    ''' <returns>True if parsing succeeded; otherwise, false.</returns>
    Public Shared Function TryParseValue(Of T)(input As String, parser As TryParseHandler(Of T), ByRef result As T) As Boolean
        result = Nothing

        ' Guard clause: handle null or empty strings safely
        If String.IsNullOrEmpty(input) Then
            Return False
        End If

        ' Invoke the passed parser delegate
        Return parser(input.Trim(), result)
    End Function

    Public Shared Sub Main(args As String())
        ' 1. Parsing an Integer
        Dim intResult As Integer
        If TryParseValue(Of Integer)("2026", AddressOf Integer.TryParse, intResult) Then
            Console.WriteLine($"Successfully parsed int: {intResult}")
        End If

        ' 2. Parsing a Boolean
        Dim boolResult As Boolean
        If TryParseValue(Of Boolean)("true", AddressOf Boolean.TryParse, boolResult) Then
            Console.WriteLine($"Successfully parsed bool: {boolResult}")
        End If

        ' 3. Handling invalid parsing gracefully
        Dim invalidResult As Integer
        If Not TryParseValue(Of Integer)("not-an-int", AddressOf Integer.TryParse, invalidResult) Then
            Console.WriteLine("Failed to parse 'not-an-int' as expected, returning false safely.")
        End If
    End Sub

End Class


' run:
'
' Successfully parsed int: 2026
' Successfully parsed bool: True
' Failed to parse 'not-an-int' as expected, returning false safely.
'

 



answered Oct 28 by avibootz
...