Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factory based on Typeof or is a

Tags:

c#

factory

What's a more elegant way of having the code below where i want to return a derived class based on the type of another class.

            if (option_ is Rectangle)
            {
                modelInputs = new Foo();
            }
            else if (option_ is Circle)
            {
                modelInputs = new Bar();
            }
            else if (option_ is Triangle)
            {
                modelInputs = new Bar2();
            }
like image 811
leora Avatar asked Dec 18 '22 10:12

leora


1 Answers

Have Rectangle, Circle and Triangle implement IHasModelInput:

interface IHasModelInput
{
    IModelInput GetModelInput();
}

then you can do

IModelInput modelInputs = option_.GetModelInput();
like image 126
mmiika Avatar answered Dec 24 '22 01:12

mmiika