Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose which class to instantiate c#

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.

like image 288
user26098 Avatar asked Nov 28 '22 19:11

user26098


1 Answers

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.

like image 58
Tamas Czinege Avatar answered Dec 20 '22 14:12

Tamas Czinege