I just saw the following syntax in code: (int, string) testTwo
It seems to mimic a Tuple, but the return types are incompatible with a Tuple. Example:
Tuple<int, string> test = Test.Get(); // This doesn't work
(int, string) testTwo = Test.Get(); // This works
public static class Test
{
public static (int, string) Get()
{
return (1, "2");
}
}
Seems like you can name the params too, but this appears to be for readability only, e.g.:
public static (int foo, string bar) Get()
- What is this syntax called?
- What's the real world use case?
CodePudding user response:
There are two tuple types in the modern C#/.NET - "old" ones - series of Tuple classes and value tuples introduced in C# 7 which are syntactic sugar based on series of ValueTuple structs and there is no conversions between those two (though both can be deconstructed - var (i1, i2) = Tuple.Create(1,2); and var (i1, i2) = (1,2); both are a valid code).
Tuples vs
System.TupleC# tuples, which are backed by
System.ValueTupletypes, are different from tuples that are represented bySystem.Tupletypes. The main differences are as follows:
System.ValueTupletypes are value types.System.Tupletypes are reference types.System.ValueTupletypes are mutable.System.Tupletypes are immutable.- Data members of
System.ValueTupletypes are fields. Data members ofSystem.Tupletypes are properties.
CodePudding user response:
When creating a Tuple in parentheses it's a value type, specifically it's a System.ValueTuple. System.Tuple is a reference type.
CodePudding user response:
It's a Tuple type which maps to System.ValueTuple, a value type, available in .NET Core and Framework 4.7 .
A ValueTuple and a Tuple are distinct, incompatible types.
The syntax with parentheses is tuple assignment and deconstruction.
