Search code examples
interfacef#automatic-properties

F# interfaces and properties


I'm trying to get a grip on F#, and in the process I am converting some C# code. I'm having some trouble with defining properties in an interface and implementing them in a type.

Consider the following code:

module File1

type IMyInterface =
    abstract member MyProp : bool with get, set
    abstract member MyMethod : unit -> unit

type MyType() = 
    interface IMyInterface with
        member val MyProp = true with get, set
        member self.MyMethod() = if MyProp then () else ()

The documentation for F# properties appears to state that my implementation of MyProp in MyType is correct, however, the compiler complains that "The value or constructor 'MyProp' is not defined". Any ideas?


Solution

  • To access the property within an (explicit) interface you need to cast to the self reference to the interface type:

    type MyType() = 
        interface IMyInterface with
            member val MyProp = true with get, set
            member self.MyMethod() = if (self :> IMyInterface).MyProp then () else ()
    

    You get the same error in C# if you implement the interface explicitly, and a cast is also required to access the member:

    interface IMyInterface
    {
        bool MyProp { get; set; }
        void MyMethod();
    }
    
    class MyType : IMyInterface
    {
        bool IMyInterface.MyProp { get; set; }
    
        void IMyInterface.MyMethod()
        {
            if (((IMyInterface)this).MyProp) { }
        }
    }