Search code examples
c#.nettuplesunboxingvaluetuple

Quick ValueTuple initialization with 1 argument


I want to create a simple way to create a matrix-like structure for users. This means that the user can define rows and columns. For now its looks like this:

var matrix = new()
{
   new() { Item1, Item2 } // Row
   new() { Item3, Item4 } // Row
}

Pretty good, but for large matrices it already looks not compact enough. I try to use ValueTuple for creating matrices:

(
 (Item1, Item2),
 (Item3, Item4)
)

And it works, but if we try to create matrix with 2 row and 1 column it will be reversed.

(
 (Item1),
 (Item2)
)

Previous code the same as:

(
 Item1, Item2
)

Is exist any way to disable automatic unboxing ValueTuple's in C#? So that (Item1) will be equals ValueTuple.Create(Item1).

P.S. In IDE it looks like. But matrix = ValueTuple<int, int> not ValueTuple<ValueTuple, ValueTuple>

enter image description here


Solution

  • As Matthew Watson mentioned, C# supports multidimensional arrays.

    But if you define an extension method like this:

    public static class ListExtensions
    {
        public static void Add<T>(this List<List<T>> list, params T[] values)
            => list.Add(new List<T>(values));
    }
    

    you can write code like this:

    var matrix = new List<List<int>>
    {
        { 1, 2, 3 },
        { 4, 5, 6 },
        { 7, 8, 9 },
    };
    

    As long as there's an applicable collection initializer, you can use this compact syntax.