C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C# TuplesC# tuple is a data structure that is used to store sequence of elements. Tuple with n elements are known as n-tuple. We can use Tuple for the following reasons.
In C#, tuple is a class that contains static methods. These methods are used to create tuple objects. Following is the syntax of Tuple class. C# Tuple Class Syntaxpublic static class Tuple C# Tuple Methods
The following table contains methods of Tuple class.
Let's see an example that creates a Tuple to store book information. Here, we are creating Tuple without using static method. C# Tuple Example 1
using System;
namespace CSharpFeatures
{
class TupleExample
{
public static void Main(string[] args)
{
// Creating Tuple of three values
var book = new TupleOutput: -----------------Book's Record--------------------- Title C# in Depth Author Jon Skeet Price 100.5 We can use static methods of Tuple class to create Tuple. In the following example, we are using create method. C# Tuple Example with Static Method
using System;
namespace CSharpFeatures
{
class TupleExample
{
public static void Main(string[] args)
{
// Creating Tuple using helper method (Create)
var book = Tuple.Create("C# in Depth", "Jon Skeet", 100.50);
Console.WriteLine("-----------------Book's Record---------------------");
Console.WriteLine("Title " + book.Item1);
Console.WriteLine("Author " + book.Item2);
Console.WriteLine("Price " + book.Item3);
}
}
}
Output: -----------------Book's Record--------------------- Title C# in Depth Author Jon Skeet Price 100.5 We can use tuple to return multiple values from a method. In the following example, we are returning a tuple to the caller method. C# Tuple Example Return Multiple Values
using System;
namespace CSharpFeatures
{
public class Student
{
public static void Main(string[] args)
{
var (name,email) = Show();
Console.WriteLine(name+" "+email);
}
static (string name, string email) Show()
{
return ("irfan","irfan@gmail.com");
}
}
}
Next TopicHTML Aside tag
|