Skip to content
Tutorials Center
My learning

Topics

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.

C#
int n = default;            // 0
string? s = default;        // null
var p = default(DateTime);  // 0001-01-01 00:00:00

Try it

C# Defaults of common types

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.

C# default in generic code and parameters

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

C#
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) with new T(). For a struct with a parameterless constructor you declared (C# 10+), new T() runs it but default(T) never does.
  • default also appears in switch as the fallback label and as a pattern-less branch in switch expressions as _. Those are a different use of the same word.
  • With nullable reference types, default(string) has type string but holds null, and the compiler warns when you assign it to a non-nullable variable. Declare the variable as string?.
  • In a generic method, default(T) is null for classes and zero-like for structs. Use T? as the return type so callers see that it may be missing.
  • For an array, default(int[]) is null, not an empty array. Use [] or Array.Empty<int>() when you want empty.
  • default works as the default value of an optional parameter, as value = default does in the second example.
  • Comparing with default through EqualityComparer<T>.Default avoids boxing for value types and works for any T.
  • A struct's default ignores field initializers, because no constructor runs.