DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Matheus Rodrigues
Matheus Rodrigues

Posted on • Originally published at matheus.ro on

Design Patterns and Practices in .Net: Option Functional Type in C#

In the functional programming the option type is very used, in languages such as Haskell, F#, Scala and a lot more. In this language it’s a convention to return a value when the function fails. The following example is a function written in F#, to show how the option type works:

(* This function uses pattern matching to deconstruct Options *)
let compute = function
  | None -> "No value"
  | Some x -> sprintf "The value is: %d" x

printfn "%s" (compute <| Some 42)(* The value is: 42 *)
printfn "%s" (compute None) (* No value *)

We have no equivalent of the option type in the C# languageΒ , but we can try to emulate it.

In my lastΒ post, I discussed two design patterns, Null Object and the Special Case Object, the goal of these patterns are to return a special object instead of return null. If you didn’t read that post,Β go check itΒ and come back to this post.

The idea in this post is to show the implementation of the option type in C#.

Problem

The problem is very similar to my last post, in fact it’s the continuation of that same problem.

public IProduct GetProductById(int productId)
{
    Product product = _productRepository.GetProductById(productId);

    if(product == null)
        return new ProductNotFound();

    return product;
}

Continue Reading...

Top comments (0)

Dream Big


Use any Linode offering to create something unique or silly in the DEV x Linode Hackathon 2022 and win the Wacky Wildcard category.

β†’ Join the Hackathon <-