Different Methods to Read a Character in C#
In C#, there are several methods to read a single character from the standard input. Let’s see them:
Console.ReadLine()[0]Method:
- The
Console.ReadLine()method reads a string from the input, and since a string is a sequence of characters, you can extract the first character using the 0th index.
Example
using System;
namespace dm
{
class Program
{
static void Main(string[] args)
{
char chr = Console.ReadLine()[0];
Console.WriteLine(chr);
Console.ReadLine();
}
}
}
Input: “Geeks” Output: “G”.
2.console.ReadKey().KeyChar Method:
- The
Console.ReadKey()method obtains the next character or function key pressed by the user. TheKeyCharproperty returns the Unicode character represented by the currentSystem.ConsoleKeyInfoobject. - It reads a character without waiting for the Enter key to be pressed.
- Example
char chr = Console.ReadKey().KeyChar; Console.WriteLine(chr);
Input: “G” Output: “G”.
3.
Char.TryParse()Method:- The
Char.TryParse()method reads a character and handles exceptions. It returnstruefor valid characters andfalsefor invalid ones. - Example
char chr; bool valid = Char.TryParse(Console.ReadLine(), out chr); Console.WriteLine("Result: " + valid); Console.WriteLine("Input character: " + chr);Input: “G” Output: “Result: True” and “Input character: G”
4.
Convert.ToChar()Method:- The
Convert.ToChar()method converts a specified string value to a character. The string must be of length 1. - Example
char chr = Convert.ToChar(Console.ReadLine()); Console.WriteLine(chr);
Input: “G” Output: “G”
- The
- The