+ 1

Methods practice

Hey everyone, So I just tried to play around and practice creating and using a method. At first it worked perfectly, but once I wanted to ask for user input and then activate it in the method, it throws an error message that it cannot implicitly convert a type string to int. What is strange is that if you look at the method definition, I entered 3 parameters, the first one being a string, the second an integer and the third a string with a default input. I used the method in the main section and it worked well. However after I tried to place in the function the string and integer given by the user, it doesn't let me run the program. Corrections and explanations would be highly appreciated! Thanks! Here's the code: -------------------------------------------------------------------- using System; namespace ConsoleApp4 { class Program { static void Main(string[] args) { /* This code works perfectly well Experiment("Theresa", 40); Experiment("Oren", 52); Experiment("Tom", 37); Experiment("Eliran", 36); */ Console.WriteLine("\nType in your name: "); string name = Console.ReadLine(); Console.WriteLine("\nNow type in your age: "); int age = Console.ReadLine(); /* I don't understand why this throws an error of not being able to implicitly convert a string to int. */ Experiment(name, age); } // method that takes 3 parameters and writes to the console your name and age. static void Experiment(string name, int age, string years = "years old") { Console.WriteLine(

quot;Your name is {name}, and you are {age} {years}"); } } }

23rd Sep 2021, 9:07 AM
Tom Eckert
Tom Eckert - avatar
2 Respostas
+ 4
The `Experiment()` method requires <age> argument to be an `int`, but here you forgot to convert input from `Console.ReadLine()` (which returns a string) into an `int`. int age = Convert.ToInt32(Console.ReadLine());
23rd Sep 2021, 10:43 AM
Ipang
+ 2
You are totally right! I forgot that the Console. ReadLine() method always returns a string. Thank you so much! Perfect 🥰
23rd Sep 2021, 10:49 AM
Tom Eckert
Tom Eckert - avatar