Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate classes and their properties in F#

Tags:

c#

f#

c#-to-f#

Follow Code C#:

var body = new CustomerRequest
{
    Method = "CREDIT_CARD",
    CreditCard = new Creditcard
    {
        ExpirationMonth = "06",
        ExpirationYear = "2022",
        Number = "4012001037141112",
        Cvc = "123"
    }
};

I'm new to F#, I can not instantiate classes like C#, See the code below in F#:

let body = CustomerRequest
(
    Method = "CREDIT_CARD"     // Help here
)

I can not convert C # to F #

like image 953
Matheus Miranda Avatar asked Mar 05 '23 16:03

Matheus Miranda


1 Answers

If you are doing idiomatic F# you would model this with Records instead of classes.

You could do it like this:

type CreditCard = {
    ExpirationMonth: int;
    //More
}

type CustomerRequest = {
    Method: string;
    CreditCard: CreditCard;
}

let req = {
    Method = "Credit"
    CreditCard = {
        ExpirationMonth = 6
        //More
    }
}

The compiler has type-inference that means it can guess that req is a CustomerRequest by the fields you have in it, and the same for the CreditCard - you can hint the type if you really need to.

If you really are after classes - perhaps you have to interop with C# code, then you would do it like this:

type CreditCard2(expirationMonth:int) = 
    member this.ExpirationMonth = expirationMonth

type CustomerRequest2(method: string, creditCard: CreditCard2) = 
    member this.Method = method
    member this.CreditCard = creditCard

let req2 = CustomerRequest2 ("Credit", CreditCard2 (5))
like image 98
DaveShaw Avatar answered Mar 12 '23 21:03

DaveShaw