Read a console line in C#

Asked

Viewed 608 times

3

CS1503 Argument 1: cannot convert from "group of methods" to "Object"

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Teste
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("QUal é a sua idade?");
            int age = Convert.ToInt32(Console.ReadLine); // erro nesta linha
            if (age < 16)
            {
                Console.WriteLine("Não é permitido entrada de menores de 16.");
            } else if (age >= 16)
            {
                Console.WriteLine("Bem-Vindo!");
            }
        }
    }
}

I’m Using Visual Studio 2017.

3 answers

6


Working is different from being right and this is one of the most important things you need to learn in software development.

Funcionar é diferente de estar certo

In this case if someone enters something wrong will break the program, so it works and is right:

using static System.Console;

public static class Program {
    public static void Main(string[] args) {
        WriteLine("Qual é a sua idade?");
        if (int.TryParse(ReadLine(), out var age)) {
            if (age < 16) WriteLine("Não é permitido entrada de menores de 16.");
            else WriteLine("Bem-Vindo!");
        } else WriteLine("O valor informado é inválido");

    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

3

You can write that conversion line this way:

int age = int.Parse(Console.ReadLine());

3

Just for the record, the mistake you’re making is because you forgot to put the Parenteses () in the method Console.ReadLine(). If you change and use the Convert.ToInt32(Console.ReadLine()); It will work as well as int.Parse(). And don’t forget to add the Console.ReadLine() at the end of the program so that your program doesn’t close without you being able to see anything. The fixed var code looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Teste
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("QUal é a sua idade?");
            int age = Convert.ToInt32(Console.ReadLine()); // erro nesta linha
            if (age < 16)
            {
                Console.WriteLine("Não é permitido entrada de menores de 16.");
            } else if (age >= 16)
            {
                Console.WriteLine("Bem-Vindo!");
            }

           Console.ReadLine();
        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.