In this article, let us see how to use the latest feature of Tuple in C# 7.0.
Usually when we want to return multiple values from a method, then we will create a model class with the required property and will return it as a return type from the method.
Sample code without Tuple,
-
- public class ReturnTypeWithoutTuple
- {
- public int _int { get; set; }
- public List<long> _longlist { get; set; }
- }
-
- public class WithoutTupleApplication
- {
- public ReturnTypeWithoutTuple WithoutTuple()
- {
-
- ReturnTypeWithoutTuple returnTypeWithoutTuple = new ReturnTypeWithoutTuple();
- returnTypeWithoutTuple._int = 10;
- returnTypeWithoutTuple._longlist.Add(1);
- returnTypeWithoutTuple._longlist.Add(2);
-
- return returnTypeWithoutTuple;
- }
- }
- static void Main(string[] args)
- {
- WithoutTupleApplication withoutTupleApp = new WithoutTupleApplication();
-
- ReturnTypeWithoutTuple _data = withoutTupleApp.WithoutTuple();
-
- }
But with the latest feature in C# 7, we don’t need to create separate model class anymore for every return type. Instead, let us see how we can use the tuple feature to do the same functionality of the above code.
To use the tuple in the application, first, we have to add the System.ValueTuple from NuGet package.
Sample Code with Tuple along with custom names as a return type,
- public class WithTupleApplication
- {
- public (int _int, List<long> _longlist) WithTuple()
- {
- int intvalue = 10;
- List<long> longlist = new List<long>();
- longlist.Add(1);
- longlist.Add(2);
-
- return (intvalue, longlist);
- }
- }
The names for return type can be anything as you required.
- static void Main(string[] args)
- {
- WithTupleApplication withTupleApplication = new WithTupleApplication ();
- var _data = withTupleApplication.WithTuple();
-
- }
Now, we can access the returned values with the custom name. We can also return the tuple without the custom name as well like the below code snippet.
Sample Code with Tuple without custom names as return type,
- public class WithTupleApplication
- {
- public (int, List<long>) WithTuple()
- {
- int intvalue = 10;
- List<long> longlist = new List<long>();
- longlist.Add(1);
- longlist.Add(2);
-
- return (intvalue, longlist);
- }
- }
The return type will be only the datatype. Now, let us call the method from our main method.
- static void Main(string[] args)
- {
- WithTupleApplication withTupleApplication = new WithTupleApplication ();
- (int, List<long>) _data = withTupleApplication.WithTuple();
-
- }
Advantage of tuple
Avoids creation of model required only for few places in the application.
Conclusion
Tuple is a very effective feature in C# 7.0 and it can be used when we want to return more than one value from a method. Tuple can return 8 values and if we want to return more values then we can use the nested tuple on the 8th place.