What does : this()
mean after a constructor of struct?
The this
keyword in C# refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method.
As it pertains to a struct
and the constructor of a struct
, it actually is meaningless and does nothing. In C# a struct
doesn't have a parameterless constructor. They are very similar to class
constructors but differ in the following ways:
- Structs cannot contain explicit parameterless constructors. Struct members are automatically initialized to their default values.
- A struct cannot have an initializer in the form: base (argument-list).
As such, the : this()
after the struct constructor does nothing and is redundant - it can be removed with no issues whatsoever. However, in the context of a struct
constructor, the this
keyword works as expected.
Classes
When used in after a constructor, it invokes another constructor in the same class first - in this specific situation the parameterless constructor. This can be used to initialize other various parts of an object instance as they are invoked first.
Constructors
Read "using constructors" on MSDN for more details.
Consider the following:
public class FooBar
{
public int Number { get; }
public string Name { get; }
public FooBar()
{
Number = 10;
Name = "Pickles";
}
public FooBar(int number) : this()
{
Number = number;
}
public FooBar(int number, string name) : this(number)
{
Name = name;
}
}
var fooBar1 = new FooBar();
var fooBar2 = new FooBar(20);
var fooBar3 = new FooBar(77, "Stackoverflow");
// The following would be true
// fooBar1.Number == 10 and fooBar1.Name == "Pickles"
// fooBar2.Number == 20 and fooBar2.Name == "Pickles"
// fooBar3.Number == 77 and fooBar2.Name == "Stackoverflow"
The
this
keyword in the context of a constructor can also be used (as shown above) to call into parameterized constructors as well. If you were to inherit then you could call into default or parameterized constructors of the base class using the
base
keyword.