I have the following code:
using System;
using System.Collections.Generic;
namespace c_sharp_exercises
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please provide 6 numbers seperated by space:");
var line = Console.ReadLine().Split(",");
var num1 = int.Parse(line[0]);
var num2 = int.Parse(line[1]);
var num3 = int.Parse(line[2]);
var num4 = int.Parse(line[3]);
var num5 = int.Parse(line[4]);
var num6 = int.Parse(line[5]);
var num7 = (num1, num2, num3, num4, num5, num6);
Console.WriteLine(num7);
}
}
}
Which will ask for 6 different numbers and when providing numbers let's say from 1-6, then it will print the following in the terminal:
(1, 2, 3, 4, 5, 6)
.
My question is how do I do this with the Tuple
class?
What I tried is the following:
using System;
using System.Collections.Generic;
namespace c_sharp_exercises
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please provide 6 numbers seperated by space:");
var line = Console.ReadLine().Split(",");
var num1 = int.Parse(line[0]);
var num2 = int.Parse(line[1]);
var num3 = int.Parse(line[2]);
var num4 = int.Parse(line[3]);
var num5 = int.Parse(line[4]);
var num6 = int.Parse(line[5]);
Tuple<int,int,int,int,int,int> tuple = line;
Console.WriteLine(tuple);
}
}
}
Which gave me the following error:
error CS0029: Cannot implicitly convert type 'string[]' to 'System.Tuple<int, int, int, int, int, int>'
What am I doing wrong here and should I change my whole approach?
CodePudding user response:
You cannot convert a string (or an array) into a Tuple.
Instead you can do
var tuple = Tuple.Create(num1, num2, num3, num4, num5, num6);
CodePudding user response:
see this link Tuple
You can define tuples with an arbitrary large number of elements:
var t = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26);
Console.WriteLine(t.Item26);
The num7
that you defined is actually a tuple:
var num7 = (num1, num2, num3, num4, num5, num6);
if you run this code, you see the result:
string _type = num7.GetType().Name;
Console.WriteLine(_type); //the result is ValueTuple`6