Home > Enterprise >  How to add multiple constructors to a struct?
How to add multiple constructors to a struct?

Time:10-03

I have the following code:

struct test {
    public int a;
    public int b;

    public test(int a) {
        this(a, null);
    }

    public test(int a, int b) {
        this.a = a;
        this.b = b;
    }
}

Where I would like to have two different constructors for the test struct, one where I only need to pass in a and another where I can pass in both a and b.

This code does not work, as it fails with a few errors:

For the public test(int a) { line:

Field 'test.a' must be fully assigned before control is returned to the caller

Field 'test.b' must be fully assigned before control is returned to the caller

And for the this(a, null); line:

Method name expected.

The 'this' object cannot be used before all of its fields have been assigned

CodePudding user response:

struct test {
    public int a;
    public int b;

    public test(int a) : this(a, 0) { }
    
    public test(int a, int b = 0) {
        this.a = a;
        this.b = b;
    }
}

You can't assign null to int. Also your variable names are ambiguous. You can use an optional parameter to achieve what you're looking for. Or chaining constructors.

CodePudding user response:

Try this

struct Test 
{
    public readonly int a;
    public readonly int b;

    public Test(int a) : this()
    {
        this.a = a;
        this.b = 0;
    }

    public Test(int a, int b) : this()
    {
        this.a = a;
        this.b = b;
    }
}

an alternative is to use an optional parameter with one constructor

    public Test(int a, int b = 0) : this()
    {
        this.a = a;
        this.b = b;
    }

or instead of 0 to use default(int), or just default

    public Test(int a) : this()
    {
        this.a = a;
        this.b = default(int);
    }

The : this() call is added by Microsoft when the create constructor tool is used so I have added it here. I think it is just to remind the reader of the code that space in the stack is allocated first and then the fields are assigned.

I also added the readonly keyword because mutable structures are evil and to emphasize the requirements the fields need to be all defined before the constructor ends.

Or you can always use one constructor from another constructor

    public Test(int a) : this(a, 0)
    { }
  • Related