2

I am building a matrix class ( I am aware one exists), I'm thinking about initialization. Currently one of the initializations is

  double[,] data;
  public Matrix(double[,] data)
  {
      if (data.GetLength(0) == 0 || data.GetLength(1) == 0)
      {
          throw new ArgumentException();
      }
      this.data = (double[,])(data.Clone());
  }

which is nice because it can be initialized like

  Matrix matrix= new Matrix(new double[,]{{1, 0  , 0  },
                                           {1, 0.5, 0  }});

Is there a way to do this more compact, something like

  Matrix matrix= new Matrix{{1,0}, {1,1}, {1,5}};

or even better

  Matrix matrix = {{1,0}, {1,1}, {1,5}};

?

2 Answers 2

4

Well, not the last - but the penultimate one is at least possible using collection initializers:

  • Implement IEnumerable (which can be done explicitly, throwing an exception if you really don't want it to be called normally)
  • Create an Add(params double[] values) method

The trouble is, this makes your matrix mutable. You could potentially create a MatrixBuilder class, and use:

Matrix matrix = new MatrixBuilder{{1,0}, {1,1}, {1,5}}.Build();

There are other issues, of course -you'd need to check that the "matrix" didn't suddenly start changing dimensions half way through, e.g.

Matrix matrix = new MatrixBuilder{{1,0}, {1,1,2,2,2,2,2,2}, {1,5}}.Build();
Sign up to request clarification or add additional context in comments.

Comments

2

You can use an implicit conversion operator to create code like this:

Matrix matrix = new double[,] {{1,0}, {1,1}, {1,5}};

This is the related code:

class Matrix {
  // ...
  public static implicit operator Matrix(double[,] data) {
    return new Matrix(data);
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.