Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding values to a Dictionary using reflection

Tags:

c#

reflection

I have a class

class a
{  
    private Dictionary <int , string> m_Dict = new Dictionary<int , string>();
}

from some other component/class need to add values to the m_Dict dictionary using reflection! How do i do it ? i searched and tried but was not successfull.

like image 502
siva Avatar asked Feb 06 '26 02:02

siva


1 Answers

Dictionary is a pain, since it doesn't implement IList (something I was moaning about just the other evening). It really comes down to what you have available. Resolving the Add method for int/string is easy enough, but if you are dealing with typical list reflection you'll need the Add method from ICollection<KeyValuePair<int,string>>.

For standard usage:

object data = new Dictionary<int, string>();
object key = 123;
object value = "abc";
var add = data.GetType().GetMethod("Add", new[] {
          key.GetType(), value.GetType() });
add.Invoke(data, new object[] { key, value });
like image 158
Marc Gravell Avatar answered Feb 08 '26 19:02

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!