Let's say we have these two structs...
public struct Example
{
public int Number { get; set; }
public Example(int Number)
{
Number = number;
}
}
and:
public struct Example
{
public int Number { get; set; }
public Example(int number) : this()
{
Number = number;
}
}
You can see that there's a struct with a constructor with **this()**
at the end and another without.
What is the difference between the two?
Calling this() initializes all fields with zeroes. C# compiler requires all struct fields to be initialized in constructor. So if you want to specify not all fields you should call this().
Will not compile:
struct A
{
public int field1;
public string field2;
public A(string str)
{
field2 = str;
}
}
Gives:
Error CS0171 Field 'A.field1' must be fully assigned before control is returned to the caller ...
Is OK:
struct A
{
public int field1;
public string field2;
public A(string str) : this()
{
field2 = str;
}
}
Weird, but still OK:
struct A
{
public int field1;
public string field2;
public A(string str)
{
this = new A(); // in structs 'this' is assignable
field2 = str;
}
}
or
struct A
{
public int field1;
public string field2;
public A(string str)
{
this = default(A); // in structs 'this' is assignable
field2 = str;
}
}
UPDATED
For a class:
The difference is that the constructor that calls this()
will also call the class's constructor that takes no arguments. So, for example, if this were your class:
public class Example
{
public int Number { get; set; }
public Example(int number) : this()
{
Number = number;
}
public Example()
{
Console.WriteLine("Hello");
}
}
Then including this()
would also print "Hello". This is a way you can chain constructors together, for code reuse.
For a struct:
You cannot add an empty constructor in a struct, so adding this()
does not provide any benefit. Thanks to vendettamit for waking up my tired brain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With