c# - How can I share constructor code with readonly class members? -


i have class, foobarset single "core" chunk of initialization logic.

a foobar made of foo , bar. class foobarset initialized list of foobar. foobarset can also initialized separate parallel foo , bar lists.

ideally, run this:

public class foobarset {     private readonly list<foobar> _list;      // primary constructor.     public foobarset(list<foobar> foobarlist)     {         // contracts , initialization...         _list = foobarlist;     }      // secondary constructor.     public foobarset(list<foo> foolist, list<bar> barlist)      {         // zip new list of new foobars         var zipped = foolist.zip(barlist,                                  (foo, bar) => new foobar(foo, bar));          // call primary constructor zipped list.         this(zipped);     } } 

this c#, not java, this(zipped) illegal. common solution, as in answer, pull core initialization common private method:

public class foobarset {     private readonly list<foobar> _list;      // common "constructor" called actual constructors.     private init(list<foobar> foobarlist)     {         // contracts , initialization...         _list = foobarlist;     }      public foobarset(list<foobar> foobarlist)     {         init(foobarlist);     }      public foobarset(list<foo> foolist, list<bar> barlist)      {         var zipped = foolist.zip(barlist,                                  (foo, bar) => new foobar(foo, bar));          init(zipped);     }  } 

however, doesn't work either, because of readonly _list field.

assuming _list must readonly, how can these constructors share initialization code?

the simple answer init method return value set in constructor:

public class foobarset {     private readonly list<foobar> _list;      // common "constructor" called actual constructors.     private list<foobar> init(list<foobar> foobarlist)     {         // contracts , initialization...         return whateverlist;     }      public foobarset(list<foobar> foobarlist)     {         _list = init(foobarlist);     }      public foobarset(list<foo> foolist, list<bar> barlist)      {         var zipped = foolist.zip(barlist,                                  (foo, bar) => new foobar(foo, bar));          _list = init(zipped);     }  } 

Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -