Home > Mobile >  .NET 7 ConfigurationBinder incorrect return type?
.NET 7 ConfigurationBinder incorrect return type?

Time:11-10

In .NET 6, the ConfigurationBinder.Get<T> method used to return a T. In .NET 7, it's now returning a T?. However, when I look at its source code, I don't see why it needs to be so:

public static T? Get<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] T>(this IConfiguration configuration, Action<BinderOptions>? configureOptions)
{
    ThrowHelper.ThrowIfNull(configuration);

    object? result = configuration.Get(typeof(T), configureOptions);
    if (result == null)
    {
        return default(T);
    }
    return (T)result;
}

Doesn't this function always actually return T?

CodePudding user response:

return default(T); will result in null if T is reference type or nullable value type (as shown in the docs example or you can check it out yourself), so the return type is correct.

  • Related