Chris Long
Chris Long

Reputation: 3074

Can an object expression refer to itself?

I'm exploring converting our C# codebase to F#. This codebase uses an external library that provides an interface; one of the methods allows the library to create new instances of our class:

public class Worker : IWorker
{
    public IWorker CreateNewInstance()
    {
        return new Worker();
    }
}

Given the number of these classes, I'd like to take advantage of object expressions. Is there a way an object expression can refer to itself in this way?

Upvotes: 1

Views: 70

Answers (1)

Brian Berns
Brian Berns

Reputation: 17028

I'm not sure I would recommend this without knowing more about your use case, but something like this should work:

let rec makeWorker () =
    {
        new IWorker with
            member _.CreateNewInstance() = makeWorker ()
    }

let worker1 = makeWorker ()
let worker2 = worker1.CreateNewInstance()

Upvotes: 2

Related Questions