In C#, Console.SetIn replaces the TextReader behind standard input. Afterward, ReadLine, Read, and related calls read from your reader instead of the keyboard.
Common choices are StringReader for tests and StreamReader for files. Restore the original reader if the rest of the program still needs the keyboard.
This is a static member of System.Console. You call it with the type name, such as Console.SetIn(...). Console is the everyday API for reading from standard input and writing to standard output in C# console apps.
Syntax
Pass any TextReader. Remember to dispose file readers when finished.
C#
Console.SetIn(new StringReader("Ada\\n"));
string name = Console.ReadLine();
Call
What it does
Console.SetIn(reader)
Makes Console input methods use that TextReader.
SetOut and SetError redirect output streams the same way.
Library declarations
C#
public static void SetIn(TextReader newIn);
Parameters
Parameter
Description
newIn
Required. The TextReader that becomes standard input.
Return Value
Return Value
Description
void
Input is redirected; nothing is returned.
C# Examples
Example 1 — Feed ReadLine From a String
Simulate typed input without a keyboard.
C#
using System;
using System.IO;
class Program {
static void Main() {
Console.SetIn(new StringReader("Ada"));
string? name = Console.ReadLine();
Console.WriteLine("Hello, " + name);
}
}
Output
Hello, Ada
How It Works
Fake keyboard. StringReader supplies the line Ada.
SetIn. Points Console input at that reader.
ReadLine works. Same API as interactive input.
Great for demos. Output stays deterministic.
Example 2 — Provide Multiple Lines of Input
Stack lines with newlines inside the string.
C#
using System;
using System.IO;
class Program {
static void Main() {
Console.SetIn(new StringReader("3\\n4\\n"));
int a = int.Parse(Console.ReadLine()!);
int b = int.Parse(Console.ReadLine()!);
Console.WriteLine("sum=" + (a + b));
}
}
Output
sum=7
How It Works
Two ReadLine calls. Each consumes one line from the reader.
Parse ints. Convert text lines to numbers.
sum 7. 3 + 4 printed after both lines are read.
Deterministic test. No human typing required.
Example 3 — See null When the Reader Ends
Call ReadLine after the content is exhausted.
C#
using System;
using System.IO;
class Program {
static void Main() {
Console.SetIn(new StringReader("only"));
Console.WriteLine(Console.ReadLine());
string? again = Console.ReadLine();
Console.WriteLine(again == null ? "EOF null" : again);
}
}
Output
only
EOF null
How It Works
First line. Returns only.
Second call. Reader is empty β null.
Null means EOF. Same rule as end of redirected input.
Check before use. Do not assume another string arrives.
Frequently Asked Questions
The TextReader used by Console.Read, ReadLine, and In.
Yes. Pass a StreamReader opened on the file.
StringReader lets tests supply input without a keyboard.