Enum Factory

August 10, 2008 on 9:16 pm | In Uncategorized | 3 Comments

I have a little tip for you. Let’s say you have an enumeration. You need a enumeration constant out of string variable. simply use System.Enum.Parse(). Here a small Snippet Compiler source code.

using System;
using System.Collections.Generic;

public class MyClass
{
    public enum FooBar
    {
        Foo,
        Bar,
        FooBar
    }

    public static void Main()
    {
        WL(FooBarFactory("Foo"));
        RL();
    }

    public static FooBar FooBarFactory(string init)
    {
        try
        {
            return (FooBar)System.Enum.Parse(typeof(FooBar), init);
        }
        catch
        {
            // Do something
            throw;
        }
    }

    #region Helper methods

    private static void WL(object text, params object[] args)
    {
        Console.WriteLine(text.ToString(), args);
    }

    private static void RL()
    {
        Console.ReadLine();
    }

    private static void Break()
    {
        System.Diagnostics.Debugger.Break();
    }

    #endregion
}

Powered by WordPress with Pool theme design by Borja Fernandez.
Text © Marcin Kawalerowicz. Hosting CODEFUSION.