MatthewJohnHeath
MatthewJohnHeath

Reputation: 493

Static constraint on Item

I'm trying to write a option-valued version of "TryGetValue" that will work on any object that implements either IDictionary or IReadOnlyDictionary. I have this :

let inline contains   (key:^key) (dictionary:^dic )=
    (^dic: (member ContainsKey: ^key -> bool) (dictionary, key) ) 

let inline tryGetValue (dictionary:^dic )  (key:^key)=
    if contains key dictionary then  
        let value = ( ^dic : (member  get_Item: ^key -> ^value )  (dictionary, key) )   (dictionary) ) key
        value |> Some
    else None  

The definition of "value" produces a warning that member constraints with name get_Item have special status which may cause runtime errors. What should I be doing here?

Upvotes: 0

Views: 84

Answers (1)

Tarmil
Tarmil

Reputation: 11372

How about using TryGetValue instead of ContainsKey and Item?

let inline tryGetValue dic key =
    let mutable value = Unchecked.defaultof< ^value>
    let contains = (^dic : (member TryGetValue : ^key * byref< ^value> -> bool) (dic, key, &value))
    if contains then Some value else None

Upvotes: 3

Related Questions