Why is *DoesNotReturnAttribute* not working as expected?

Viewed 263

Ich have a method ThrowNull covered with DoesNotReturn attribute which indicates that this method will never return.

[DoesNotReturn]
public static void ThrowNull([InvokerParameterName] string argName, string? customErrorText = null, [CallerMemberName] string callerName = "") => throw new ArgumentException(AddMethodName(customErrorText != null ? customErrorText.InsertArgs(argName) : Strings.ArgumentMustNotBeNullArgumentTemplate.InsertArgs(callerName), callerName), customErrorText == null ? argName : null);

but, it does not seem to work (as intended)

public static T ThrowIfNullOrGet<T>([MaybeNull, NotNullIfNotNull("source")] this T source, string argName, string? customErrorText = null, [CallerMemberName] string callerName = "") where T : class
{
    if (source != null)
        return source;

    Requires.ThrowNull(argName, customErrorText, callerName);
    return default; // still necessary to prevent compile error
}

Why?

Does DoesNotReturn not omit the necessity to put an return statement as it only avoids warnings?

1 Answers

The DoesNotReturn attribute has only declarative character and does not save you from putting return statement to non void methods/properties

use throw directly in your code and get the exception from somewhere else. (this can be seen often in decompiled MS code)

public static T GetOrThrowIfNull<T>([MaybeNull, NotNullIfNotNull("source")] this T source, string argName, string? customErrorText = null, [CallerMemberName] string callerName = "") where T : class
{
    if (source != null)
        return source;

    throw Exceptions.ArgumentNull(argName, customErrorText, callerName);
}
Related