Calling a generic function with an instance of a type

I have been struggling with this problem for quite some time and cannot find a solution. Let me simplify this for you.

I have a generic function that I want to call, but the type argument I want to call is only as an instance. Example

let foo_a<'a> () = typeof<'a>
let foo_b (t : System.Type) = foo_a<t>() // of course this does not work

      

I would like the following statement to be true

foo_a<int>() = foo_b(typeof<int>)

      

In C #, I would reflect foo_a MethodInfo and do MakeGenericMethod (t), but how do I do that in F #?

Just to clean up by reversing the dependency and making foo_a call foo_b instead, that's not an option for me.

+3


source to share


1 answer


As @svick said, there is no specific way to do this in F # - you need to use Reflection the same way you do in C #.

Here's a simple example that you can paste into F # interactive:

open System.Reflection

type Blah =
    //
    static member Foo<'T> () =
        let argType = typeof<'T>
        printfn "You called Foo with the type parameter: %s" argType.FullName


let callFoo (ty : System.Type) =
    let genericFoo =
        typeof<Blah>.GetMethod "Foo"

    let concreteFoo =
        genericFoo.MakeGenericMethod [| ty |]

    concreteFoo.Invoke (null, Array.empty);;  // The ;; is only needed for F# interactive

      



Output:

> callFoo typeof<int>;;
You called Foo with the type parameter: System.Int32
val it : obj = null

      

+3


source







All Articles