4 ms·
C# only sort-of-fixed this problem and it did so rather inelegantly IMO. E.g. nullable types are not options - you can't "map" them (you can't invoke Select, W
by virgilp 5y ago
C# only sort-of-fixed this problem and it did so rather inelegantly IMO.
E.g. nullable types are not options - you can't "map" them (you can't invoke Select, Where etc). It's easy to "get value or default" (via operator `??`), but you can't do the other, equally frequent thing, of "apply transformation on value if not-null". Or... well, you can, but here's the syntax:
var newVal = val == null ? (resultType?) null : compute(val.Value);
instead of
var newVal = val.Select(compute);
- CodesInChaos 5y agoFor that I use my own extension function like `?.Map(x => ...)`, defined as `Map(this T input, Func<T, TResult> map) => map(input)`. Still a bit ugly, but much nicer than the ternary operator. Of course that doesn't fix all the other issues with null handling in C# (inconsistency between null references and null value types, inability to nest options, ...)
- mathw 5y agoVarious bits of C# and its libraries also variously ignore non-nullability when it suits them. I know it's done the way it's done for compatibility reasons, but it's really quite confusing around the edges as a result. And despite something being non-nullable in the code it could still be null at runtime thanks in my experience particularly to the joys of deserialisation libraries.