Different Methods to Read a Character in C#

Read a character in C#: Here, we are going to learn how to read a character by using different methods in C#?
By IncludeHelp Last updated : April 06, 2023

As we know that, Console.ReadLine() is used for input in C#, it actually reads a string and then we convert or parse it to targeted type.

In this tutorial, we will learn how to read a character in C#?

Methods to read/input single character in C#

Following methods can be used to read a character:

  1. Using Console.ReadLine()[0]
  2. Using Console.ReadKey().KeyChar
  3. Using Char.TryParse()
  4. Using Convert.ToChar()

1) Character input using Console.ReadLine()[0]

It's very simple, as we know that Console.ReadLine() reads a string and string is the set of characters. So we can use this method and extract its first character using 0th Index ([0]). In this case, we can input a single character and string also – it will return only first character.

Syntax:

    char_variable = Console.ReadLine()[0];

Example: C# code to Read a character using Console.ReadLine()[0]

// C# program to input character
// using Console.ReadLine()[0]
using System;
using System.IO;
using System.Text;

namespace IncludeHelp
{
    class Test
    {
        // Main Method 
        static void Main(string[] args)
        {
            char ch;
            
            //input character 
            Console.Write("Enter a character: ");
            ch = Console.ReadLine()[0];
         
            //printing the input character
            Console.WriteLine("Input character is {0}", ch);

            //hit ENTER to exit the program
            Console.ReadLine();
        }
    }
}

Output

First run:
Enter a character: H
Input character is H

Second run:
Enter a character: Hello world
Input character is H

2) Character input using Console.ReadKey().KeyChar

We can also use Console.ReadKey() method to read a key and then to get the character, use KeyChar.

Console.ReadKey() – is used to obtain the next character or function key pressed by the user. The pressed key will display on the console.

KeyChar returns the Unicode character represented by the current System.ConsoleKeyInfo object.

Note: In other words, please understand – it reads a function key (a character also), displays on the console, but don't wait to press return key (i.e. ENTER).

Syntax:

    char_variable = Console.ReadKey().KeyChar;

Example: C# code to Read a character using Console.ReadKey().KeyChar

// C# program to input a character 
// using Console.ReadKey().KeyChar
using System;
using System.IO;
using System.Text;

namespace IncludeHelp
{
    class Test
    {
        // Main Method 
        static void Main(string[] args)
        {
            char ch;
            
            //input character 
            Console.Write("Enter a character: ");
            ch = Console.ReadKey().KeyChar;
         
            //printing the input character
            Console.WriteLine("Input character is {0}", ch);

            //hit ENTER to exit the program
            Console.ReadLine();
        }
    }
}

Output

Enter a character: HInput character is H

3) Character input using Char.TryParse(string, out)

Char.TryParse() method is the perfect method to read a character as it also handles the exception i.e. if an input value is not a character it will not throw any error. It returns an input status also if character input is valid – it returns true, else it returns false.

Syntax:

    bool result = Char.TryParse(String s, out char char_variable);

It stores the result in char_variable and returns a Boolean value.

Example: C# code to Read a character using Char.TryParse()

// C# program to input a character
// using Char.TryParse() 
using System;
using System.IO;
using System.Text;

namespace IncludeHelp
{
    class Test
    {
        // Main Method 
        static void Main(string[] args)
        {
            char ch;
            bool result;
            
            //input character 
            Console.Write("Enter a character: ");
            result = Char.TryParse(Console.ReadLine(), out ch);
         
            //printing the input character
            Console.WriteLine("result is: {0}", result);
            Console.WriteLine("Input character is {0}", ch);

            //hit ENTER to exit the program
            Console.ReadLine();
        }
    }
}

Output

First run:
Enter a character: A
result is: True
Input character is A

Second run:
Enter a character: Hello world
result is: False
Input character is

4) Character input using Convert.ToChar()

Convert.ToChar() method converts the specified string's value to the character.

Note: Input value must be a single character if you input a string – it will throw an exception "String must be exactly one character long".

Syntax:

    char_variable = Convert.ToChar(string s);

Example: C# code to Read a character using Convert.ToChar()

// C# program to input a character
// using Convert.ToChar()
using System;
using System.IO;
using System.Text;

namespace IncludeHelp
{
    class Test
    {
        // Main Method 
        static void Main(string[] args)
        {
            char ch;
            
            //input character 
            Console.Write("Enter a character: ");
            ch = Convert.ToChar(Console.ReadLine());
         
            //printing the input character
            Console.WriteLine("Input character is {0}", ch);

            //hit ENTER to exit the program
            Console.ReadLine();
        }
    }
}

Output

First run:
Enter a character: H
Input character is H

Second run: 
Enter a character: Hello world
Exception throws...




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.