0

I was looking in the tree structure and I found a constructor (in the Tree class) that looked like this:

public Tree(T value, params Tree<T>[] children)
: this(value)
{
   foreach (Tree<T> child in children)
   {
     this.root.AddChild(child.root);
   }
}

can someone explain to me what does ": this(value)" mean?

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • It's the call to the **constructor overload** of `Tree` that takes only `value` as argument. – René Vogt Aug 17 '17 at 12:10
  • See: https://stackoverflow.com/questions/6270774/what-is-the-meaning-of-this-in-c-sharp – EJoshuaS - Stand with Ukraine Aug 17 '17 at 12:13
  • Thank you sir . Now i remember that i have seen this and i'm going to read through it again .Im sorry for losing your time. – Nikolai Kolev Aug 17 '17 at 12:14
  • In general, `this` refers to the same class you're currently in. You don't see it a lot because it's implied.. e.g. you don't see a method in the person class say `this.Name = "Nikolai"` because `Name = "Nikolai"` will do just fine. Same for methods: when one method in your class wants to call another in the same class it could say `this.DoSomething()` but you're more likely to write simply `DoSomething()`.. So why use it with constructors? Well.. there isn't any way to refer to a constructor by name because they don't have one in the same way that a method or property has a name so the.. – Caius Jard Aug 17 '17 at 12:20
  • ..convention is to use `this(arguments to constructor here)` – Caius Jard Aug 17 '17 at 12:21

2 Answers2

2

It's called constructor chaining. Another constructor of the class is called before that constructor. Basically it's base but with a constructor of the current class instead of the base class.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
0

The usage of this here is calling another constructor overload on the class and passing value as an argument.

Owen Pauling
  • 11,349
  • 20
  • 53
  • 64