Static extension methods supporting element restrictions

I need to implement a static extension method that supports element restrictions for some basic primitive types, such as integers, floats, etc. Here is my code for signed integers:

module MyOperators = let inline foo (x : ^T) = (^T : (static member Foo : ^T -> int) (x)) type System.Int32 with static member Foo(x : Int32) = 7 // static extension 

Test code:

 open MyOperators let x = foo 5 // x should be 7 

But the compiler complains about the error:

Type "System.Int32" does not support any statements named "Foo"

What am I missing here? Thank!

+5
extension-methods f # type-constraints
Sep 09 '10 at 10:54
source share
2 answers

Constraints of a static member in F # never find "extension methods", they can only see internal methods for types (and a few special cases called in the F # language specification).

Perhaps you can use method overloading? What is your ultimate goal?

+5
Sep 09 '10 at 23:00
source share

F # static type constraints do not work with extension methods. Extension methods cannot be statically checked at compile time, and even then you can have several definitions for Int32 :: Foo (depending on which namespace was imported).

Unfortunately, you may have to resort to using reflection to solve your problem.

+3
Sep 09 '10 at 23:00
source share



All Articles