Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I create a tuple with the "Tuple" class out of input provided from the user

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading