c# – How to extend/inherit/decorate a 2D array

Question:

Is there any way to expand the built in rectangular array in c#? For instance:

public class Array2D<T>:????
{
    private T[,] _data;

    public Array2D(T[,] vals)
    {
        _data = vals;
    }

    public IEnumerable<T> Row( int iRow)
    {
        return _data.Cast<T>().Select((t, j) => _data[iRow, j]);
    } 
}

Answer:

Use extension methods ?

public static class TwoDimensionalArrayExtensions
{
    public static IEnumerable<T> Row<T>(this T[,] array, int iRow)
    {
        if (array == null)
        {
            throw new ArgumentNullException(nameof(array));
        }
        if (iRow < array.GetLowerBound(0) && iRow > array.GetUpperBound(0))
        {
            throw new ArgumentOutOfRangeException(nameof(iRow));
        }

        for (int columnIndex = array.GetLowerBound(1); columnIndex <= array.GetUpperBound(1); columnIndex++)
        {
            yield return array[iRow, columnIndex];
        }
    }
}

Usage:

static void Main(string[] args)
{
    var array = new int[2, 2] { { 1, 2 }, { 3, 4 } };
    foreach (var value in array.Row(0))
    {
        Console.WriteLine(value);
    }
}
Scroll to Top