Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding ToString when creating interface type using object expression

Tags:

f#

Is there a way to override System.Object's virtual methods, particularly ToString, when creating an interface type using an object expression?

type INamedObject =
    abstract Name : string

let makeNamedObject name = 
    { new INamedObject with
        member x.Name = name
        override x.ToString() = x.Name } //would like to do this, but doesn't work
like image 469
Daniel Avatar asked Oct 24 '25 00:10

Daniel


1 Answers

It's possible to supplly multiple types to implement / override in an object expression including concrete types. This allows you to both specify Object and INamedObject in the expression and get the desired effect.

let makeNamedObject name =  
    { 
        new System.Object() with 
            member x.ToString() = name
        interface INamedObject with
            member x.Name = name  }
like image 53
JaredPar Avatar answered Oct 26 '25 20:10

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!