Parser Class

This page is part of the Class Library Pages collection.
Click the icon to see the index.


The Parser class provides a generic means of parsing a string as any data type.

Source Code


Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Net
Imports System.Reflection

Public Class Parser(Of T)

    Public Shared Function TryParse(ByVal input As String, ByRef value As T) As Boolean

        Dim result As Boolean = False
        Dim type As Type = GetType(T)
        Dim pt As Type() = New Type() {GetType(System.String)}
        Dim mi As MethodInfo = type.GetMethod("Parse", pt)
        value = Nothing

            value = DirectCast((mi.Invoke(Nothing, New Object() {input})), T)
            result = True
        End Try

        Return result

    End Function
    Public Shared Function ParseEnum(input As String) As T

        Return CType([Enum].Parse(GetType(T), input), T)

    End Function

End Class


using System;
using System.Reflection;

public class Parser<T>
    public static bool TryParse(string input, out T value)
        bool result = false;
        Type type = typeof(T);
        Type[] pt = new Type[] { typeof(System.String)};
        MethodInfo mi = type.GetMethod("Parse", pt);
        value = default(T);

            value = (T)(mi.Invoke(null, new object[] {input}));
            result = (value != null);
        catch {}

        return result;
    public static T ParseEnum(string input)
        return (T)Enum.Parse(typeof(T), input);