We can do this in vb.net:
Dim d= new Dictionary(of string, string) from {{"a","valA"},{"b","valB"}}
Please how can we make the following possible for convenience:
public sub Setup(args)
Dim d= new Dictionary(of string, string) from args
end sub
Thanks.
No, you can't initialize a dictionary with collection initializer syntax from a variable or parameter. It's just syntactic sugar that the compiler eats if you assign it in the way you've shown in the first snippet.
However, you can pass an IDictionary(Of String, String)
and use that for the constructor of the dictionary:
Public sub Setup(dict As IDictionary(Of String, String))
Dim d = new Dictionary(Of String, String)( dict )
End Sub
Or you can pass an IEnumerable(Of KeyValuePair(Of String, String))
and use that for args.ToDictionary(Function(kv) kv)
:
Public sub Setup(keyVals As IEnumerable(Of KeyValuePair(Of String, String)))
Dim d = args.ToDictionary(Function(kv) kv)
End Sub
The former approach is more efficient, the latter is more general. Allowing IDictionary(Of TKey, TValue)
has the advantage that you can pass more types since there are many classes that implement that interface.