I have two classes, Foo and Bar, that have constructors like this:
class Foo { Foo() { // do some stuff } Foo(int arg) { // do some other stuff } } class Bar : Foo { Bar() : base() { // some third thing } }
Now I want to introduce a constructor for Bar that takes an int, but I want the stuff that happens in Bar() to run as well as the stuff from Foo(int). Something like this:
Bar(int arg) : Bar(), base(arg) { // some fourth thing }
Is there any way to do this in C#? The best I have so far is putting the work done by Bar() into a function, that also gets called by Bar(int), but this is pretty inelegant.
No, this isn’t possible. If you use Reflector to examine the IL that’s generated for each constructor, you’ll see why — you’d end up calling both of the constructors for the base class. In theory, the compiler could construct hidden methods to accomplish what you want, but there really isn’t any advantage over you doing the same thing explicitly.