C# User Input: Read, Validate, and Use Answers Safely
Console.ReadLine reads a line of text, not a guaranteed valid answer. Ask clearly, handle missing or blank input, check numeric parsing, and enforce the allowed range before using a value.
What you will understand
- Read one or more lines in order with Console.ReadLine.
- Use the website runner’s prepared standard input and explain how it differs from a terminal.
- Distinguish null, an empty line and whitespace-only text.
- Check a required name before trimming its surrounding whitespace.
- Use the TryParse success flag instead of mistaking failure for zero.
- Separate numeric representation checks from allowed-range rules.
- Test the happy path, missing input and boundary failures.
ReadLine gives you text, even when someone types a number
An input operation lets a person supply information while a program runs. Console.WriteLine sends a message out; Console.ReadLine takes one line in. Keep those directions separate. The method name does not tell C# what kind of answer you hoped to receive.
If someone types 12, ReadLine returns the text "12", not the integer 12. If someone types Mina Ali, it returns that complete line, including the space. You must decide later whether to keep the answer as text or interpret it as another type.
Before this lesson, review variables, data types and conversions. Here you will read a name, parse a quantity and reject invalid entries. You will also see a small preview of if and return so that each input check has an understandable outcome; the full decisions lessons come later.
Program.cs · Read one complete line
Predict the result, edit Program.cs, then run your program.
Standard input · prefilled example
Select Run code to compile and execute this program.
What is your name?
Hello, Mina!
ReadLine reads the next complete input line without its line-ending characters. The question is output; Mina is input. In this website runner the input is supplied before execution and is not echoed into the output. Change the input field to a different name and run again.
Supply all lines before Run in the website editor
In a terminal on your computer, ReadLine usually waits for you to type a line and press Enter. This website editor instead receives a prepared input stream. Expand Standard input, enter every required answer on its own line, and then select Run code. Each example below already includes suitable sample input.
The website sends those lines in order and then closes the stream. You cannot type a second answer into the output pane after the program starts. To try another answer, edit the input field and run the program again. Reset restores both the example code and its sample input.
The output pane does not echo the prepared input. That is why its transcript contains the program questions and final message but does not include separate lines showing what you typed. A local interactive terminal may echo your keystrokes, so its visible transcript can look different without changing the program logic.
Program.cs · Each read consumes the next line
Predict the result, edit Program.cs, then run your program.
Standard input · prefilled example
Select Run code to compile and execute this program.
First name?
Favorite language?
Mina is learning C#.
Two calls read two successive lines. A space inside Mina Ali does not split a ReadLine call into two values. The order matters: swapping the input lines changes which variable receives which answer. ReadLine consumes lines, not words or the entire input stream at once.
Missing input, an empty line and spaces are different states
ReadLine returns string? because there may be no more input to read. null means no line was available. An empty string means a line was available but contained no characters. A string of spaces contains characters even if it looks blank to a reader.
The experiment with two reads supplies one line, so the second result is null. A final newline terminates the first answer; it does not automatically create another empty answer. In the blank-line experiment, one newline is itself the complete empty first line. Remove all input and run again to see the difference.
For a required name, all three states can be unacceptable. string.IsNullOrWhiteSpace handles them together. For another field, an empty line might have a defined meaning, such as accepting a default. Choose that policy deliberately rather than treating every missing value as an empty or zero answer.
Program.cs · Recognize the end of supplied input
Predict the result, edit Program.cs, then run your program.
Standard input · prefilled example
Select Run code to compile and execute this program.
First: [Mina]
Second is null: True
The supplied stream has one line. The second read finds no more data and returns null. The is null expression asks whether a value is absent. A trailing line terminator completes the first line; it does not itself supply an additional blank line. Use a second newline if you intend to provide an empty second line.
Program.cs · Distinguish a blank line from no line
Predict the result, edit Program.cs, then run your program.
Standard input · prefilled example
Select Run code to compile and execute this program.
Is null: False
Is empty: True
Missing or whitespace: True
This input contains one blank line, so the result is an empty string rather than null. Clear all input to observe null instead. Supply spaces to get a nonempty string that still counts as whitespace. The three checks answer different questions; choose the one that matches the field requirement.
Validate a required name before cleaning its edges
Text validation asks whether an answer is meaningful for this field. A display name should contain something other than whitespace. Check that requirement before calling methods on a possibly absent string. The guard below gives a helpful message and ends this run if the requirement is not met.
An if statement runs its braced block when its condition is true. return stops this top-level program, so later lines do not run after the guard rejects the input. This creates a readable path: reject the invalid state early, then continue with the known valid state.
Trim returns text with surrounding whitespace removed. It does not remove the internal space in Mina Ali and does not alter the original string in place. Nor does it prove that a name is unique, verified or safe for every later use. Here it simply makes the accepted display value tidy.
Program.cs · Require a meaningful display name
Predict the result, edit Program.cs, then run your program.
Standard input · prefilled example
Select Run code to compile and execute this program.
Display name?
Welcome, Mina Ali.
The guard handles absent, empty and whitespace-only input before Trim is called. Trim removes surrounding whitespace and returns a new string; it preserves the space between Mina and Ali. return ends this top-level program early. This small if statement is a preview of the later decisions lesson.
Check whether numeric text can become a number
Use TryParse when malformed or missing numeric text is an ordinary possibility. Read its two results separately: the method returns a success flag, and out int quantity declares a variable receiving the numeric result. The method syntax will become familiar through use; you do not need to write your own methods yet.
The prefix ! means not. In if (!int.TryParse(...)), the block runs when parsing did not succeed. Invalid spelling, a fractional spelling for int and a number outside the int range fail this parse. Leading or trailing whitespace and an optional sign are accepted by this standard integer overload.
On failure, the result slot is zero. But "0" is valid integer text and also produces zero. Testing only the slot loses the distinction. Keep the Boolean result or put TryParse directly in a guard as shown. Do not use a null-forgiving suffix to pretend that input has been checked.
Program.cs · Use the success flag before the number
Predict the result, edit Program.cs, then run your program.
Standard input · prefilled example
Select Run code to compile and execute this program.
How many notebooks?
You entered: 3
TryParse returns true only when this text can be represented as an int. The out declaration receives its numeric result. The ! symbol means not, so the guard runs when parsing fails. Once that guard has finished without returning, quantity holds a successfully parsed integer. It is not yet checked against the allowed notebook quantity.
Program.cs · Zero is not a parsing-failure signal
Predict the result, edit Program.cs, then run your program.
Standard input · prefilled example
Select Run code to compile and execute this program.
Parsed: True
Quantity: 0
The valid spelling 0 succeeds and produces zero. An invalid spelling such as zero also writes zero into quantity, but returns false. Test both cases: the number alone cannot tell you whether parsing worked. Any rule forbidding a zero quantity belongs after the parse check.
Program.cs · See why assuming valid text fails
Predict the result, edit Program.cs, then run your program.
Standard input · prefilled example
Select Run code to compile and execute this program.
Quantity?
Then execution fails with FormatException.The null-forgiving ! after ReadLine suppresses a nullable warning; it does not validate, replace or parse missing data. Parse throws for the supplied invalid text before the final output. A null input would fail differently. This is an intentional failure to inspect, not the recommended input pattern.
A number that parses may still be forbidden
A representation check asks whether text can be read as an int. A domain check asks whether that int is allowed for the operation. Negative two parses successfully, but it is not an allowed notebook quantity when the rule is 1 through 20. Neither check replaces the other.
The second guard uses < and > to test the boundaries and || to join the two ways a quantity can be outside the range. Read it aloud: below one or above twenty. This is a small introduction to comparisons and logical operators; the next lesson examines expressions in more detail.
Test the exact endpoints as well as values on both sides. For the 1-to-20 rule, 1 and 20 should succeed; 0 and 21 should fail. A helpful rejection message tells the reader how to correct the answer. The program ends after one attempt here; retry loops belong to a later lesson.
Program.cs · Accept only a quantity from 1 to 20
Predict the result, edit Program.cs, then run your program.
Standard input · prefilled example
Select Run code to compile and execute this program.
Notebooks (1 to 20)?
Accepted quantity: 3
Parsing and allowed-range validation are separate guards. The || expression means or: below 1 or above 20 is outside the allowed range. A successfully parsed -2 still fails this domain rule. Only the final line represents accepted input. Printing it does not create an order or change inventory.
Follow the valid path and test every rejection path
A useful input flow has four stages: ask, read, validate and use. You may need more than one validation stage, such as checking presence, parsing a number and enforcing its allowed range. Only after the checks succeed should the program calculate a result or describe an answer as accepted.
Begin testing with a normal answer so you know the happy path works. Then supply an empty stream, a blank line, whitespace, invalid text, a value outside the numeric type and a value just outside the business range. These inputs are different causes of failure and may deserve different feedback.
Keep the example honest about its effects. Printing a request does not reserve stock, save a record or send a message. The exercises build a console-input boundary. They use one attempt and report the first failure; they do not yet implement interactive retries or persistence.
Guided repair: a failed parse is not an accepted zero
The program prints Accepted: 0 after the user enters three. It used TryParse but ignored one of its results. Repair the flow so invalid text receives a useful message and never appears as an accepted quantity.
Program.cs · Ignored parse failure becomes a misleading zero
Predict the result, edit Program.cs, then run your program.
Standard input · prefilled example
Select Run code to compile and execute this program.
Quantity?
Accepted: 0
The program does not crash, yet it labels a failed parse as accepted zero. Ignoring the Boolean result silently changes the meaning of the input. A program that runs without an exception can still be incorrect. Repair the decision, not the output label alone.
Repair checkpoints
- Run the broken version with three and explain where zero came from.
- Check the Boolean result of TryParse before using quantity.
- Use a guard to stop this run after the failure message.
- With 0, expect Parsed quantity: 0: zero is valid integer text.
- With -2, parsing still succeeds. Explain why a separate allowed-range rule may reject it.
Reveal the repair and explanation
Program.cs · Reject failure before reporting a quantity
Predict the result, edit Program.cs, then run your program.
Standard input · prefilled example
Select Run code to compile and execute this program.
Quantity?
Quantity must be a whole number.
The failure branch exits before any numeric quantity is reported. With valid text, execution reaches the success line. That line deliberately says Parsed rather than Accepted: this repair addresses parse success only, so negative integers and zero remain valid numeric representations until a separate domain rule is added.
Independent lab: validate a workshop-seat request
Build a workshop-seat request with two answers: a required name followed by a whole-number seat count from 1 to 6. Each invalid answer must produce helpful feedback instead of a misleading summary.
Acceptance checklist
- Ask for the name first and reject null, empty or whitespace-only names.
- Trim accepted names while preserving internal spaces.
- Ask for seats only after the name check succeeds.
- Use TryParse and reject noninteger or out-of-int-range text.
- Accept seat counts 1 through 6, including both endpoints.
- Print a request summary only after all checks succeed; do not claim to save a booking.
Program.cs · Workshop request starter
Predict the result, edit Program.cs, then run your program.
Standard input · prefilled example
Select Run code to compile and execute this program.
Your name?
Seats requested (1 to 6)?
Request: Mina, seats 2
The happy-path output looks plausible, but neither field is validated. Try a blank name, an invalid number and seven seats before editing. The task is to make the program distinguish meaningful text, successful parsing and the allowed range, not just reproduce this reference.
Show hints
- Start with the required-name guard and return before asking about seats if it fails.
- Keep parsing failure separate from a successfully parsed but disallowed seat count.
- Check below 1 or above 6 to reject both outside ranges.
Reveal the reference solution
Program.cs · Workshop request with three guards
Predict the result, edit Program.cs, then run your program.
Standard input · prefilled example
Select Run code to compile and execute this program.
Your name?
Seats requested (1 to 6)?
Request: Mina Ali, seats 2
The name guard runs before requesting seats. The parse guard runs before the range guard, and the final summary runs only after all checks succeed. The first failing check ends this run with useful feedback. This is a request summary, not a saved booking. A real application would validate again at its trusted boundary and handle availability separately.
Changed-input checks
- Mina with 1 seat and Mina with 6 seats must both succeed.
- 0 and 7 seats must report the allowed range and produce no request summary.
- two, 1.5 and 2147483648 must report a whole-number error.
- An empty stream or a whitespace-only name must stop before the seats question.
- A valid name with no second line must report a whole-number error without crashing.
- A name with surrounding spaces must be trimmed; internal spaces must remain.
Recap: follow the input checks in order
Ask clearly, read the expected line, check presence and numeric representation, and then enforce the field’s allowed range. Only use the value after the relevant checks have succeeded.
Console.WriteLine- Ask a question or explain the result; it does not read an answer.
Console.ReadLine()- Read the next line without its line ending, or receive null at end of input.
string?- Allow for a line that may be absent; the annotation itself does not validate it.
string.IsNullOrWhiteSpace(text)- Reject absent, empty or whitespace-only text when the field is required.
int.TryParse(text, out int value)- Check numeric representation and preserve the success result.
if (...) { ... return; }- Report a failing condition and end this run before the accepted-value path.
value < minimum || value > maximum- Reject values outside the inclusive range after a successful parse.
Frequently asked questions
Why does ReadLine return string?
The answer is a line of characters. Even digits are text until you parse them. The nullable annotation string? acknowledges that ReadLine can also return null at end of input.
Why can I not type into the website output after Run?
This runner sends the prepared Standard input field as a stream before execution and then ends it. Enter all answers on separate lines before running. A local terminal can instead accept answers as the program asks.
Is a blank line the same as null?
No. A blank line produces an empty string. null means there was no next line. Spaces produce a nonempty whitespace string. IsNullOrWhiteSpace can treat all three as invalid for a required field.
Should I use Console.Read instead?
Read reads a single character code, not a complete line, and returns an int with -1 at end of input. ReadLine is the appropriate starting point for these line-based answers. ReadKey is not suitable for the prepared input stream used here.
Does TryParse validate the allowed quantity?
It checks whether the text can be represented as the requested number type. A negative integer can parse successfully. Add a separate range check for the application rule.
Why does the program stop instead of asking again?
These examples deliberately handle one attempt and stop at the first failure. A later loop lesson adds retries. Re-run the website example with changed input to test another attempt.
Can you follow the input flow?
Distinguish text, missing input, parse success and allowed values. Read the explanation after submitting.
Next step and references
User input starts as text that may be absent. A good input flow checks what is present, interprets numeric text deliberately, and enforces domain rules before using the result. Test each failure path as well as the valid path.
Next is C# Operators and Expressions. You will trace arithmetic, comparisons and logical conditions, including the operators briefly introduced in these input guards.
Official references
Original SovranCode explanations, examples and exercises. Technical details were checked against these references.
- Microsoft Learn: Console.ReadLine
- Microsoft Learn: Int32.TryParse
- Microsoft Learn: String.IsNullOrWhiteSpace
- Microsoft Learn: Selection statements
Last updated: .