Friday 17 August 2018

C#: Read input from console

‘Console’ class provides ‘ReadLine’ method to read input from console. ReadLine method reads the information from console and return the input in string format.

String name = Console.ReadLine();

Program.cs
using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Welcome to C#, Please Enter Basic Informaiton");

        Console.WriteLine("Enter Your Name");
        String name = Console.ReadLine();

        Console.WriteLine("Enter Your Age");
        String age = Console.ReadLine();

        Console.WriteLine("Hello " + name + " You are " + age + " years old");

    }
}

Output
Welcome to C#, Please Enter Basic Informaiton
Enter Your Name
Hari krishna
Enter Your Age
26
Hello Hari krishna You are 26 years old


Place Holder Syntax
While concatenating the strings, place holder syntax is very convenient than using ‘+’ operator.

Following is the example of place holder syntax.

Console.WriteLine("Hello {0}. You are {1} years old", name, age);

Above statement is equivalent of following statement.

Console.WriteLine("Hello " + name + " You are " + age + " years old");

Program.cs
using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Welcome to C#, Please Enter Basic Informaiton");

        Console.WriteLine("Enter Your Name");
        String name = Console.ReadLine();

        Console.WriteLine("Enter Your Age");
        String age = Console.ReadLine();

        Console.WriteLine("Hello {0}", name);
        Console.WriteLine("You are {0} years old", age);

        Console.WriteLine("Hello {1}. You are {0} years old", name, age);

    }
}


Output
Welcome to C#, Please Enter Basic Informaiton
Enter Your Name
Hari Krishna
Enter Your Age
26
Hello Hari Krishna
You are 26 years old
Hello 26. You are Hari Krishna years old
Press any key to continue . . .





Previous                                                 Next                                                 Home

No comments:

Post a Comment