kuskmen
kuskmen

Reputation: 3775

Get type of a module at compile time in F#

We know that in C# we can get type of a type at compile time using typeof(OutType) this lets us pass this to attributes later as it is constant expression.

I saw this question, but it doesn't really address the compile time usage.

So my question is: Is there a way to get System.Type of a given module at compile type within F# standard library?

Upvotes: 2

Views: 488

Answers (2)

scrwtp
scrwtp

Reputation: 13577

F# disallows obtaining a module's type using its typeof operator by design, as they're not first-class concepts in the language.

From the spec, section 13.2:

F# modules are compiled to provide a corresponding compiled CLI type declaration and System.Type object, although the System.Type object is not accessible by using the typeof operator.

Modules compile to static classes however, so it is possible to obtain the type at runtime using reflection (and that's what happens in typeof<MyModule.Dummy>.DeclaringType example), and it's possible to obtain the type of a module defined in a referenced F# assembly using typeofoperator in C#.

For what you're trying to do, you'd best use a class instead of a module, because then you can get hold of the type without hassle:

type MyFactoryClass = 
    static member TestCases = [ 1; 2; 3 ]

...

[<Test; TestCaseSource(typeof<MyFactoryClass>, "TestCases">] 
let test (arg: int) = ...

Upvotes: 3

TheQuickBrownFox
TheQuickBrownFox

Reputation: 10624

If you are OK to refer to a type inside that module (or create a dummy one if there are no types), you could do this:

module MyModule =
    type Dummy = Dummy

let myModule = typeof<MyModule.Dummy>.DeclaringType

Upvotes: 1

Related Questions