What is the purpose of Tuple? Explain with example.

 Posted by Niladri.Biswas on 7/11/2012 | Category: C# Interview questions | Views: 2080 | Points: 40
Answer:

C#4.0 has introduce a new feature call Tuple.It is useful when we want to return more than one value from a method or function.

Let us look the below example

class Program

{
static void Main(string[] args)
{

var returnValue = Calculate();

string format =
"Addition: {0}" + Environment.NewLine +
"Subtraction: {1}" + Environment.NewLine +
"Multiplication: {2}" + Environment.NewLine +
"Division: {3}";
string result = string.Format(format, returnValue.Item1, returnValue.Item2, returnValue.Item3, returnValue.Item4);
Console.WriteLine(result);
Console.ReadKey(true);
}

private static Tuple<int,int,int,int> Calculate()
{
int num1 = 20;
int num2 = 10;
return Tuple.Create(num1+num2,num1-num2,num1 * num2,num1/num2);
}
}


As can be seen that using Tuple we can return multiple values from the function/method in a better and readable way.


Source: http://www.codeproject.com/Art | Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response