I am coding in C# and I have a class with a property of type List<List<T>> that gets initialized in the constructor. The code is as follows:
public class MyMatrix<T>
{
private readonly List<List<T>> matrix;
public MyMatrix(int dimension)
{
this.matrix = new List<List<T>>();
for (int i = 0; i < dimension; i++)
{
List<T> subList = new List<T>();
this.matrix.Add(subList);
}
}
.....
The problem is that if I create a new object of type MyMatrix the sublists are empty so if I invoke the ToString() method of the class or any other method that returns the values contained in the sublists I get an OutOfOrder Exception as expected. Get and Set methods are as follows:
public T Get(int row, int column)
{
return this.matrix[row][column];
}
public void Set(int row, int column, T value)
{
this.matrix[row].Insert(column, value);
}
If I initialize the sublists with a Set method then everything is fine obviously. I can't change the constructor as it is up to the user of the class to initialize the sublists so it is not possible to know in advance what they are going to contain. How would you manage the exceptions in the class methods or would you bother at all?
if (this.matrix[row].Length < column - 1) { throw new ArgumentException(); }?ToString()you can returnstring.Empty. CallingToStringon empty matrix shouldn't be an exceptionMyMatrix.ToString()should know and respect the array sizes (possibly zero). Accessing non-existing elements from user code in a list is a logical/application error and is correct to throw. I do not quite understand the problem (seriously). @wudzik Yes, returning a default prevents "crashing" but may just camouflage serious errors.ToStringon non-existing element (row) it should throw exception. I understand that OP is saying that he runsToStringon empty Matrix just like:var m = new Matrix(); m.ToString()and it shouldn't throw.