c# - Implement Derived Class as Base on Constructor Exception? -


i'm working code implement hardware test system, involves communication several benchtop instruments. when instantiate instance of 1 of these instruments, constructor attempts open communication session instrument. if fails, can throw kinds of errors, i'd have instrument object default virtual or simulation mode no actual communication done can still run code.

right have instruments of 1 type inheriting base class. i've added virtual methods base class perform these debugging functions, i'm stuck on clean way modify derived object @ creation time implement base classes methods when communication session fails.

the ideal solution have constructor (technically new keyword) return instance of base class instead of derived class, i've done fair amount of searching , doesn't appear possible.

i add property derived class use boolean flag every method in derived class tests against flag , invokes base class method if true, i'm hoping find more elegant solution doesn't require few hundred if statements , serious flogging of base.stuff() calls.

i have few dozen methods , handful of instruments inheriting in way solution doesn't require explicit change every 1 of overriding methods go long, long way.

public abstract class baseinstrument {     public string address;     protected messagebasedsession mbsession;      public virtual string identify()     {         return "debugging mode, fake identity";     } }   public class specificinstrument : baseinstrument {     public specificinstrument(string address)     {         address = address;         try         {             mbsession = (messagebasedsession)resourcemanager.getlocalmanager().open(address);         }         catch         {             // return object modified in such way invokes base class virtual methods             // instead of method overrides.             // constructor has no return value (that comes new keyword) can't             // return instance of base class...         }     }      public override string identify()     {         return actualinstrumentread();     }      // ... }  public class program {     public static void main()     {         specificinstrument instr = new specificinstrument(ipaddress);         console.writeline(instr.identify()); // print debug case if eg. lan down     } } 

i feel might missing obvious solution i've been scratching head hours.

you can't return baseinstrument specificinstrument constructor.

one alternative put logic create instrument:

baseinstrument instrument; try {     instrument = new specificinstrument(); } catch {     instrument = new baseinstrument(); } 

Popular posts from this blog