How to create an F# list from an interface to be consumed by C#/WPF

Viewed 102

I am a newbie. Given that each of these represents different classes in C#:

  1. ContactDetails
  2. Internet
  3. PhoneNumbers
  4. Addresses

How is a "list" created in F# to hold the different concrete types?

All the above types will have a common field of:

  1. Name -- string

Outside of the name, all the concrete types will have different fields and contents.

This "list" type is to be consumed by WFP/XAML.

(I'm thinking an interface for the F# list needs to be used, but I do not know how this is implemented--F# is really really new to me. :)

TIA

2 Answers

Consider using Seq instead of List to aid C# clients:

I would recommend using a sequence (i.e. seq) instead of list for C# consumption. Hence a sequence in F# equates to IEnumerable in C#. Thus, you will be able to use these items from your Windows app.

Here's how I would implement the requirement:

type ContactDetail = { Name : string; Other:string }
type Internet      = { Name : string; Other:string }
type PhoneNumber   = { Name : string; Other:string }
type Address       = { Name : string; Other:string }

type MyType =
    | ContactDetails of ContactDetail seq
    | Internet       of Internet      seq
    | PhoneNumbers   of PhoneNumber   seq
    | Addresses      of Address       seq

let contactDetail  : ContactDetail = { Name="some name"; Other="???" }
let contactDetails = ContactDetails [contactDetail]

let internet       : Internet = { Name="some name"; Other="???" }
let internets      = Internet [internet]

let phoneNumber    : PhoneNumber = { Name="some name"; Other="???" }
let PhoneNumbers   = PhoneNumbers [phoneNumber]

let myTypes : MyType seq = seq [ contactDetails
                                 internets
                                 PhoneNumbers
                               ]

Excuse me, is this what you want?

F#

module FSharpTest.ListTest
open System


type YourType = Object

type ContactDetails = YourType
type Internet = YourType
type PhoneNumbers = YourType
type Addresses = YourType


type WrapperOfCSharpClass =
| CD of ContactDetails
| I of Internet
| PN of PhoneNumbers
| A of Addresses

let list = [
    Unchecked.defaultof<WrapperOfCSharpClass>
    CD (new ContactDetails())
    I (new Internet())
]

C#

using System;
using FSharpTest;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var fsharplist_item = ListTest.list[0];
            if (fsharplist_item.IsPN)
            {
                Console.WriteLine("I am a phone number");
            } else if (fsharplist_item.IsA)
            {
                Console.WriteLine("I am an address");
            }
        }
    }
}
Related