Enum Factory

August 10, 2008 on 9:16 pm | In Uncategorized | 2 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
}

2 Comments »

RSS feed for comments on this post. TrackBack URI

  1. 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

    Comment by hsd — %A %B %e%q, %Y #

  2. @Hsd: right. As usual!

    Comment by Marcin Kawalerowicz — %A %B %e%q, %Y #

Leave a comment

XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

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