ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

Enum.ParseWithDefault

.NET 4.5 version of Enum.ParseUnstrict

Source

public static T ParseWithDefault<T>(this Enum self, string value, T defaultValue = default(T)) where T : struct
{
    T res;
    var done = Enum.TryParse(value, true, out res);

    return done ? res : defaultValue;
}

Example

public enum Example{
   A = 0, // default Value
   B = 1,
   C = 2
}

var c = Enum.ParseWithDefault<Example>("D"); (c = Example.A)
var c = Enum.ParseWithDefault<Example>("D", Example.C); (c = Example.C)

Author: JohnnyOddSmile

Submitted on: 28 apr 2014

Language: C#

Type: System.Enum

Views: 5971