Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Mastering F#

You're reading from   Mastering F# A comprehensive and in-depth guide to writing functional programs using F#

Arrow left icon
Product type Paperback
Published in Nov 2016
Publisher
ISBN-13 9781784393434
Length 264 pages
Edition 1st Edition
Languages
Arrow right icon
Authors (2):
Arrow left icon
 García-Caro Núñez García-Caro Núñez
Author Profile Icon García-Caro Núñez
García-Caro Núñez
 Fahad Fahad
Author Profile Icon Fahad
Fahad
Arrow right icon
View More author details
Toc

Interop with C#


Some F# features require a bit of interop code to make it easily consumable in C#.

Optional parameters

We can define a C# function by writing the following piece of code:

    public class CSharpExample { 
        public static int Add(int x, int y = 1) { 
            return x + y; 
        } 
    } 

We can call the function in C# by writing the following piece of code:

    var a = CSharpExample.Add(10) 
    var b = CSharpExample.Add(10, 20); 

If we try the same with F#, it will work as well:

    let a = CSharpExample.Add(10) 
    let b = CSharpExample.Add(10, 20) 

Now, the other way around; a method defined in F# using the F# flavor of optional parameters is as follows:

    type FSharp =  
        static member Add(x, ?y) =  
            let y = defaultArg y 1  
            x + y  

We can happily use it like this in F#:

    let a = FSharp.Add(10)
    let b = FSharp.Add(10, 20)

If we try to use this in C#, then we will see that it's not exposed as an optional parameter, so we will...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime
Visually different images