How to convert a string to an enum in C#?

Use this extension method:

using System;

namespace Rhyous.Extensions
{
    public static class StringExtensions
    {
        public static T AsEnum<T>(this string str, T defaultValue)
        {
            try { return (T)Enum.Parse(typeof(T), str, true); }
            catch { return defaultValue; }
        }
    }
}

So imagine you have this enum:

public enum LogLevel
{
   Debug,
   Information,
   Warning,
   Error,
   Fatal
}

Call it like this:

var levelStr = "Error";
LogLevel level = levelStr.AsEnum(LogLevel.Info);

Leave a Reply

How to post code in comments?