Reputation: 171
How can i pass a Dictionary to a method that receives a Dictionary?
Dictionary<string,string> dic = new Dictionary<string,string>();
//Call
MyMethod(dic);
public void MyMethod(Dictionary<object, object> dObject){
.........
}
Upvotes: 4
Views: 5317
Reputation: 6101
If you want to pass dictionary for read-only purposes, then you could use Linq:
MyMethod(dic.ToDictionary(x => (object)x.Key, x => (object)x.Value));
Your current aproach does not work due to type-safe restrictions:
public void MyMethod(Dictionary<object, object> dObject){
dObject[1] = 2; // the problem is here, as the strings in your sample are expected
}
Upvotes: 1
Reputation: 726849
You cannot pass it as is, but you can pass a copy:
var copy = dict.ToDictionary(p => (object)p.Key, p => (object)p.Value);
It is often a good idea to make your API program take an interface rather than a class, like this:
public void MyMethod(IDictionary<object, object> dObject) // <== Notice the "I"
This little change lets you pass dictionaries of other kinds, such as SortedList<K,T>
to your API.
Upvotes: 8