Ehsan Ghanbari

Experience, DotNet, Solutions

Using Generic type for type casting in F#

In order to validate some input of type object into numeric types, you can use System.Convert in C#. We have them in F# as well! Look at the following function:


open System

let validate<'a, 'b> (cast: 'a -> 'b) (x: 'a) =
        cast x |> Some
    with _ -> None

let a = validate int "3423"
let d = validate<obj, decimal> Convert.ToDecimal (null :> obj)
let e = validate<string, DateTime> Convert.ToDateTime "2017-10-10"


Validate has been used to convert obj to decimal and even to DateTime. In order to see the result of the following piece of code, you can use it in F#.Net Core console application: 



let main argv =

    printfn "%A" e // or d and a that has calculated by Validate<,>



About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
Peridic pattern
How to use PagedList In MVC
How to query over Icollection<> of a type with linq
Domain driven design VS model driven architecture
What's the DDD-lite?
Redis as a cache server