Alex Rivera | Logout

: this(foo) syntax in C# constructors?

Asked 2008-12-03T19:16:02.963
17

Every now and then, I bump into syntax that I've seen before, but never used. This is one of those times.

Can someone explain the purpose of ":this" or ":base" following a C# constructor method?

For example:

public MyClass(SomeArg arg) : this(new SomethingElse(), arg)
{
}

My gut feeling is that it is used to map a default argument onto another constructor method.

Edit
Report

3 Answers

21

You're basically right. this() calls a constructor on the current instance, base() calls the supertype's constructor on current instance. They're generally used to handle constructor overloads so you can add additional options without breaking things out into a separate method.

answered 2008-12-03T19:19:33.083
2

Exactly. The call it Constructor Chaining and it's used to get around the fact that C# doesn't have the ability to do default arguments.

This is used a lot in IoC.

answered 2008-12-03T19:22:15.480
2

Yes you are right. This syntax is used to have your subclass constructors to explicitly call an appropriate custom base class constructor, rather than the default. The this keyword in your question is explained:

Another use of the this keyword is to force one constructor to call another in order to avoid redundant member initialization logic.

in Pro C# 2005 and the .NET 2.0 Platform, 3rd Edition by Andrew Troelsen

answered 2008-12-03T19:25:51.260

Your Answer