3

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.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
EBDS
  • 1,244
  • 5
  • 16
  • 1
    Duplicate of [When to use: Tuple vs Class in C# 7.0](https://stackoverflow.com/questions/44650636/when-to-use-tuple-vs-class-in-c-sharp-7-0) – Adam Sep 16 '22 at 04:07
  • 4
    Does this answer your question? [What's the difference between System.ValueTuple and System.Tuple?](https://stackoverflow.com/questions/41084411/whats-the-difference-between-system-valuetuple-and-system-tuple) – Muhammad Sulaiman Sep 16 '22 at 04:12
  • 1
    "I looked at the source for both Tuple and ValueTuple. The difference is that Tuple is a class and ValueTuple is a struct that implements IEquatable. That means that Tuple == Tuple will return false if they are not the same instance, but ValueTuple == ValueTuple will return true if they are of the same type and Equals returns true for each of the values they contain." [source](https://stackoverflow.com/a/41084594/4108016) – Muhammad Sulaiman Sep 16 '22 at 04:13
  • I sorry. Before, I didn't know about these terms System.ValueTuple and System.Tuple. I tired to search () and Tuple<>, didn't get anything helpful. That's why I posted the question. – EBDS Sep 16 '22 at 14:17

1 Answers1

6

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);
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104