Recently, Microsoft announced many new features in C# 7.0 along with Visual Studio 2017. Tuples are a new feature of C# 7.0 in Visual Studio 2017. Tuples aren’t new to C# or .NET ,they were first introduced as a part of .NET Framework 4.0.
Tuples are very useful thing where you can replace the list, dictionary and observableCollection returning more than one value from a method anonymously. Now a day's return multiple values from a method is now a common practice, for this we had two options until C# 6.0.
- To have return type like Array, List<>, ArrayList or Dictionary.
- Use out or ref keyword
With C# 7.0 we get special features to use of tuple by extending the functionality by adding tuple types and tuple literals. The tuple type is defined by specifying the types and names. To create an instance of a tuple, a tuple literal can be used.
Let's have a fresh start.
Step 1: Start your Visual Studio 2017 RC
Note: C# 7.0, basically introduce in Visual Studio 2017.
Step 2: Create a New Console App and name it as you want. Here, we name it as "TupleDemo"
Step 3:In Program.cs, Add following code by creating a new Class Named "Demo" and declare a method pubilc (string,string,int) GetData(). Here we get an error.
class Demo
{
public (string, string, int) GetData()
{
return ("Avnish", "R&D", 001);
}
}
Step 4:For removing this error, We go to add a Nuget Package. By right click to "References" in solution explorer then click on "Manage NuGet Package...". Now, Search for "System.ValueTuple" then install such package
Step 5: Wow, now no error found here.
Step 6: Add the following code, by creating object of Demo Class and call the method GetData() with the help of this object.
static void Main(string[] args)
{
Demo demo = new Demo();
var result = demo.GetData();
Console.WriteLine("Name= " + result.Item1 + " Dept = " + result.Item2 + " Id= " + result.Item3);
Console.ReadKey();
}
Step 7: Build and run the project "TupleDemo" then we get the results with the help of the tuple.
Step 8:For few more interactive use of tuples, add the following code in Project.
namespace TupleDemo
{
class Program
{
static void Main(string[] args)
{
Demo demo = new Demo();
var result = demo.GetData();
Console.WriteLine("Name= " + result.name + " Dept = " + result.dept + " Id= " + result.id);
var result2 = demo.GetData2();
Console.WriteLine("Name= " + result2.Item1 + " Dept = " + result2.Item2 + " Id= " + result2.Item3);
var result3 = demo.GetData3();
Console.WriteLine("Name= " + result3.Item1 + " Dept = " + result3.Item2 + " Id= " + result3.Item3);
Console.ReadKey();
}
}
class Demo
{
public (string name, string dept, int id) GetData()
{
return ("Avnish", "R&D", 001);
}
public Tuple GetData2()
{
return new Tuple("Rakesh", "Marketing", 002);
}
public (string, string, int) GetData3()
{
return ("Mukesh", "Testing", 003);
}
}
}
Step 9: Build and run the project "TupleDemo" then we get the results with the help of the tuple.
Thanks for reading.
;