Tuesday, May 7, 2013

Difference between typeof and typedefof

(In learning from "Programming F# 3.0, 2nd Edition")

There are two functions to know type information - typeof and typedefof. typeof shows information both class-itself and its type parameter while typedefof shows only class-itself and shows generics as-is.
> let typeOfSeqInt = typeof<seq<int>>;;

val typeOfSeqInt : System.Type =
  System.Collections.Generic.IEnumerable`1[System.Int32]

> let typeOfSeqGeneric = typeof<seq<'a>>;;

  let typeOfSeqGeneric = typeof<seq<'a>>;;
  ----------------------------------^^

stdin(7,35): warning FS0064: This construct causes code to be less generic than
indicated by the type annotations. The type variable 'a has been constrained to
be type 'obj'.

val typeOfSeqGeneric : System.Type =
  System.Collections.Generic.IEnumerable`1[System.Object]

> let typeDefOfSeqInt = typedefof<seq<int>>;;

val typeDefOfSeqInt : System.Type =
  System.Collections.Generic.IEnumerable`1[T]

> let typeDefOfSeqGeneric = typedefof<seq<'a>>;;

  let typeDefOfSeqGeneric = typedefof<seq<'a>>;;
  ----------------------------------------^^

stdin(9,41): warning FS0064: This construct causes code to be less generic than
indicated by the type annotations. The type variable 'a has been constrained to
be type 'obj'.

val typeDefOfSeqGeneric : System.Type =
  System.Collections.Generic.IEnumerable`1[T]

No comments:

Post a Comment