DEV Community

Matheus Rodrigues
Matheus Rodrigues

Posted on • Originally published at 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#.


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)