Working with User Input in C#: Basic to Advanced

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

The C# programming language provides excellent support for working with input and output. This programming tutorial talks about how we can work with user input in C# with relevant code examples.

Looking to learn how to program in C# in an online setting? We have a list of the Best Online Courses to Learn C# to help you get started.

The Console Class in C#

In C#, the Console class provides a set of static methods that allow developers to read from – and write to – the console. Programmers can use these methods to get input from the user and use it in our programs. The class can be used to read input from the console, such as keyboard input or text input from a file. It can also be used to write output to the console, such as text output or formatted table data.

The ReadLine Method in C#

The ReadLine() method in C# can be used to read a line of text from the standard input stream, which includes the keyboard. If you wish to read individual characters from the input stream, you may also use the Read() method. It returns an int that represents the next character in the stream.

In this section we will examine example code showing how we can work with user input using the ReadLine method of the Console class in C#:

Console.WriteLine("Please enter your name:"); 
string name = Console.ReadLine(); 
Console.WriteLine("Hello, {0}!", name);

The above code, when executed, will display a prompt asking the user for their name, then read the name that they enter and store it in a variable. Finally, it will display a greeting message using the name entered.

Here is another example that shows how you can read first name and last name from the keyboard and display the full name in the console window:

Console.Write("Enter First Name:");
string firstName = Console.ReadLine();
Console.Write("Enter Last Name:");
string lastName = Console.ReadLine();
Console.WriteLine($"The name is : {firstName} {lastName}");

You can also use the Console class to get numeric input from the user. The following code example illustrates how you can retrieve numeric user input in C#:

Console.WriteLine("Please enter a number:"); 
int n = Convert.ToInt32(Console.ReadLine()); 

This code will prompt the user to enter a number, then convert the input into an integer value and store it in a variable called n.

The Read() and ReadKey() Methods in C#

The Read() and ReadKey() methods are used to read input from the user in C#. Using the Read() method, developers can read a character from the standard input stream, while using the ReadKey() method, you can read a keystroke from the console.

The Read() method returns an int value that represents the character code of the character that was read. On the flip side, the ReadKey() method reads the next character entered by the user. It returns a ConsoleKeyInfo object that contains information about the keystroke that was read, including the key code and whether or not the shift, alt, or control keys were pressed.

To use either of these methods, you must first import the System namespace into your program. You can do this by adding a using statement at the top of your program:

using System;

Once you have imported the System namespace, you can call either the Read() or ReadKey() method from anywhere in your code. For example, the following code will read a single character from the user and store it in a variable named c:

char c = (char)Console.Read();

Read: C# Tools for Code Quality

Using the Convert Class in C#

When working with user input in C#, it is important to first read the input and then convert it to the appropriate data type using the methods of the Convert class. You could use the following code in order to convert a string into an integer:

int n = Convert.ToInt32(Console.ReadLine());

You can also use the TryParse method to convert an input represented as a string to another data type. This is helpful if you are not sure if the string can be converted to the desired data type. For example, the following code will attempt to convert a string to an int and return true or false depending on whether or not the conversion was successful:

int n;
bool success = Int32.TryParse(Console.ReadLine(), out n);

Reading Numerical Values in C#

C# provides a number of ways to read numerical values from user input. The simplest way is to use the Convert class, which provides methods for converting various data types to and from numeric values.

The TryParse method in C# can be used to convert a string to an integer, float, double, etc. The method accepts two parameters: the string to be converted and a variable to store the result in. If the conversion fails, TryParse returns false. Otherwise, it returns true and stores the converted value in the specified variable.

The Parse method can also be used to convert a string to a number, as shown in the following code example:

int result = Int32.Parse(input);

This method works similarly to TryParse, but it throws an exception if the conversion fails instead of returning false.

If you need more control over how a string is converted to a number, you can use the NumberStyles and CultureInfo parameters of the Parse and TryParse methods. These parameters let you specify things like whether leading and trailing whitespace should be ignored, whether decimal points are allowed, and what culture’s formatting rules should be used.

The following code example illustrates how you can accept integer and double values and then display them at the console window in C#:

Console.Write("Enter an integer: ");
int i = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("You entered {0}", i);
Console.Write("Enter a double: ");
double d = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("You entered {0}", d);

The WriteLine() and Write() Methods in C#

The WriteLine() method outputs a line of text to the console, followed by a newline character. The Write() method outputs a line of text to the console without adding a newline character. This means that if you use Write() to output multiple lines of text, the entire text will be printed on a single line.

Printing Variables and Literals in C#

The Console class provides static the methods WriteLine() and Write() for printing variables and literals to the standard output stream. The following code shows how to use the WriteLine() and Write() methods in C#:

int i = 10;
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name);

The WriteLine() method prints the given object to the standard output stream and appends a newline character (\n) at the end. The Write() method prints the given object to the standard output stream without adding a newline character at the end. Thus, when using Write(), programmers need to explicitly add a newline character (\n) if we want to start printing on a new line.

Read: Project Management Software for .NET Developers

How to Display Formatted Strings and Placeholders in C#

Programmers can use placeholders {0}, {1}, …, {9} to specify where objects need to be printed. The object corresponding to placeholder {0}, for instance, is printed first and then so on for the other placeholders:

Console.WriteLine("{0} + {1} = {2}", 2, 3, 2+3); // Displays "2 + 3 = 5"
Console.WriteLine("{0} * {1} = {2}", 2, 3, 2*3); // Displays "2 * 3 = 6"

How to Display Formatted Strings with Alignment and Padding Specifiers

You can also align the generated output. The padding specifier is used to indicate the minimum number of characters to be displayed. If the object does not have enough characters to fill up the minimum characters required by the padding specifier, it is padded with spaces (or some other character).

The following piece of C# code illustrates how you can display integers with a display width of 5:

Console.WriteLine("{0,5}", 1);
Console.WriteLine("{0,5}", 12);
Console.WriteLine("{0,5}", 123);
Console.WriteLine("{0,5}", 1234);
Console.WriteLine("{0,5}", 12345);

When you execute the above piece of code, here’ i how the integers will be displayed at the console.

C# Input Code Examples

Final Thoughts on C# User Input

Input and output are the two most essential features in any application. Note that the input data can come from any compatible input device such as a keyboard, mouse, etc. Likewise, output data can be sent to any compatible output device such as the console, printer, etc.

Read more C# programming tutorials and software development guides.

Joydip Kanjilal
Joydip Kanjilal
A Microsoft Most Valuable Professional in ASP.NET, Speaker, and Author of several books and articles. More than 25 years of experience in IT with more than 18 years in Microsoft .NET and its related technologies. He was selected as a Community Credit Winner at several times. He has authored 8 books and more than 500 articles in some of the most reputed sites worldwide including MSDN, Info World, CodeMag, Tech Beacon, Tech Target, Developer, CodeGuru, and more.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read