Alan Wayne
Alan Wayne

Reputation: 5384

Make an F# class or module for a C# interface?

I am totally lost on F# interfaces. I am trying to replace my C# classes with F# types that satisfy the C# interfaces.

I have the following C# interface:

public interface IPatientName
    {
        string lastName { get; }
        string firstName { get; }
        string mi { get; }
        DateTime? birthDate { get; }       
    }

In my C# code, I have multiple Dependency Injections and other such, e.g., "List<"IPatientName>".

Assuming I have a typical C# class that implements IPatientName, e.g.,

public class PatientName : IPatientName
{
     …………….
}

How would a F# module or class be made to satisfy the C# compiler and replace the C# class PatientName with an F# class or module?

Thank you for any help on this.

Upvotes: 0

Views: 232

Answers (1)

akara
akara

Reputation: 406

Implementing an interface is pretty straightforward. Given your example above the code below should suffice. Note: In an F# context Nullable isn't really recommended, but for C# interop it is OK to use. For F# asgnostic code its better to use the Option type which deals with the null problem better. Ionide (VS Code) extensions at time of writing can implement/generate the methods for you after you type the "interface IPatientName" part of the code in a class below.

open System

// F# version of the interface you described.
type IPatientName = 
    abstract member LastName: string with get
    abstract member FirstName: string with get
    abstract member Mi: string with get
    abstract member BirthDate: Nullable<DateTime> with get

// Class implementing interface above.
type PatientName = 
    interface IPatientName with
        member this.BirthDate = Nullable(DateTime(2020, 1, 1))
        member this.FirstName = "FirstName"
        member this.LastName = "LastName"
        member this.Mi = "Mi"

Upvotes: 2

Related Questions