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


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.


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

Author: Joel Mueller

Submitted on: 29 okt 2010

Language: F#

Type: System.String

Views: 3918