From 6252b87c1a6b9d63c9868a2535cd9ae181f9bafc Mon Sep 17 00:00:00 2001 From: Sebastian Krysmanski Date: Tue, 25 Jun 2024 10:42:34 +0200 Subject: [PATCH] Fix Type.GetDefaultValue() for nullable value types --- src/AppMotor.Core/Extensions/TypeExtensions.cs | 5 +++++ .../Tests/Extensions/TypeExtensionsTests.cs | 12 ++++++++++++ 2 files changed, 17 insertions(+) diff --git a/src/AppMotor.Core/Extensions/TypeExtensions.cs b/src/AppMotor.Core/Extensions/TypeExtensions.cs index 0a8ff35d..46d497fe 100644 --- a/src/AppMotor.Core/Extensions/TypeExtensions.cs +++ b/src/AppMotor.Core/Extensions/TypeExtensions.cs @@ -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 diff --git a/tests/AppMotor.Core.Tests/Tests/Extensions/TypeExtensionsTests.cs b/tests/AppMotor.Core.Tests/Tests/Extensions/TypeExtensionsTests.cs index 42a6c4f5..d53d5ba5 100644 --- a/tests/AppMotor.Core.Tests/Tests/Extensions/TypeExtensionsTests.cs +++ b/tests/AppMotor.Core.Tests/Tests/Extensions/TypeExtensionsTests.cs @@ -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); + } + /// /// 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 ).