The post default value expressions (C# programming guide) by microsoft explains the usage and behaviour of default(T)
. The behaviour was (and still is) as follows:
var x = default(uint?);
Assert.IsNull(x); // ok
uint? y = default;
Assert.IsNull(y); // ok
The post then continues and explains the usage and behaviour of default
( default literal and type inference ) which was introduced in C# 7.1. Before C# 7.1 we did:
void BeforeCsharp7_1(uint? z = default(uint?))
{
Assert.IsNull(z); // ok
}
With C# 7.1 we can do:
void WithCsharp7_1(uint? z = default)
{
Assert.IsNull(z); // Fail, expected null but was 0
}
You might be surprised to read that the last snipped will not assert because the parameter z
equals 0
. After upgrading my project to C# 7.1 Visual Studio kept telling me that default(uint?)
could be simplified to default
which then results in this very different behaviour. This must be a bug in Visual Studio.
Is this also a bug in the C# Specification / Roslyn or is this by design?
This was a bug in Roslyn which has now been fixed in VS15.5 / .NET Core SDK 2.1.200 and above. Yes, the default literal should indeed return null
for nullable value types.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.