Enum Factory

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
}

3 Comments

  • hsd

    Hi Marcin,
    I have only one suggestion to that helper class.
    The form of that class should be similar to Int32 implementation. That class should provide two functions, one like yours but with name ‘Parse’ and additional ‘TryParse’. The second is important because very often you would like to parse some thing but you would like do not care about the exception stuff. This is especially nice when you have to care about your most favorite friend like FxCop 🙂
    Regards Hsd

Leave a Reply

Your email address will not be published. Required fields are marked *