C# Console Input and Output methods


//Sample Program to show the console input and output methods in C#

using System;

namespace TrainingSamples
{
    class Demo
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter Your Name");
            string EmployeeName = Console.ReadLine();

            Console.WriteLine("Enter Your Age");
            Int32 currentAge = int.Parse(Console.ReadLine()); //or
            //Int32 currentAge = Convert.ToInt32(Console.ReadLine());

            //Output by Concatenation
            Console.WriteLine("Your Name is " + EmployeeName + "\nYour Age is " +                                                                                  currentAge);

            //Output by Placeholders
            Console.WriteLine("Your Name is {0},\nYour Age is {1}", EmployeeName,                                                                                  currentAge);

            //Output by string interpolation (Introduced in C# 6.0)
            Console.WriteLine($"Your Name is {EmployeeName},\nYour Age is {currentAge}");

            Console.Read(); //or
            //Console.ReadKey(); //or
            //Console.ReadLine();
        }
    }
}

/*----Output------


Enter Your Name
Syed

Enter Your Age
35

Your Name is Syed
Your Age is 35
Your Name is Syed,
Your Age is 35
Your Name is Syed,
Your Age is 35
*/

Points to Learn from this Program

1. Console.ReadLine() capable of accepting the input in the form of text including spaces from the left end to the right end of the command window 

2. We can convert the text/string input received by Console.ReadLine() to possible types using conversion methods like int.Parse() or Convert.ToInt32().

3. output can be produced by 3 methods as listed above

3. we can include escape sequences like \t, \n, etc., in output as above

No comments:

Post a Comment