views:

1113

answers:

3

I'm working on a class that is storing a 2D array of class MyType and would like it to use dynamic data types. i.e. not MyType[,]

The problem with MyType[,] is that the class doesn't know the size of the array ahead of time, and I don't want to go to the trouble of managing array re-sizing if it's been done elsewhere in the .NET Frameworks.

The class will not know maximum array size at any given moment, but the array will be dense. I know I can use static arrays, and re-allocate memory as needed, but I'd prefer to use a built-in implementation if possible.

Is there anything better than List<List<MyType>> for this purpose?

Edit 1: specified that array is dense;

Edit 2 and 3: specified problem with MyType[,]

+1  A: 

It depends on how sparse your structure will be. For instance, if your entries will resemble something like myTypes[0, 1] and myTypes[134, 544], you'd be much better off using sparse matrix. Otherwise, List<List<MyType>> will do.

Anton Gogolev
+1  A: 

Create your own List<List<T>> encapsulation like :

public class Matrix<T>
{
   List<List<T>> matrix;

   public void Add(IEnumerable<T> row)
   {
      List<T> newRow = new List<T>(row);
      matrix.Add(newRow);
   }

   public T this[int x, int y]
   {
      get  { return matrix[y][x]; }
   }
   ....
}

define your own set of operation on it ! Be freee !

By encapsulating it, you can decide to go for a more optimised implementation later if it's not sufficient.

Think Before Coding
+1  A: 

For a dense 2D matrix, a rectangular array is ideal. What is the issue you are having with SomeType[,]? Note that you can create dynamic arrays either with Array.CreateInstance(type, dim0Size, dim1Size), or with generics:

void DoWork<T>(...) {
   T[,] data = ...
}
DoWork<Foo>(...);
DoWork<Bar>(...);

(perhaps using MakeGenericMethod if you want to use ad-hoc types)

Marc Gravell
Clarified my problem with SomeType[,] in edit to question.
biozinc