c# - Assigning a Readonly Field via Virtual Member in Abstract Class's Constructor -


i know there similar questions asked here on so, question deals scenarios involving setting readonly field calling virtual member in abstract class's constructor.

consider following abstract class:

public abstract class foobase {     private readonly idictionary<string,object> _readonlycache;      protected abstract idictionary<string,object> setcache();      protected foobase()     {         _readonlycache = setcache();     } } 

questions:

1) flat-out bad design?

2) there better design?

i'm aware declare implementers of foobase sealed , insure correct implementation of setcache() called. don't there no way enforce implementers must marked sealed. suggestions welcome.

it's avoided if possible - calling virtual methods within constructor bit smelly, you'll executing code before subclass gets perform initialization - constructor body won't have executed. true regardless of whether subclass sealed or not; you're in fundamentally nasty situation.

you might want consider making subclass constructor pass cache constructor:

public abstract class foobase {     private readonly idictionary<string,object> _readonlycache;      protected foobase(idictionary<string,object> cache)     {         _readonlycache = cache;     } } 

that way direct subclass gets decide - might abstract , take cache further-derived class, example, or might construct own.


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -