Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static extension methods supporting member constraints

I need to implement a static extension method supporting member constraints on some basic primitive types like integers, floats, etc. Here's 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 compiler complains with error:

The type 'System.Int32' does not support any operators named 'Foo'

What am I missing here? Thanks!

like image 840
Stringer Avatar asked Sep 09 '10 22:09

Stringer


People also ask

What is static extension method?

Essentially, an extension method is a special type of a static method and enable you to add functionality to an existing type even if you don't have access to the source code of the type. An extension method is just like another static method but has the “this” reference as its first parameter.

What is the difference between a static method and an extension method?

The only difference between a regular static method and an extension method is that the first parameter of the extension method specifies the type that it is going to operator on, preceded by the this keyword.

What is an advantage of using extension methods?

The main advantage of the extension method is to add new methods in the existing class without using inheritance. You can add new methods in the existing class without modifying the source code of the existing class. It can also work with sealed class.

Why extension methods are static?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.


2 Answers

Static member constraints in F# never find 'extension methods', they can only see intrinsic methods on types (and a few special cases called out in the F# language spec).

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

like image 131
Brian Avatar answered Sep 23 '22 23:09

Brian


F#'s static type constraints don't work with extension methods. Extension methods cannot statically be checked at compile time, and even so, you can have multiple definitions for Int32::Foo (depending on which namespace you imported).

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

like image 28
Chris Smith Avatar answered Sep 26 '22 23:09

Chris Smith