anon
anon

Reputation:

How to add a value to a dictionary using reflection in c#?

I have the following Dictionary:

private Dictionary<string, double> averages = new Dictionary<string, double>();

Now I want to use reflection to add two additional values. I can retrieve the field info, but what else do I have to do?

FieldInfo field = ProjectInformation.SourceManager.GetType().GetField("averages");
if (field != null)
{
    //what should be here?
}

Upvotes: 3

Views: 1843

Answers (3)

rene
rene

Reputation: 42444

MethodInfo mi = field.FieldType.GetMethodInfo("set_Item");
Object dict = field.GetValue(ProjectInformation.SourceManager);
mi.Invoke(dict, new object[] {"key", 0.0} );

Upvotes: 5

Ian Dallas
Ian Dallas

Reputation: 12741

If you need to get the field and values just for Unit Testing consider using Microsoft's PrivateObject

Its there so you can check the internal state of data members during unit testing if you need to, which appears to be what you are trying to do.

In your unit tests you can do the following:

MyObject obj = new MyObject();
PrivateObject privateAccessor = new PrivateObject(obj);
Dictionary<string, double> dict = privateAccessor.GetFieldOrProperty("averages") as Dictionary<string, double>;

Then you are free to get and set any values you need to from the Dictionary.

Upvotes: 4

Bivoauc
Bivoauc

Reputation: 853

if(field != null)
{
   field.GetValue(instance);
}

Upvotes: 0

Related Questions