Hacker News new | past | comments | ask | show | jobs | submit login

Nullable is not an adequate replacement for Maybe/Option, one because it is constrained only to value types, which makes it useless generically anyway, and secondly, because you can easily "bypass" it and attempt to call .Value while skipping .HasValue, causing an exception to be thrown. C# lacks the necessary features to have a useful Maybe type - namely exhaustive pattern matching and the Unit type.

A better pattern used in say, F#, would be to return the tuple of <bool, T>, which could handle reference types and value types uniformly unlike Nullable. That won't slide in C# though as there's no syntactic sugar for tuples, and calling .Item1, .Item2 is too "inelegant" for the regular programmer.

For now though, the bool Try_(_, out _ _) is still the preferred method by most.

Func and Action are certainly useful, but sometimes having a named delegate type is still preferable because you can capture the purpose of the delegate in it's name, rather than resorting to doc comments nobody is going to read anyway.




You don't need it for reference types, because those can just return a null.

I agree that it would be nice if C# checked that you dealt with the null case of the return - Resharper will happily warn me if I haven't, but it would be nice if the base compiler did. Maybe in the future!


>You don't need it for reference types, because those can just return a null.

The point is that it is not necessarily correct to conflate the nullability of the parse with the correctness of the parse. If I wanted to parse a string into a Foo, null might be a valid value for a successful parse to return, say because the rule is that the string "(null)" maps to a null Foo.


There is a draft for pattern-matching in C# [1].

[1] https://roslyn.codeplex.com/discussions/560339


Nullable is the perfect solution for TryParse. The InvalidOperationException on null is the equivalent of the NullPointerException you would expect for a reference class TryParse method.

I have implemented TryParse methods on many reference types with exactly these semantics - object on success, null on failure (often with details logged at DEBUG).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: