Reading string from user input in C#

C# reading string: Here, we are going to learn how to take input (read a string) from the user in C#.Net?
By IncludeHelp Last updated : April 06, 2023

Reading string as input

To read a string from the user in C#, we use ReadLine() method of Console class.


    public static string Console.ReadLine();

Here, we don't pass any parameter and this method returns a string (a next line of the characters) from the input stream or returns null if there is no line of characters in the input stream.

The method ReadLine() may returns following exceptions,

  • IOException: If there is an input/output exception is occurred.
  • OutOfMemoryException: If there is no sufficient memory to store the user input.
  • ArgumentOutOfRangeException: If the string length if the more than the allowed number of characters (MaxValue).

C# example to read string from the user input

using System;

class IncludeHelp {
  static void Main() {
    // declaring string variables
    String first_name = "";
    String last_name = "";

    // input the strings
    Console.Write("Enter first name: ");
    first_name = Console.ReadLine();
    Console.Write("Enter last name : ");
    last_name = Console.ReadLine();

    // printing the values
    Console.WriteLine("Your name is: " + first_name + " " + last_name);


Enter first name: Shivang
Enter last name : Yadav
Your name is: Shivang Yadav

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.