Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i pass Dictionary<string, string> to a dictionary<object,object> method?

Tags:

c#

.net

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){
    .........
}
like image 874
Raphael Avatar asked Jan 17 '23 19:01

Raphael


2 Answers

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.

like image 179
Sergey Kalinichenko Avatar answered Jan 31 '23 00:01

Sergey Kalinichenko


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
}
like image 38
ie. Avatar answered Jan 31 '23 00:01

ie.