namespace Foo

open System

module FsExtensions =

    type String with
        /// Strongly-typed shortcut for Enum.TryParse(). Defaults to ignoring case.
        member this.ToEnum<'a when 'a :> Enum and 'a : struct and 'a : (new: unit -> 'a)> (?ignoreCase) =
            let ok, v = Enum.TryParse<'a>(this, defaultArg ignoreCase true)
            if ok then Some v else None
match "DarkRed".ToEnum<ConsoleColor> with
| Some x -> "Parsed successfully."
| None   -> "Not a valid value."


Shortcut for the .NET 4 Enum.TryParse(). Defaults to ignoring case, returns an F# Option to indicate success/failure. Unlike a C# extension method, this is able to enforce that the generic type is an enum at compile time.


Double click on the code to select all.