DEV Community

Matheus Rodrigues
Matheus Rodrigues

Posted on • Originally published at matheus.ro on

1 1

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...

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay