tags:

views:

126

answers:

2

How to get 'System.Type' of the module?

For example module:

module Foo =
     let bar = 1

And this does not work:

printfn "%s" typeof<Foo>.Name

Error is:

The type 'Foo' is not defined
+2  A: 

It would certainly be nice to have a moduleof operator... Since there's not one, the easiest way to do what you want is probably to use the Metadata library in the F# PowerPack:

#r "FSharp.PowerPack.Metadata.dll" 
open Microsoft.FSharp.Metadata

// get .NET assembly by filename or other means
let asm = ...

let fasm = FSharpAssembly.FromAssembly asm
let t = fasm.GetEntity("Foo").ReflectionType

Unfortunately, this won't work with dynamic assemblies (such as those generated via F# Interactive). You can do something similar using vanilla System.Reflection calls, but that's more dependent on having a good understanding of the compiled form that your module takes.

kvb
Main problem is that 'FSharpAssembly.FromAssembly asm' loads all types. Also reduce type safety.
Mike Chaliy
@Mike - I'm not sure what you mean by "reduce type safety"... There is no way to use a module as a generic type parameter, so you will have to use a string. This is unfortunate, but unavoidable.
kvb
A: 

module name is not a type.

List in List.map and let (a:List<int>) = [1;2;3] are different.

The first List is a module name, the second is a type.

Yin Zhu
I am concerned about 'FSharpType.IsModule(System.Type)', so module IS type, at least in CLR terms.
Mike Chaliy