So I've got a little method that looks like:
public static bool AnyNull(params object?[] args)
{
if (args.Any(a => IsNull(a)))
{
return true;
}
return false;
}
private static bool IsNull([NotNullWhen(false)] object? obj) => obj is null;
e.g.
var maybeNullObj1 = source1.GetValue();
var maybeNullObj2 = source2.GetValue();
...etc
if(AnyNull(maybeNullObj1, maybeNullObj2, ...)){
return;
}
// Do something without nullable warnings
The goal here is to be able to just throw a bunch of objects in the function and assert that they aren't null, to avoid these big chains of if (x == null) return;. However I'd like this to get rid of nullability warnings in the calling method. Unfortunately the above does not work, despite the attempt at NotNullWhen. Does anyone have any idea how you could do this?
paramsvalues is not null? (you should provide a code sample to highlight this) Yeah, I don't see how that could work. The best way to avoid lots of not-null test, is to keep pushing knowledge of not-null constraints up the call stack.IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> self)that filters all thenull-items or an extension method likeIEnumerable<T> ThrowOnNullItem<T>(this IEnumerable<T?> self)that throws anArgumentNullExceptionif annullitem is found. But in that case your variable should be declared asIEnumerable<T>instead of allowing the caller to pass annullitem just to punish him with an exception.IEnumerable<T?>to anIEnumerable<T>- and that is an extension method. But that filters the elements away - that does not ensure that all the elements are not null. That's why this is only a comment and not an solution.