2

The following code is from the AvalonEdit project:

// Creates a new TextEditor instance.

public TextEditor() : this(new TextArea())
{
}

I have no idea what the : this(new ... part does. Could you please help explain the C# syntax?

Sabuncu
  • 5,095
  • 5
  • 55
  • 89
  • 1
    @AlexeiLevenkov - the dupe question wasn't a dupe and the answer only usable with the instructions from your comment here. – H H Jul 04 '14 at 20:31
  • 1
    Considering that the marked duplicate question doesn't actually list constructor chaining as an option, I would have to say that it isn't a duplicate. – Lasse V. Karlsen Jul 04 '14 at 20:33
  • @LasseV.Karlsen I thought "To pass parameters between constructors" link in http://stackoverflow.com/questions/23250/when-do-you-use-the-this-keyword is reasonable explanation... – Alexei Levenkov Jul 04 '14 at 20:35
  • 1
    OK, doh, read the list 3 times, still didn't spot that entry. Perhaps too late on a friday evening for me. I agree, the duplicate lists it. (and no, I did not vote to reopen). In my defense, "pass parameters between constructors" is not a very good description of the operation being performed. But oh well. Too late on a friday :) – Lasse V. Karlsen Jul 04 '14 at 20:36
  • So, it's equivalent to the following (albeit illegal) syntax: `public TextEditor() : TextEditor(new TextArea())` - now I understand it. – Sabuncu Jul 04 '14 at 20:38
  • 1
    @Sabuncu please edit your question so it looks reasonable "please explain code" is awful title. Maybe something along line "what 'this` after constructor means"... – Alexei Levenkov Jul 04 '14 at 20:39
  • @AlexeiLevenkov what would you suggest? Is "What is the following use of the "this" keyword?" acceptable? – Sabuncu Jul 04 '14 at 20:40
  • 1
    @Sabuncu - definitely better than current. Maybe mention constructor too. – Alexei Levenkov Jul 04 '14 at 20:41
  • Thank you everyone for your contributions - 20 mins ago, I was completely lost. Now it's all clear, thanks to SO. – Sabuncu Jul 04 '14 at 20:44

1 Answers1

9

It means that this constructor calls another constructor which accepts argument of type TextArea. It is called constructor chaining.

See the link provided by @Lasse: http://msdn.microsoft.com/en-us/library/aa645603(v=vs.71).aspx

AlexD
  • 32,156
  • 3
  • 71
  • 65