C# Reference ยท Operators and Expressions
The default operator and literal
Reference for the C# default operator and default literal: the zero value of any type, default in generics, optional parameters and struct initialization.
default(T) produces the default value of type T: zero for numbers, false for bool, '\0' for char, null for reference types and nullable value types, and a struct with all fields set to their defaults. Since C# 7.1 you can drop the type when the compiler can infer it: int x = default;.
It is most important in generic code, where you do not know whether T is a class or a struct and cannot write null or 0.
int n = default; // 0 string? s = default; // null var p = default(DateTime); // 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) // default operator default // default literal, type inferred (C# 7.1)
| Name | Description |
|---|---|
type |
Any type, including type parameters. |
Returns: the all-bits-zero value of the type. For a reference type or Nullable<T> that means null.
Errors: the literal needs a known target type. var x = default; fails because there is nothing to infer from.
Usage notes
- Do not confuse
default(T)withnew T(). For a struct with a parameterless constructor you declared (C# 10+),new T()runs it butdefault(T)never does. defaultalso appears inswitchas the fallback label and as a pattern-less branch inswitchexpressions as_. Those are a different use of the same word.- With nullable reference types,
default(string)has typestringbut holdsnull, and the compiler warns when you assign it to a non-nullable variable. Declare the variable asstring?. - In a generic method,
default(T)isnullfor classes and zero-like for structs. UseT?as the return type so callers see that it may be missing. - For an array,
default(int[])isnull, not an empty array. Use[]orArray.Empty<int>()when you want empty. defaultworks as the default value of an optional parameter, asvalue = defaultdoes in the second example.- Comparing with
defaultthroughEqualityComparer<T>.Defaultavoids boxing for value types and works for anyT. - A struct's
defaultignores field initializers, because no constructor runs.