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

String.ToEnum<'a>

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.

Source

namespace Foo

open System

[<AutoOpen>]
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

Example

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: 5464