4

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){
    .........
}
Raphael
  • 171
  • 1
  • 3
  • 12
  • Exact duplicate http://stackoverflow.com/questions/4734280/how-to-pass-dictionarystring-string-object-in-some-method – emd May 03 '12 at 15:20
  • It depends on the context. Can you make your method generic? Can you put your method in an interface? You may have different solutions. The example you provided is exactly what you need? – Adriano Repetti May 03 '12 at 15:26

2 Answers2

8

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

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
}
ie.
  • 5,982
  • 1
  • 29
  • 44