Skip to content

Commit

Permalink
Fix Type.GetDefaultValue() for nullable value types
Browse files Browse the repository at this point in the history
  • Loading branch information
skrysmanski committed Jun 25, 2024
1 parent c69a3f7 commit 6252b87
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/AppMotor.Core/Extensions/TypeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ public static string GetCSharpName(this Type type, bool includeNamespaces = fals
{
if (type.IsValueType)
{
if (type.IsNullableValueType())
{
return null;
}

return RuntimeHelpers.GetUninitializedObject(type);
}
else
Expand Down
12 changes: 12 additions & 0 deletions tests/AppMotor.Core.Tests/Tests/Extensions/TypeExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,18 @@ public void Test_GetDefaultValue()
typeof(bool).GetDefaultValue().ShouldBe(false);
}

[Fact]
public void Test_GetDefaultValue_NullableValueTypes()
{
// Verify assumptions
default(bool?).ShouldBe(null);
default(int?).ShouldBe(null);

// Tests
typeof(bool?).GetDefaultValue().ShouldBe(null);
typeof(int?).GetDefaultValue().ShouldBe(null);
}

/// <summary>
/// Tests that mutating the default value of a mutable struct doesn't mutate the default value itself.
/// This version works with regular C# (where such a thing isn't possible - see <see cref="Test_GetDefaultValue_MutableStruct_Reflection"/>).
Expand Down

0 comments on commit 6252b87

Please sign in to comment.