NGenerics Overview - The ObjectMatrix

NGenerics Overview - The ObjectMatrix

Previous instalments

General Data Structures


Looking at tree structures will make your eyes bleed, so we’ll take a break to discuss one of the simpler data structures NGenerics offers - the ObjectMatrix. The ObjectMatrix is a representation of a 2-dimensional array of objects, like, for example, a game board :

Tic tac toe

Why not use a two-dimensional array in the first place?  The ObjectMatrix offers the following useful operations at the time of writing:

  • Rows and Columns - formal definition of rows and columns - much better than having .Length scattered all over your code.
  • GetSubMatrix -  enables the retrieval of a subset of the matrix.
  • InterchangeRows and InterchangeColumns - swap individual rows and columns.
  • GetRow and GetColumn - provides an easy way of retrieving individual rows and columns.
  • AddRow and AddColumn - add new rows and columns when you need more space.
  • DeleteRow and DeleteColumn - delete individual rows and columns.
  • Resize - resize the matrix to have any arbitrary column/row count.

Use it like you would use any two dimensional array :

var matrix = new ObjectMatrix(3, 3);
matrix[0, 0] = new Cross();
matrix[0, 1] = new Nought();
matrix[0, 2] = new Nought();
matrix[1, 0] = new Nought();
matrix[1, 1] = new Cross();
matrix[2, 2] = new Cross();

var enumerator = matrix.GetEnumerator();

while (enumerator.MoveNext())

The ObjectMatrix is also the base class for one of the biggest classes in NGenerics - the mathematical Matrix, which we’ll get to in a later post.

Photo by Markus Spiske on Unsplash

See also