this.shawn
this.shawn

Reputation: 19

Parent method that chooses child class (C#)

I'm trying to avoid duplicate blocks of code--each dealing with different children of a parent. Here is an example of what I would like to avoid:

if (FormNumber == 0)
    {  
    Child1 obj = new Child1()  
    statements;
    }
else
    {  
    Child2 obj = new Child2()  
    statements;
    }

I would like to pass FormNumber to the parent class and use a parent function to determine which child class is used. I'm imagining a parent function like:

public Parent GetChild(int F)  
    {  
        if (FormNumber == 0)
            return new Child1();
        else
            return new Child2();
    } 

and then in the main function

Parent obj = new Parent();  
Child? newobj = obj.GetChild(FormNumber);  
statements;

The problem is I need to figure out how to fill in the ? with the right Child class.

Upvotes: 1

Views: 929

Answers (2)

Aliostad
Aliostad

Reputation: 81660

You are looking for factory/strategy pattern. Get them implement a similar interface and have it:

IChild newobj = obj.GetChild(FormNumber);  

Upvotes: 3

jjnguy
jjnguy

Reputation: 138884

You need to set up an inheratance hierarchy for Child. If you set up a common interface for Child1 and Child2 then you can do the following:

Parent obj = new Parent();  
IChild newobj = obj.GetChild(FormNumber); 
// newobj may be a Child1 or Vhild2 object.

The hiearrchy may look like:

public interface IChild {
    public methods();
}

public class Child1 : IChild {}

public class Child2 : IChild {}

Your method could then look like:

public IChild GetChild(int F)  
{  
    if (FormNumber == 0)
        return new Child1();
    else
        return new Child2();
} 

Upvotes: 1

Related Questions