c# - Returning an unknown object -


as example, have base class called baseabstractclass , couple of derived classes:

public class derived : baseabstractclass {     public derived()     {     }     // abstract methods go here } public class derivedex : baseabstractclass {    // code goes here } 

and have class:

public class someclass {      public someclass()      {      }      object returnmeanobject(int whichobject)      {           object toreturn = null;            if (whichobject == 0)           {               toreturn = new derived();           }           else           if (whichobject == 1)           {                toreturn = new derivedex();           }           return toreturn;      }  } 

in main function:

public class start {      static void main()      {           someclass someclass = new someclass()           derived derived = (derived)someclass.returnmeanobject(0);      } } 

the object i'm returning unknown until runtime, in reality don't know type of object going returned - derived, or derivedex. there simplier way having cast return value shown in main function can result in large switch statement or, large set of if... else conditions.

i have tried determine if design correct constructing class diagram, can't seem fit code.

any appreciated.

your problem can solved using generics. have limit generic parameter t , ensure class used has default constructor.

public t returnmeanobject<t>() t : baseabstractclass, new() {     return new t(); } 

then can use in code follows:

someclass someclass = new someclass() derived derived = someclass.returnmeanobject<derived>(); derivedex derivedex = someclass.returnmeanobject<derivedex>(); 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -