4

How can I get an instance of a static class with a string?

Example:

class Apple : IFruit
{
    public static Apple GetInstance() { ... }
    private Apple() { }

    // other stuff
}

class Banana : IFruit
{
    public static Banana GetInstance() { ... }
    private Banana() { }

    // other stuff
}

// Elsewhere in the code...
string fruitIWant = "Apple";
IFruit myFruitInstance = [What goes here using "fruitIWant"?].GetInstance();
5
  • 1
    C#, presumably? If so, please tag your question as such... Commented Aug 25, 2011 at 19:47
  • It doesn't have to be C#, the example was just that - an example. The solution should work for both C# and VB.NET. Commented Aug 25, 2011 at 19:49
  • 2
    @SpikeX I don't see any static class in code provided. What you're asking for? Please correct question. Commented Aug 25, 2011 at 19:50
  • The class is not static but the method I want is. The question is worded as such because I don't want an answer that gives me an instance of the class, I want the class reference itself. Any time you have static members in a class, a static instance of that class is available for access. Commented Aug 25, 2011 at 19:52
  • Btw why don't you just invoke the constructor instead of using a static GetINstance methnod? Commented Aug 25, 2011 at 20:16

5 Answers 5

3
Type appleType = Type.GetType("Apple");
MethodInfo methodInfo = appleType.GetMethod(
                            "GetInstance",
                            BindingFlags.Public | BindingFlags.Static
                        );
object appleInstance = methodInfo.Invoke(null, null);

Note that in Type.GetType you need to use the assembly-qualified name.

Sign up to request clarification or add additional context in comments.

1 Comment

This worked best. It turns out that "GetInstance" was actually a property, not a method in my specific application, but the question and answer still match up and this was the solution that worked best for me, so you win. Thanks! :)
3

Here is a complete example. Just pass in the name of the type you want to load and the name of the method to invoke:

namespace Test
{

    class Program
    {
        const string format = @"hh\:mm\:ss\,fff";
        static void Main(string[] args)
        {
            Console.WriteLine(Invoke("Test.Apple", "GetInstance"));
            Console.WriteLine(Invoke("Test.Banana", "GetInstance"));
        }
        public static object Invoke(string type, string method)
        {
            Type t = Type.GetType(type);
            object o = t.InvokeMember(method, BindingFlags.InvokeMethod, null, t, new object[0]);
            return o;
        }

        }
        class Apple 
        {
            public static Apple GetInstance() { return new Apple(); }
            private Apple() { }

            // other stuff
        }

        class Banana
        {
            public static Banana GetInstance() { return new Banana(); }
            private Banana() { }

            // other stuff
        }

}

Comments

1

You do like this:

string fruitIWant = "ApplicationName.Apple";

IFruit a = Type.GetType(fruitIWant).GetMethod("GetInstance").Invoke(null, null) as IFruit;

For ApplicationName you substitute the namespace where the class is declared.

(Tested and working.)

Comments

-1

OK, may be I got your question. A pseudocode

EDIT

foreach (var type in System.Reflection.Assembly.GetExecutingAssembly().GetTypes())
{
      if (type.Name.Equals("MyClass"))
      {
          MethodInfo mi = type.GetMethod("GetInstance", BindingFlags.Static);
          object o = mi.Invoke(t, null);
          break;
      }
}

Should work..

4 Comments

You used typeof(Apple) but I need this to be figured out using a string. You can never type Apple by itself, you need to use the string variable. Additionally, this can be condensed into one line - no need to declare an additional MethodInfo that you'll never use.
What if it's not in the executing assembly? Why are you doing a linear search through the types? Your code for dynamically invoking a static method is not correct.
@Jason: it's reported like pseudocde, I didn't even compile just write inside the site editor. Just to give an idea. Is this is a problem?
The problem isn't that you wrote it directly in the site, it's that your methodology is wrong. Why execute a loop when there are other, more efficient functions that do exactly the same thing?
-1

While the others give you what you asked for, this is probably what you want:

IFriut GetFruit(string fruitName)
{
   switch(fruitName)
   {
       case "Apple":
          return Apple.GetInstance();
       case "Banana":
          return Banana.GetInstance();
       default:
          throw new ArgumentOutOfRangeException();
   }
}

1 Comment

This relies on the fact that I'd have to input entries manually each time I added a new class based on IFruit, which I don't want to do (and which defeats the purpose of having an interface in the first place), especially if I'm dynamically loading assemblies. This code's maintainability is very poor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.