As Mark points out, you can work with the Hashtable
type directly from F# (just like with any other .NET type). The syntax for accessing indexers in F# is slightly different though:
open System.Collections
// 'new' is optional, but I would use it here
let ht = new Hashtable()
// Adding element can be done using the C#-like syntax
ht.Add(1, "One")
// To call the indexer, you would use similar syntax as in C#
// with the exception that there needst to be a '.' (dot)
let sObj = ht.[1]
Since Hashtable is not generic, you would probably want to cast the object back to string. To do that, you can either use the :?>
downcast operator, or you can use the unbox
keyword and provide a type annotation to specify what type do you want to get as the result:
let s = (sObj :?> string)
let (s:string) = unbox sObj
If you have any control over what type is used, then I would recommend using Dictionary<int, string>
instead of Hashtable
. This is fully compatible with C# and you would avoid the need to do casting. If you're returning this as a result from F#, you could also use standard F# map
and just upcast it to IDictionary<_,_>
before passing it to C#:
let map = Map.empty |> Map.add 1 "one"
let res = map :> IDictionary<_, _>
This way, C# users will see a familiar type, but you can write the code in the usual functional style.