From 0aa92903c7230159f311a300ec12e507caeecd57 Mon Sep 17 00:00:00 2001 From: hmoratopcs Date: Mon, 5 May 2025 19:20:51 +0200 Subject: [PATCH] Improve nullability annotations on the Adapt extension method A warning will appear if you try to map a nullable input to a non-nullable result: ` ProductDTO dto = ((Product?)null).Adapt();` --- src/Mapster/TypeAdapter.cs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/Mapster/TypeAdapter.cs b/src/Mapster/TypeAdapter.cs index 0ac37924..4c107adf 100644 --- a/src/Mapster/TypeAdapter.cs +++ b/src/Mapster/TypeAdapter.cs @@ -1,5 +1,6 @@ -using System; +using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using Mapster.Models; @@ -24,7 +25,8 @@ public static ITypeAdapterBuilder BuildAdapter(this TSource so /// Destination type. /// Source object to adapt. /// Adapted destination type. - public static TDestination Adapt(this object? source) + [return: NotNullIfNotNull(nameof(source))] + public static TDestination? Adapt(this object? source) { return Adapt(source, TypeAdapterConfig.GlobalSettings); } @@ -36,14 +38,15 @@ public static TDestination Adapt(this object? source) /// Source object to adapt. /// Configuration /// Adapted destination type. - public static TDestination Adapt(this object? source, TypeAdapterConfig config) + [return: NotNullIfNotNull(nameof(source))] + public static TDestination? Adapt(this object? source, TypeAdapterConfig config) { // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (source == null) - return default!; + return default; var type = source.GetType(); var fn = config.GetDynamicMapFunction(type); - return fn(source); + return fn(source)!; } ///