John Tan
John Tan

Reputation: 1385

Refer to objects dynamically

Say I have 2 objects ObjA and ObjB. Assuming that they are from the same class with a method called CommonMethod(), I am looking for a method to do something like this:

void CallObjectMethod(string name)
{
    // where name could be 'A' or 'B'
    (Obj + name).CommonMethod();
}

instead of doing the long way:

void CallObjectMethod(string name)
{
    if(name == 'A')
        objA.CommonMethod();
    else if(name == 'B')
        objB.CommonMethod();
}

I understand this probably can be done through reflection, but not quite sure how to achieve this.

Upvotes: 4

Views: 71

Answers (2)

John Wu
John Wu

Reputation: 52290

Assuming both ObjA and ObjB are of class SomeClass and are fields (member variables) of this, you can use the following. If the caller supplies the wrong suffix (e.g. not "A" and not "B") the method will throw an exception, of course.

class Example
{
    private SomeClass ObjA;
    private SomeClass ObjB;

    void CallObjectMethod(string suffix)
    {
        string name = "Obj" + suffix;
        var fieldInfo = this.GetType().GetField(name, BindingFlags.Instance | BindingFlags.NonPublic);
        if (fieldInfo == null || (fieldInfo.FieldType != typeof(SomeClass)) throw ArgumentException(nameof(suffix));
        SomeClass obj = fieldInfo.GetValue(this) as SomeClass;
        obj.CommonMethod();
    }
}

Note: While this solution does exactly what you ask, I don't recommend it. You would normally not want your implementation to depend on private field names being passed in a string. You are probably better off using a dictionary, maybe like this:

class Example
{
    Dictionary<string, SomeClass> _objects = new Dictionary<string, SomeClass>();

    public SomeClass()
    {
        _objects["A"] = new SomeClass();
        _objects["B"] = new SomeClass();
    }

    void CallObjectMethod(string key)
    {
        _objects[key].CommonMethod();
    }
}

Upvotes: 2

You should use a dictionary of the Types <string, Obj> and then in the method do:

void CallObjectMethod(string name)
{
   Obj ObjFromDictionary = MyDictionary[name];
   ObjFromDictionary.CommonMethod();
}

you can of course call that directly without creating a temporary Obj ObjFromDictionary...

and you should validate that string parameter first...

Upvotes: 6

Related Questions