Skip to content

Default literals C# 7.1code reduction

Use `default` without specifying the type explicitly.

As part of the push to eliminate unnecessary duplication of type specification the default keyword used to initialize reference types to null, numeric types to 0 and booleans to false can now have the type omitted provided the compiler can definitively determine which type it must be.

Code ​

csharp
static T LoadValues<T>(int index)
{
    if (index < 0) return default;
    // ...
}
csharp
static T LoadValues<T>(int index)
{
    if (index < 0) return default(T);
    // ...
}

Notes ​

  • The type is the target type, so default is only valid where the compiler can infer it; var x = default; is an error because there is no target
  • Works for any type, not just the primitives: default for a reference type is null, for a struct it is the all-zero value, and for a nullable value type it is null
  • default and default(T) compile to identical code, so this is purely a readability change with no runtime cost
  • In a nullable reference types context default for a non-nullable reference type produces the same CS8600 warning as assigning null directly, so it offers no protection - prefer an explicit initializer
  • Common in generic code and in switch expressions where the default arm returns nothing useful
  • Target-typed new C# 9.0 brings the same type inference to new, creating an instance rather than a default value

More information ​

Powered by Intracia