Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Simple "Hello World" in console missing a line of code?

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

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            string userName = "";
            int userAge = 0;
            int currentYear = 0;

            Console.Write("Please enter your name: ");
                userName = Console.ReadLine();
            Console.Write("Please enter your age: ");
            userAge = Convert.ToInt32(Console.ReadLine());
            Console.Write("Please enter the current year: ");
            currentYear = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Hello World, my name is {0} and I'm {1} years old, I was born on the year {2} .", userName, userAge, currentYear - userAge);
        }
    }
}

It is missing the last Console.WriteLine for some reason, after I enter the currentYear, it closes the application without displaying the string to the console. Im just now starting to learn c# so also any other sources to help me learn are also welcome, thanks! (btw im using visual studio)

like image 330
Zach Avatar asked Dec 07 '25 06:12

Zach


1 Answers

You need to add Console.Read or Console.ReadLine at the bottom of your code

Console.ReadLine();

Or else the console will close because the blocks of codes has already been executed.

Side Note : Possible Duplicate of this Question Why is the console window closing immediately without displaying my output?

like image 135
keysl Avatar answered Dec 09 '25 18:12

keysl