How to use constructor with parameters from one without parameters

I have a controller which takes a DbContext and one who does not. I.e.,:

public CalendarController()
{
    var db = new DbContext(); 
    CalendarController(db); // <= Not allowed
}

public CalendarController(IDbContext db)
{
    _calendarManager = new CalendarManager(db);
    _userManager = new UserManager(db);
    _farmingActionManager = new FarmingActionManager(db);
    _cropManager = new CropManager(db);
}

Unfortunately the above gives an error on the CalendarController(db) line:

Expression denotes a 'type', where a 'variable', 'value' or 'method group` was expected

Is it possible to call one constructor from another? I don't want to duplicate all the code.

Jon Skeet
people
quotationmark

You have to chain to the constructor like this:

public CalendarController() : this(new DbContext())
{
}

That's the syntax for chaining to any constructor in the same class - it doesn't have to be from a parameterless one to a parameterized one, although it does have to be to a different one :)

Note that this comes before the body of the constructor, so you can't do anything else first, although you can call static methods to compute arguments to the other constructor. You can't use instance methods or properties though. So this is okay:

public Foo() : this(GetDefaultBar())
{
}

public Foo(int bar) { ... }

private static int GetDefaultBar() { ... }

But this isn't:

public Foo() : this(GetDefaultBar())
{
}

public Foo(int bar) { ... }

private int GetDefaultBar() { ... }

The syntax to chain to a constructor in the base class is similar:

public Foo() : base(...)

If you don't specify either : base(...) or : this(...) the compiler implicitly adds a : base() for you. (That doesn't necessarily chain to a parameterless constructor; it could have optional parameters.)

people

See more on this question at Stackoverflow