FreeBSD FridayProgramming / DevelopmentWPF Databinding TutorialMy Posts

Welcome to my technology learning website. The goal of this site is to learn and retain as much information as possible. I consider this blog my knowledge base and hope that you both find and share knowledge here as well. Also for those wondering, Rhyous is pronounced ‘rī-əs. As in the words ‘Rye‘ and ‘us‘ compounded into a two syllable word.

Please take a moment to subscribe, or setup an RSS feed so you never miss a post.

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

Call it like this:

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

Leave a Reply

How to post code in comments?