0

This won't compile

public struct Matrix 
{
    readonly double[] elems;
    public Matrix(int rows, int cols) 
    {
        this.elems=new double[rows*cols];
        this.Rows=rows;
        this.Columns=cols;
    }
    public int Rows { get; private set; }
    public int Columns { get; private set; }
}

but this does:

public struct Matrix 
{
    readonly double[] elems;
    public Matrix(int rows, int cols) : this()
    {
        this.elems=new double[rows*cols];
        this.Rows=rows;
        this.Columns=cols;
    }
    public int Rows { get; private set; }
    public int Columns { get; private set; }
}

Why is that?

The compile time error is

error CS0188: The 'this' object cannot be used before all of its fields are assigned to

and

error CS0843: Backing field for automatically implemented property 'SO_MMul.Matrix.Columns' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.

Doesn't the parameterized constructor call the default constructor anyway?

John Alexiou
  • 28,472
  • 11
  • 77
  • 133
  • 1
    In particular, [this answer](http://stackoverflow.com/a/7670809/2642204) explains the issue explicitly. – BartoszKP Apr 29 '15 at 17:53
  • The parameterized constructor never calls `this()` by default. In class types, it calls `base()` by default. In structs, `base()` is meaningless (`object` is not applicable until the struct is boxed), so in any case you have to say `this()` explicitly. – Theodoros Chatzigiannakis Apr 29 '15 at 18:00

0 Answers0