Skip to content

Commit

Permalink
Slightly improve performance of Type.IsNullableValueType()
Browse files Browse the repository at this point in the history
  • Loading branch information
skrysmanski committed Jun 25, 2024
1 parent c350e70 commit c69a3f7
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/AppMotor.Core/Extensions/TypeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -252,13 +252,22 @@ public static bool IsNullableType(this Type type)
/// <summary>
/// Returns whether this is a nullable value type.
/// </summary>
/// <seealso cref="IsNullableType"/>
/// <remarks>
/// This method returns <c>false</c> for <c>typeof(Nullable&lt;&gt;)</c> (i.e. the open
/// generic).
/// </remarks>
[MustUseReturnValue]
public static bool IsNullableValueType(this Type type)
{
Validate.ArgumentWithName(nameof(type)).IsNotNull(type);

return Nullable.GetUnderlyingType(type) != null;
// ReSharper disable once MergeIntoPattern
if (type.IsGenericType && !type.IsGenericTypeDefinition)
{
return type.GetGenericTypeDefinition() == typeof(Nullable<>);
}

return false;
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,8 @@ public void Test_IsNullableValueType()

typeof(string).IsNullableValueType().ShouldBe(false);
typeof(object).IsNullableValueType().ShouldBe(false);

typeof(Nullable<>).IsNullableValueType().ShouldBe(false);
}

[Fact]
Expand Down

0 comments on commit c69a3f7

Please sign in to comment.