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
defaultis 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:
defaultfor a reference type isnull, for a struct it is the all-zero value, and for a nullable value type it isnull defaultanddefault(T)compile to identical code, so this is purely a readability change with no runtime cost- In a nullable reference types context
defaultfor a non-nullable reference type produces the same CS8600 warning as assigningnulldirectly, so it offers no protection - prefer an explicit initializer - Common in generic code and in
switchexpressions 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