You are previewing Programming F#.

Programming F#

Cover of Programming F# by Chris Smith Published by O'Reilly Media, Inc.
O'Reilly logo

Type Reflection

So you have learned how to attribute code, but what if you wanted to inspect those attributes? You can access attributes on code through type reflection.

Recall that everything in .NET inherits from System.Object, and therefore every value in .NET has a GetType method, which returns an instance of System.Type. The Type class describes everything there is to know about a type—including its attributes.

Accessing Types

The following FSI session defines a custom type named Sprocket and then uses two different methods to access its type information. The first method used in the sample is the generic typeof<_> type function, which returns the type of the supplied type parameter. The second method used is to call the GetType method found on an instance of Sprocket because it inherits from obj:

> // Simple sprocket type
type Sprocket() =
    member this.Gears = 16
    member this.SerialNumber = "WJM-0520";;

type Sprocket =
  class
    new : unit -> Sprocket
    member Gears : int
    member SerialNumber : string
  end

> // Get type information via typeof<_>
let type1 = typeof<Sprocket>;;

val type1 : System.Type = FSI_0002+Sprocket

> // Get type information via GetType
let aSprocket = new Sprocket()
let type2 = aSprocket.GetType();;

val aSprocket : Sprocket
val type2 : System.Type = FSI_0002+Sprocket

> type1 = type2;;
val it : bool = true
> type1.Name;;
val it : string = "Sprocket"

Accessing generic types

While typeof<_> is helpful for getting type information, when used on generic types it must fix any ...

The best content for your career. Discover unlimited learning on demand for around $1/day.