C# Reference ยท Keywords and Statements
The default keyword
Reference for the C# default keyword: the default literal, default(T) for generics, default parameter values and the default label in switch statements.
default has three jobs. As an expression, default(T) or the shorter literal default produces the default value of a type: 0 for numbers, false for bool, '\0' for char, null for reference types and nullable value types, and a struct with every field set to its default. In a switch, default: is the label that matches when no case does. In an optional parameter, = default means "the default value of the parameter's type".
The expression form matters most in generic code, where you do not know whether T is a class or a struct and still need a "nothing yet" value.
int n = default; // 0 string? s = default; // null DateTime d = default; // 0001-01-01 00:00:00
Try it
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.
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.
Syntax
default(Type) // operator, any C# version default // literal, C# 7.1+, type inferred from context default: // switch statement label parameter = default // optional parameter
| Form | Meaning |
|---|---|
default(T) |
The default value of T, written with an explicit type. |
default literal |
Same, but the compiler infers T from the target (assignment, argument, return type, ?: branch). |
default: |
The fall-back label of a switch statement. A switch expression uses the discard _ instead. |
Returns: the all-zero-bits value of T. Errors: var x = default; fails with CS8716 because there is no target type to infer.
Usage notes
- For reference types and nullable value types
defaultisnull, sodefault(string)isnull, not"". - For a struct,
defaultskips constructors and field initializers. An all-zero instance may be invalid for your domain (for example aMoneywhose currency isnull). Design structs so the zero value is meaningful, or check for it. - With nullable reference types enabled,
T? Method<T>()returningdefaultis the idiom for "no value". Use[MaybeNull]orT?so callers get a warning if they ignore it. - In generic code,
x == defaultis not allowed for an unconstrainedT. UseEqualityComparer<T>.Default.Equals(x, default)orx is nullchecks. defaultin aswitchstatement can appear anywhere, but it is evaluated last. Aswitchexpression with no matching arm throwsSwitchExpressionException.- A
defaultliteral in?:needs the other branch to give a type:flag ? 1 : defaultworks,flag ? default : defaultdoes not. - The
defaultpointer ordefault(T)of aref structis also allowed.