Hacker News new | ask | show | jobs
by angrysaki 290 days ago
>The compiler gives us a way to deal with this situation. It is all about being absolutely clear with intentions. Yes, Where(..) in my example would return IEnumerable<TR?> but then in subsequent code I can tell the compiler that I know for a fact that TR? is actually TR by using the null forgiving operator (!).

I guess that seems way less clear with intentions to me. If I have an array of potentially null types and I want to filter out the not nulls, I'd much rather have an operation that returns a T[] vs a T?[].

I should also note that I also have a "IEnumerable<T> WhereNotNull(IEnumerable<T>?)" function in my codebase, but I implemented it using a foreach/yield which doesn't suffer from the extra Cast<>()

1 comments

I actually use OfType<TR> to remove null elements as suggested by the doc. https://learn.microsoft.com/en-us/dotnet/api/system.linq.enu... Performance-wise, where is this situated?