Arpit Gupta Arpit Gupta -4 years ago 138
C# Question

Access a dictionary from class dynamically without knowing its name

I have a class named

SomeClass
. I have few dictionaries in it.

public class SomeClass
{
public Dictionary<double, int[]> Dict1;
public Dictionary<double, int[]> Dict2;
public Dictionary<double, int[]> Dict3;
}


I get to know the dictionary name at runtime. Means In which dictionary I need to assign the data is only known at runtime.
I get the dictionary name in
string
dynamically. Something like -

String dictName = "Dict1"; //Achieved through some code mechanism in my project.

SomeClass DynValue = new SomeClass();
DynValue.[dictName/* Known at run time */].Add(3, new int[] { 5, 10 });

Answer Source

You should initialize dictionaries after object creation.

public class SomeClass
{
    public Dictionary<double, int[]> Dict1 = new Dictionary<double, int[]>();
    public Dictionary<double, int[]> Dict2 = new Dictionary<double, int[]>();
    public Dictionary<double, int[]> Dict3 = new Dictionary<double, int[]>();
}

For dynamically change the object field using name, you should use reflection:

    String dictName = "Dict1"; //Achieved through some code mechanism in my project.

    SomeClass obj = new SomeClass();

    // Get dictionary interface object of 'Dict1' field using reflection
    var targetDict = obj.GetType().GetField(dictName).GetValue(obj) as IDictionary;

    // Add key and value to dictionary
    targetDict.Add(3.5d, new int[] { 5, 10 });

If you needed to initialize dictionary using reflection, you should use this:

String dictName = "Dict1"; //Achieved through some code mechanism in my project.

SomeClass obj = new SomeClass();

// Get field info by name
var dictField = obj.GetType().GetField(dictName);

// Get dictionary interface object from field info using reflection
var targetDict = dictField.GetValue(obj) as IDictionary;
if (targetDict == null) // If field not initialized
{
    // Initialize field using default dictionary constructor
    targetDict = dictField.FieldType.GetConstructor(new Type[0]).Invoke(new object[0]) as IDictionary;

    // Set new dictionary instance to 'Dict1' field
    dictField.SetValue(obj, targetDict);
}

targetDict.Add(3.5d, new int[] { 5, 10 });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download