C
C#•2y ago
Nelson Sousa

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!
No description
5 Replies
Nelson Sousa
Nelson SousaOP•2y ago
Note: I know we could use myList!, but that's developer work instead of compiler actually knowing 😇
Thinker
Thinker•2y ago
Where are you getting myList from? The compiler is likely inferring this for a reason
Joschi
Joschi•2y ago
I think you are looking for the NotNullWhenAttribute This is how the .NET TryParse methods are implemented.
c#
// Determines whether a String represents true or false.
//
public static bool TryParse([NotNullWhen(true)] string? value, out bool result) =>
TryParse(value.AsSpan(), out result);
c#
// Determines whether a String represents true or false.
//
public static bool TryParse([NotNullWhen(true)] string? value, out bool result) =>
TryParse(value.AsSpan(), out result);
It says: If this method returns true this parameter won't be null.
Thinker
Thinker•2y ago
oh, read the question wrong, sorry. yeah this is correct
Nelson Sousa
Nelson SousaOP•2y ago
That was it, thank you!

Did you find this page helpful?