public <return_type> getclass(string company)
{
switch (company)
{
case "cmp1": Classcmp1 temp = new Classcmp1(); return temp ;
case "cmp2": Classcmp2 temp = new Classcmp2(); return temp ;
case "cmp3": Classcmp3 temp = new Classcmp3(); return temp ;
}
}
What should be the return type of this function if classcmp1 ,classcmp2 , classcmp3 are three public classes? How to determine this dynamically?
You can always return an object, because all classes inherits from object:
public object getclass(string Company)
{
switch (Company)
{
case "cmp1": classcmp1 temp = new classcmp1(); return temp ;
case "cmp2": classcmp2 temp = new classcmp2(); return temp ;
case "cmp3": classcmp3 temp = new classcmp3(); return temp ;
}
}
Else you can build a class from which your three classes will inherit :
public class classcmp { }
public class classcmp1 : classcmp {}
public class classcmp2 : classcmp {}
public class classcmp3 : classcmp {}
public classcmp getclass(string Company)
{
switch (Company)
{
case "cmp1": classcmp1 temp = new classcmp1(); return temp ;
case "cmp2": classcmp2 temp = new classcmp2(); return temp ;
case "cmp3": classcmp3 temp = new classcmp3(); return temp ;
}
}
Else, you can build an interface:
public interface Iclasscmp { }
public class classcmp1 : Iclasscmp {}
public class classcmp2 : Iclasscmp {}
public class classcmp3 : Iclasscmp {}
public Iclasscmp getclass(string Company)
{
switch (Company)
{
case "cmp1": classcmp1 temp = new classcmp1(); return temp ;
case "cmp2": classcmp2 temp = new classcmp2(); return temp ;
case "cmp3": classcmp3 temp = new classcmp3(); return temp ;
}
}
The choice that you will make will influence the architecture of your program. With no more information on the use of the class you will need, it is hard to help you more than that.
Do all the classcmpX classes share a common class/interface?
object, the class that all types in c# extend (*).(*) well, except for pointer types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With