lukaszb
lukaszb

Reputation: 169

Cast error (Type constraint missmatch)

I have problem with casting

    type IConfig = interface end

    type test(num: string) = 
        interface IConfig
        member this.num = num


    type init(context:string) = 
        interface IConfig
        member this.context = context


let dict:Dictionary<string, IConfig> = new Dictionary<string, IConfig>()
dict.Add("x1", new test() { num = "1" });
dict.Add("x2", new init() { context = "1" });

for item in dict do
    if(item.Key = "x1") then
        let x = (item.Value :> init).context 
//Here I have an error: Type constraint missmach. The type IConfig is not compatibile with type InitConfig 

I've done the same with C#, and it works. Please, help.

Upvotes: 1

Views: 69

Answers (1)

Aaron M. Eshbach
Aaron M. Eshbach

Reputation: 6510

I had to make some changes to your code to get it working, but I think you're looking for the :?> operator instead of the :> operator. The :> only does upcasting (i.e. init -> IConfig), whereas :?> does downcasting (i.e. IConfig -> init), which is what you're trying to do here.

Here's the code I used to get it working:

open System.Collections.Generic

type IConfig = interface end

type test(num: string) = 
    interface IConfig
    member this.num = num


type init(context:string) = 
    interface IConfig
    member this.context = context


let dict:Dictionary<string, IConfig> = new Dictionary<string, IConfig>()
dict.Add("x1", new test(num = "1"))
dict.Add("x2", new init(context = "1"))

for item in dict do
    if(item.Key = "x2") then
        let x = (item.Value :?> init).context 
        printfn "%A" x

Upvotes: 2

Related Questions