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){
.........
}
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With