Home > OS >  Quick ValueTuple initialization with 1 argument
Quick ValueTuple initialization with 1 argument

Time:06-13

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

CodePudding user response:

In answer to your supplementary question in the comments,

Maybe there is another way to define a matrix compactly, without `new()'?

Have you considered just using a 2D array for the matrix? That's more succinct to initialise. For example, to initialise a matrix of doubles you can do this:

var matrix = new [,]
{
    {0.0, 0.1, 0.2, 0.3},
    {1.0, 1.1, 1.2, 1.3},
    {2.0, 2.1, 2.2, 2.3},
    {3.0, 3.1, 3.2, 3.3},
    {4.0, 4.1, 4.2, 4.3}
};

CodePudding user response:

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.

  • Related