Skip to content
Tutorials Center
My learning

Topics

Lesson 89 of 182 ยท Null Safety and Errors

Validating Input and Defensive Programming

Learn how to validate arguments, guard preconditions, use Debug.Assert, DataAnnotations and invariants, and fail fast so bugs in C# programs are caught early and clearly.

Every method makes assumptions. A Divide method assumes the divisor is not zero. A Withdraw method assumes the amount is positive and the balance is large enough. A Parse method assumes the text looks like a number. When an assumption is false, one of two things happens: the program notices immediately and says exactly what went wrong, or it carries on with bad data and fails somewhere else, later, in a way that is very hard to trace.

Defensive programming is the habit of checking assumptions at the boundaries of your code so that bad data is stopped at the door. This lesson shows what to check, where to check it, which tool to use (exceptions, TryParse, Debug.Assert, DataAnnotations) and how to design classes so that they cannot be put into an invalid state. It builds on exceptions, custom exceptions and nullable reference types.

Two kinds of bad input

Not all bad input is the same, and the right reaction differs.

  • Caller bugs. Another developer passes null to a parameter that must not be null, or a negative count. This is a programming error; the right response is to throw an exception right away, with a message that names the parameter.
  • Expected bad data. A user types "abc" where a number is expected, or a file contains a malformed line. This is not a bug; it happens every day. The right response is to report it politely, usually without exceptions: with TryParse, a validation result or an error message.

A rule of thumb: exceptions for "this should never happen if the caller is correct", return values for "this happens regularly".

Guard clauses

A guard clause is a check at the top of a method that rejects invalid arguments before any real work starts. The method body below the guards can then rely on valid data and stays free of nesting.

.NET provides helper methods for the common checks, so you do not have to write if (x is null) throw ... by hand. Each one throws the right exception type and automatically captures the argument's name through CallerArgumentExpression.

C# Guard clauses with ThrowIf helpers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Other helpers worth knowing: ArgumentOutOfRangeException.ThrowIfZero, ThrowIfNegativeOrZero, ThrowIfGreaterThan, ThrowIfLessThanOrEqual, ThrowIfEqual, ThrowIfNotEqual and ArgumentException.ThrowIfNullOrEmpty. The parameter name in the message is filled in for you, which stops the classic mistake of a stale nameof(...) after a rename.

Which exception type?

Problem Throw
Argument is null ArgumentNullException
Argument has a legal type but an illegal value (empty string, wrong format) ArgumentException
Number outside the allowed range ArgumentOutOfRangeException
The object is in the wrong state for this call InvalidOperationException
The object has been disposed ObjectDisposedException
The operation is not supported at all NotSupportedException

The distinction between argument exceptions and InvalidOperationException matters: the first says "your input is wrong", the second says "your input is fine but you called me at the wrong time" (for example calling Withdraw on a closed account).

Validate early, validate once

Put validation where data enters your system: the public methods of a library, the constructor of a type, the controller of a web app, the code that reads a file or the console. Inside private helpers that only receive already-validated data, repeated checks are noise.

This is the same idea as fail fast: detect the problem at the first possible moment, close to its cause. A negative quantity that is rejected when the order is created points directly at the bad caller. The same quantity discovered three layers later, while computing a total, tells you nothing about who produced it.

Parsing user input without exceptions

Exceptions are expensive and expected bad data is routine, so for text from people use the TryParse pattern: it returns bool and gives you the value through an out parameter. (Reading console input itself is covered in Reading Input.)

C# Validating text input with TryParse

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The method reports why the value failed, not only that it failed, so the UI can show a helpful message. A common refinement is to return a small result object instead of using two out parameters; the lesson on exception filters and error handling patterns shows a reusable Result type.

Making invalid states unrepresentable

The strongest defense is a type that cannot hold bad data at all. If every way of building an EmailAddress goes through a check, then every EmailAddress anywhere in your program is known to be valid, and no other method needs to re-check it.

C# A value object that validates in its constructor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Two techniques work together here. The constructor guards stop invalid objects from existing, and the immutable properties (get-only) mean the state cannot be broken later. OrderLine does not need to re-check the discount because a Percentage is valid by construction. One caveat: default(Percentage) still gives 0%, which happens to be valid; if the all-zeros value were invalid, a struct would be the wrong choice.

Invariants

An invariant is a condition that must hold for an object at all times when no method is running. "Balance is never negative", "start date is before end date", "the list is always sorted". You establish the invariant in the constructor and each public method must preserve it, so you check on entry and refuse any change that would break it.

C# Protecting an invariant

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The state check comes before the change. If we subtracted first and then noticed the balance was negative, the object would already be corrupted. Validate, then mutate: the failed Withdraw leaves the balance untouched.

Debug.Assert: checking your own assumptions

Guard clauses check what callers give you. Debug.Assert(condition, message) checks what you believe is true inside your own code: "after this loop, index must be in range". It is a note to future maintainers that also fails loudly if the belief turns out wrong.

The key property is that Debug.Assert is marked [Conditional("DEBUG")]: in a Release build the compiler removes the call completely, so it costs nothing in production. The consequences:

  • Use it for conditions that indicate a bug in your code, never for validating external input (it would vanish in Release).
  • Never put side effects in the condition, because the whole expression disappears: Debug.Assert(queue.TryDequeue(out _)) removes an item only in debug builds.
  • In a console app a failed assert terminates the program in debug builds (older frameworks showed a dialog), which is what you want while developing.

Our online runner compiles in Release mode, so asserts are skipped. The next example shows that by counting how many times an assertion condition was evaluated.

C# Debug.Assert is removed in Release builds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

If you want a check that is also kept in Release, throw an exception (InvalidOperationException or a guard helper). Some teams add a tiny Contract.Requires-style helper for internal bugs; the built-in Debug.Assert plus normal exceptions is enough for most projects.

Validation with DataAnnotations

When an object has many fields with simple rules, writing if statements for each becomes tedious. DataAnnotations let you declare the rules as attributes and validate the whole object in one call. The attributes live in System.ComponentModel.DataAnnotations, which is part of the base class library, so it runs here without extra packages. ASP.NET Core uses the same attributes to validate request bodies, so what you learn carries over to the ASP.NET Core chapter.

C# Declaring rules with DataAnnotations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Two details trip people up. First, validateAllProperties: true is required to check attributes other than [Required]; without it only required properties are examined. Second, nothing validates automatically: the attributes are only metadata until some code, here Validator, or later ASP.NET Core, reads them.

For rules that involve several properties, implement IValidatableObject and add a Validate method that yields ValidationResult objects, or write your own ValidationAttribute.

C# Cross-field rules with IValidatableObject

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The class-level rule runs only after the property-level attributes pass, which is why you see just one message here: Guests = 3 is in range, so the cross-field check gets its turn.

Fail fast, but fail clearly

When validation fails, how you report it decides how fast someone fixes the problem. Good error messages:

  • name the thing that was wrong (parameter, field, file line);
  • include the actual value where it is safe to do so (but never passwords or personal data);
  • state the rule ("must be between 1 and 4");
  • avoid blaming the user in UI text, and avoid leaking internals in messages shown to end users.

Also remember what not to do:

  • Do not swallow errors. An empty catch { } hides bugs and turns defensive code into silent corruption.
  • Do not validate with catch-all control flow. Parse with TryParse instead of catching FormatException on every bad keystroke.
  • Do not trust client-side checks. In web programs the browser can be bypassed, so validate again on the server.
  • Do not over-defend. Checking every parameter of every private method makes code unreadable. Validate at the boundaries and trust inside.

Nullable reference types are validation done by the compiler. If a parameter is declared string name (non-nullable), callers get a warning when they pass a possible null. You still add ArgumentNullException.ThrowIfNull in public APIs because the compiler warning can be ignored or the caller may use older code, but inside your own project you can usually trust the annotations.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A caller passes a negative quantity to your public method. What is the best reaction?

    A negative quantity is a caller bug, so fail fast with a clear exception. Silently fixing or ignoring the input hides the problem and spreads bad data.
  2. 2. Why should you not use Debug.Assert to validate user input?

    Debug.Assert has the Conditional(DEBUG) attribute, so the compiler removes it in Release. It is for checking your own assumptions, never for external input.
  3. 3. For text typed by a user, which approach is preferred for parsing a number?

    Bad user input is routine, not exceptional. TryParse avoids the cost and noise of exceptions and lets you explain the problem.
  4. 4. Which line of a DataAnnotations validation call is needed so that attributes like Range are checked, not only Required?

    With validateAllProperties set to false only [Required] properties are validated. Passing true checks every validation attribute.
  5. 5. What is an invariant?

    Invariants are established by the constructor and preserved by every public method. Validate before you change state so a rejected call leaves the object intact.

Summary

  • Separate caller bugs (throw exceptions) from expected bad data (return results or use TryParse).
  • Use guard clauses at the top of public methods; the ThrowIfNull, ThrowIfNegative and related helpers throw the right type and fill in the parameter name.
  • Validate at the boundaries, then trust inside. Fail fast so the error points at its cause.
  • Make invalid states unrepresentable: validate in constructors, keep objects immutable and check before you mutate to protect invariants.
  • Debug.Assert documents and tests your own assumptions in Debug builds only; never use it for input validation or with side effects.
  • DataAnnotations declare simple rules as attributes (Required, Range, StringLength, EmailAddress), and IValidatableObject handles cross-field rules.
  • Write error messages that name the problem, the rule and (when safe) the value; never swallow exceptions.

Next: Pattern Matching in Depth