Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a struct constructor with `this()` at the end and another without?

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?

like image 798
Abdelfattah Radwan Avatar asked Oct 16 '25 09:10

Abdelfattah Radwan


2 Answers

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;
    }
}
like image 68
Alex Avatar answered Oct 18 '25 22:10

Alex


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.

like image 39
BlueTriangles Avatar answered Oct 18 '25 23:10

BlueTriangles