Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Page History: Parser Class

Compare Page Revisions



« Older Revision - Back to Page History - Current Revision


Page Revision: Tue, Sep 15, 2009, 12:03 PM


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

Overview

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

Source Code

VB.NET

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

        Try
            value = DirectCast((mi.Invoke(Nothing, New Object() {input})), T)
            result = True
        Catch
        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

C#

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);

        try
        {
            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);
    }
}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.