Choose which class to instantiate c#


Question

what i want to do is select the appropriate class to instantiate based on parenthesis passed in. Currently what i have are two classes (ClassA and ClassB) and to call these im using 2 methods depending on the parenthesis. What i would like to achieve is to use just one method to instantiate either ClassA or ClassB based on the string parenthesis passed.

I dont really know how i can pass back the class object to use..

My old way was in Method A to call the class to instantiate then i could use it. ClassA myclass = new ClassA();

I did think about using the following but i do not (if im honest) know how i instantiate the object o or use it when it is passed back by MyMethod. object o doesnt appear to give me access to the public string methods in Class A or Class B.

public class ClassA
{
    public ClassA()
    {
        //Do something for Class A
    }
    public string msgA()
    {
        return "Here is msg A";
    }
}

public class ClassB
{
    public ClassB()
    {
        //Do something for Class B
    }
    public string msgB()
    {
        return "Here is msg B";
    }
}

private string MyMethod()
{
    object o = GetClassToInstantiate("ClassA");
    //Use object o 
}

private object GetClassToInstantiate(string parameter)
{
    object temp = null;
    switch (parameter)
    {
        case "ClassA":
            temp = new ClassA();
            break;
    }

    return temp;
}

Any suggestions how i can solve this probably very easy situation.

1
4
1/20/2009 4:14:59 PM

What you need is a factory method in a base class:

enum ClassType { ClassA, ClassB }

class ClassBase
{
   public static ClassBase Create(ClassType  classType)
   {
       switch (classType)
       {
           case ClassType.ClassA: return new ClassA();
           case ClassType.ClassB: return new ClassB();
           default: throw new ArgumentOutOfRangeException();
       }
   }
}

class ClassA : ClassBase
{
}

class ClassB : ClassBase
{
}

Check the Wikipedia article on the Factory method pattern for more info.

14
1/20/2009 4:10:49 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon