The usual way to create a custom data type (similar to what you are asking) in C# is to use class
or struct
.
class Foo { int test; string name; }
struct Foo { int test; string name; }
var foo = new Foo() {test = 10, name = "some_name"};
As you will notice, this works great when we need a lot of customization in the class - attributes, methods, properties, etc. But numerous times, we just don't need all that bells and frills. We just need to pass multiple variables of different types
With the release of LINQ in .NET Framework 2.0, came anonymous type
classes which provide named but read-only properties with a concise syntax, but these types were limited to being used within a method, and cannot be passed between methods.
var foo = new {test = 10, name = "some_name" }
In .NET Framework 4.0, they came up with the Tuple
struct. There is no magic here, it is just a predefined generic struct. There are variants of this struct with up-to 8 members of different types.
var foo = new Tuple<int, string>(10, "some_name");
var foo = Tuple.Create(10, "some_name");
The obvious limitation to this approach was that the members had generic names like Item1
, Item2
, etc - making it unsuitable to pass data over "long distance". And the benefit was that it was very concise without unwanted overhead.
With the newest version of C# 7, they are working towards combining the benefits of anonymous types and Tuple, to anonymous tuple types (called ValueTuple
) which can be passed between functions. In fact they can be created implicitly with concise syntax.
(test, name) Foo() {
return Bar()
}
(test, name) Bar() {
return (1, "new_name");
}
var allItems = new List<(int test, string name)>() {
(1, "some_name"),
(2, "new_name"),
}
With all this background, I would highly recommend using the ValueTuple
for data structures which serve as containers to pass data, and to write an explicit class
or struct
when you need more expressive power (attributes, properties, methods, etc)
Typically speaking, when you have very few members (say less than 5), ideally of ValueType
, you will get performance benefits on using ValueTuple
which are struct
. I would not recommend to focus on this aspect though, unless it is very performance centric application.
Update:
To make sure you can use the ValueTuple
, you might have to check and confirm a few things.
- Make sure you are using C# 7 or higher (Project Properties -> Build -> Advanced -> Language Version)?
- Make sure you are using .NET framework 4.7 or higher (Project Properties -> Application -> Target Framework)?
- If your .NET Framework version is lower than 4.7, then you can either install the .NET framework version 4.7 (or higher) or install the
System.ValueTuple
nuget package. There is no using clause to refer to it.