C
C#ā€¢9mo ago
nelsonprsousa

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
nelsonprsousa
nelsonprsousaā€¢9mo ago
Note: I know we could use myList!, but that's developer work instead of compiler actually knowing šŸ˜‡
Thinker
Thinkerā€¢9mo ago
Where are you getting myList from? The compiler is likely inferring this for a reason
Joschi
Joschiā€¢9mo 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ā€¢9mo ago
oh, read the question wrong, sorry. yeah this is correct
nelsonprsousa
nelsonprsousaā€¢9mo ago
That was it, thank you!
Want results from more Discord servers?
Add your server
More Posts