Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Console.Read() Method in C#
The Console.Read() method in C# reads a single character from the standard input stream and returns its ASCII value as an integer. Unlike Console.ReadLine() which reads entire lines, Console.Read() processes one character at a time.
Syntax
Following is the syntax for the Console.Read() method −
public static int Read();
Return Value
The method returns an int representing the ASCII value of the character read, or -1 if no more characters are available.
Using Console.Read() to Get Character ASCII Values
Example
using System;
public class Demo {
public static void Main() {
int val;
Console.WriteLine("Character '5' has ASCII value:");
// Simulate reading character '5'
char inputChar = '5';
val = (int)inputChar;
Console.WriteLine("ASCII value: " + val);
Console.WriteLine("Character: " + (char)val);
}
}
The output of the above code is −
Character '5' has ASCII value: ASCII value: 53 Character: 5
Reading Multiple Characters
Example
using System;
public class MultipleCharacters {
public static void Main() {
string testInput = "ABC";
Console.WriteLine("Processing characters from: " + testInput);
foreach (char c in testInput) {
int asciiValue = (int)c;
Console.WriteLine("Character: '" + c + "' ASCII: " + asciiValue);
}
}
}
The output of the above code is −
Processing characters from: ABC Character: 'A' ASCII: 65 Character: 'B' ASCII: 66 Character: 'C' ASCII: 67
Comparison with Other Console Methods
| Method | Return Type | What It Reads |
|---|---|---|
| Console.Read() | int | Single character as ASCII value |
| Console.ReadLine() | string | Entire line until Enter key |
| Console.ReadKey() | ConsoleKeyInfo | Single key press with metadata |
Converting ASCII to Character
Example
using System;
public class ASCIIConverter {
public static void Main() {
int[] asciiValues = {65, 66, 67, 97, 98, 99};
Console.WriteLine("ASCII to Character conversion:");
foreach (int ascii in asciiValues) {
char character = (char)ascii;
Console.WriteLine("ASCII " + ascii + " = '" + character + "'");
}
}
}
The output of the above code is −
ASCII to Character conversion: ASCII 65 = 'A' ASCII 66 = 'B' ASCII 67 = 'C' ASCII 97 = 'a' ASCII 98 = 'b' ASCII 99 = 'c'
Conclusion
The Console.Read() method reads a single character and returns its ASCII value as an integer. This method is useful for character-by-character processing and ASCII value manipulation, though it requires user interaction which limits its use in automated environments.
