C# 7 Features - Tuples
In this blog post
we are going to see the new feature called Tuple type introduced with C# 7.0 Version
by Microsoft.
“C# 7.0 adds a number
of new features and brings a focus on data consumption, code simplification and performance.
Perhaps the biggest features are tuples, which make it easy to have multiple results,
and pattern matching,
which simplifies code that is conditional on the shape of data. But there are many other
features big and small. We hope that they all combine to make your code more efficient and clear, and you
more happy and productive,”
Mads Torgersen, program manager at Microsoft, wrote in a post.
Tuples are
a series of finite no of elements/values.If you are aware of Tuple Class Which
was introduced with .NET 4.0 and still exists, is not same as the Tuple type.Till
C# 6.0 version we are returning multiple values from a method using custom datatype(user
defined type), out parameters, ref type , arrays and dynamic return type or a tuple
object.
C# 7.0 provides tuple
type and tuple literals to return multiple values from a method in a different approach.
Note: Tuples are value types.
Syntax of tuple type
looks as below..
(<datatype> [name1],<datatype> [name2]) methodName(parameters){
return (<val1>,<val2>);}
following line shows
the basic usage of returning values to tuple type.
(int a,string b) = (1,"hello");
Console.WriteLine($"{a} {b}");
Below is the another example of tuple type. Here we can see tuple type used with existing variables.
int a=0;
int b=0;
(a,b) = (1,"hello");
Real example below
for more understanding about the tuple type
(string ,string ) getfirstlastname(string name)
{
string[] val = name.Split(' ');
return (val[0],val[1]);
}
(string fname,string lname) = getfirstlastname("syed khaleel");
Console.WriteLine($"{fname} {lname}");
In order to work with tuple type we need to add System.ValueTuple using Nuget package manager.
Tuple literals
if we assign values of the tuple typle to local variable declared with var keyword is known as tuple literals. Here the names of the items/fields inside are not known to us.
var result = getfirstlastname("syed khaleel");
//using tuple literals we can define the names
var details = (Name:"Syed Khaleel", Age:30);
Evolution of C# and it's Versions in a Picture below...
Hope you understand
this article..Please comment below if you have and questions..
Thanks for reading..Keep
sharing to your friends..to get more articles like this.
Thanks,
Dotnetcodetree
Comments
Post a Comment