Moamen Naanou
Moamen Naanou

Reputation: 1713

Access Class Methods by string class name

Background:

I have a string variable called "object_model" which could have one of this two values ("UserImage", "CarImage") and using it in my code like this:

switch (object_model)
            {
                case "UserImage":
                    { UserImage.Add(img); break; }
                case "CarImage":
                    { CarImage.Add(img); break; }
            }

Question:

I need to avoid using switch statement and simply do it like this:

object_model.add(img)

Note: I've achieved the same in Ruby on Rails by using constantize (i.e model_object.constantize.add(img))

Upvotes: 0

Views: 740

Answers (2)

Maksim Simkin
Maksim Simkin

Reputation: 9679

Seems that your object_model is a string, in that case you could just write an extension method:

public static class Extensions
{
    public static void Add(this string object_model, Img img)
    {
        switch (object_model)
        {
            case "UserImage":
                { UserImage.Add(img); break; }
            case "CarImage":
                { CarImage.Add(img); break; }
        }
    }
}

You could use it just as "blabla".Add(img)
Danger is that you actually permit such calls for any string, so it's your own responsibility to decide if you should add this model or not.

Since your variable could have only two values it's better to define it as Enum and than extension method could be called on Enum not on string.

Upvotes: 2

Paviel Kraskoŭski
Paviel Kraskoŭski

Reputation: 1419

Type t = Type.GetType(object_model);
MethodInfo method = t.GetMethod("Add", BindingFlags.Static | BindingFlags.Public);
method.Invoke(null, new object[] { img });

Upvotes: 8

Related Questions