Using tuples in C#, (A, B, C) vs Tuple<string, string, string>

881 views Asked by At

I've created a method:

public static Tuple<string, string, string> SplitStr(string req)
{
    //...
    return (A, B, C)
}

it complaint that "CSOOZQ: Cannot implicitly convert type '(strinq _keyword, strinq _filterCondition, strinq _filterCateqory)' to 'System.Tuple<strinq, strinq, string)‘"

But if code:

public static (string, string, string) SplitStr(string req)
{
    //...
    return (A, B, C)
}

The error goes away. From the error, it looks like the bracket form of tuple and the one Tuple<> are different.

  1. Is it safe to use the bracket form ?
  2. What's the difference, why are there 2 types of Tuple ? Should I use the Tuple<> in my case ? How do I return the Tuple ?

Thanks.

1

There are 1 answers

0
Theodor Zoulias On BEST ANSWER

The type Tuple<T1,T2,T3> is different than the type ValueTuple<T1,T2,T3>. In general using value-tuples is preferable to reference-type tuples, because:

  1. They don't add pressure to the garbage collector.
  2. There is language support for naming the members of a value-tuple.

My suggestion is to declare the SplitStr like this:

public static (string First, string Middle, string Last) SplitStr(string request)
{
    // ...
    return (a, b, c)
}

You can then consume it like this:

var parts = SplitStr(request);
// Use parts.First, parts.Middle and parts.Last

...or using tuple deconstruction, which is also possible with reference-type tuples.

var (first, middle, last) = SplitStr(request);