views:

48

answers:

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}};

?

+3  A: 

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();
Jon Skeet
+1  A: 

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);
  }
}
Jordão