When to use F#'s typedefof<'T> vs. typeof<'T>?

typeof is used when you want to get the System.Type object for a given type. typedefof is used when you want to get the System.Type that represents the type definition for a generic type. As an example that uses both, suppose you had a type called Generic<'a>, and you wanted to create a function that returned the System.Type object for the Generic of any given type.

type Generic<'a> = Value of 'a

let makeGenericOf<'a> () = 
    typedefof<Generic<_>>.MakeGenericType(typeof<'a>)

Here, you would use the typedefof function to get the type defintion, and typeof to get the type of 'a for constructing the generic Generic<'a> Type.


This ought to illustrate the difference. When you use typeof, the compiler infers type arguments and constructs a concrete type. In this case, the inferred type argument is System.Object:

let t1 = typeof<System.Collections.Generic.List<_>>
let t2 = typedefof<System.Collections.Generic.List<_>>

printfn "t1 is %s" t1.FullName
printfn "t2 is %s" t2.FullName

Output:

t1 is System.Collections.Generic.List`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
t2 is System.Collections.Generic.List`1

Because typeof can only return a constructed type, typedefof is necessary if you need a type object representing a generic type definition.

Tags:

F#