A collection of tools for dealing with nulls, failures and the generic type issues that arise in this domain.

https://github.com/Andy3432344/SafeResults

I’m the author, let me know what you think!

*Edit: updated to show GitHub link, sorry!

  • @eluvatar
    link
    51 month ago

    At least for this specific example I don’t know why I wouldn’t use null instead of option and ?? As it’s more clear what’s happening as it’s standard C#

    Also in your example does the function to the right of | execute always?

    • @expr
      link
      21 month ago

      Nulls are famously called the billion dollar mistake, and for good reason.

      Option types are the answer to that problem, because they make the optionality explicit and require one to handle it or propagate it.

      That being said: as someone that does functional programming professionally, this looks kinda janky, to me. But the good news is that C# is actually adding support for discriminated unions finally (seriously, it’s been waaaay too damn long): https://github.com/dotnet/csharplang/blob/18a527bcc1f0bdaf542d8b9a189c50068615b439/proposals%2FTypeUnions.md

      With discriminated unions, you can finally comfortably work with Option/Result types natively.

      • Kogasa
        link
        31 month ago

        Null pointers are one thing, C# nulls (with nullable reference types enabled) are another. They behave a lot like an Option monad with the caveat that the static analysis can technically be tricked by incorrect hints.

        • @DrDeadCrashOP
          link
          21 month ago

          I very much disagree with this, Null Reference Exceptions have been a huge problem in c#. Nullable reference types are a partial fix, but the question of “how do I ‘return’ an error from a statically typed method” is not answered there.

      • @[email protected]
        link
        fedilink
        11 month ago

        Are there any updates on DUs in C#? I feel like the linked proposal was opened a decade ago by now.

    • @DrDeadCrashOP
      link
      21 month ago

      The example is simplified, but I dislike returning null in my own code. The function will always execute, left or right doesn’t matter it’s mapped across in the ResultObject class.

      The function must return an IResult<T>, the ResultObject analyzes the IResult<T> checking for IFail or IOk. If it’s IOk the value of type T is retrieved from the Value property of the IOk<T> object and returned, the Some property defaults to true. If the IResult<T> is an IFail, Some is set to false, it copies the message from the IFail object into the ResultObject, and returns the value the was supplied to its constructor.

      I’m just sharing something I find useful, and I hope I can make it useful for others as well. Thanks for the questions.