Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this() and base() constructors in C#

There seems to be no language syntax for specifying both a this() and a base() constructor. Given the following code:

public class Bar : Foo
{
    public Bar()
      :base(1)
      //:this(0)
    { }
    public Bar(int schmalue)
      :Foo(1)
    {
       //Gobs of initialization code
       ...
       Schmalue = schmalue;
    }

    public int Schmalue { get; private set; }
}

public class Foo
{
    public Foo()
    {
        Value = 0;
    }

    public class Foo(int value)
    {
        Value = value;
    }

    public int Value { get; private set; }
}

The compiler gives me an error stating that '{' was expected when uncommenting the :this(0) call. This is bothersome because it causes me to factor out my code into a private method, when this functionality was clearly provided to prevent such a thing.

Am I simply doing this wrong? I've attempted no separator, semi-colon, comma... It seems this was just an oversight from the dev team. I'm interested in why this was omitted, if I'm going about this the wrong way or if anybody has good suggestions for alternatives.

like image 826
Sprague Avatar asked Jan 31 '11 19:01

Sprague


1 Answers

You can accomplish this by invoking the base constructor at the end of your chain:

public Bar(): this(0) {}
public Bar(int schmalue): base(1) {
    // ... initialize
}
like image 148
Jeff Sternal Avatar answered Nov 10 '22 00:11

Jeff Sternal