How to let compiler know that List is not null?
Hi community!
I have the following extension method:, which checks if the source is not null and if it contains any elements:
public static bool SafeAny<T>(this IEnumerable<T> source) => source != null && source.Any();
I'd like to inform the compiler that, when returning true, the source is not null. Is this possible to achieve with C#?
Thank you!5 Replies
Note: I know we could use myList!, but that's developer work instead of compiler actually knowing 😇
myList
from? The compiler is likely inferring this for a reasonI think you are looking for the
NotNullWhenAttribute
This is how the .NET TryParse methods are implemented.
It says: If this method returns true this parameter won't be null.oh, read the question wrong, sorry. yeah this is correct
That was it, thank you!