Read a console line in C #

3
  

CS1503 Argument 1: Can not convert from "method group" 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.

    
asked by anonymous 08.03.2018 / 04:47

3 answers

7

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

Inthiscaseifsomeoneenterssomethingwrongwillbreaktheprogram,soitworksandisright:

usingstaticSystem.Console;publicstaticclassProgram{publicstaticvoidMain(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");

    }
}

See running on .NET Fiddle . And no Coding Ground . Also I placed GitHub for future reference .

    
08.03.2018 / 11:12
4

You can type this line of conversion in this way:

int age = int.Parse(Console.ReadLine());
    
08.03.2018 / 04:53
4

Just to register, the error you are giving is because you forgot to Parenteses () in the Console.ReadLine() method. If you change and use Convert.ToInt32(Console.ReadLine()); will work as well as int.Parse() . Oh and do not forget to add Console.ReadLine() at the end of the program so your program will not close without you being able to see anything. The code repaired var 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();
        }
    }
}
    
08.03.2018 / 05:43