Since C# 7.1, it is possible to get default values by using default
without specifying the type. I tried it out today and found the results for nullable structs and nullable value types somewhat counterintuitive.
[TestFixture]
public class Test
{
private class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
[Test]
public void ShouldBehaveAsExpected()
{
var person1 = new Person {Name = "John", Age = 58};
var person2 = new Person {Name = "Tina", Age = 27};
var persons = new[] {person1, person2};
int? myAge = persons.FirstOrDefault(p => p.Name == "MyName")?.Age;
var myDefaultAge = myAge ?? default;
var myAgeString = myAge == null ? "null" : myAge.ToString();
var myDefaultAgeString = myDefaultAge == null ? "null" : myDefaultAge.ToString();
Console.WriteLine("myAge: " + myAgeString); // "myAge: null"
Console.WriteLine("myDefaultAge: " + myDefaultAgeString); // "myDefaultAge: 0"
}
}
I would have expected myDefaultAge
to be null
rather than 0
, because myAge is of type int?
and default(int?)
is null
.
Is this behaviour specified anywhere? The C# programming guide only says that " The default literal produces the same value as the equivalent default(T) where T is the inferred type."