Discriminated Unions in C#

Tuesday, 23 April 2013 07:19:00 GMT
Discriminated Unions in FSharp

Discriminated unions are an expressive construct used to describe values that can be modeled under one or more cases. This is the syntax as in MSDN documentation:

type type-name =
   | case-identifier1 [of type1 [ * type2 ...]
   | case-identifier2 [of type3 [ * type4 ...]

Discriminated unions describe also F# lists and when recursive they can model tree data structure.

Let’s start with an example that models the booking in a vacation facility:

type Booking =
    | Free
    | Single of DateTime
    | Range of DateTime * DateTime

This type can be used to define following values:

let free = Free
let single = Single(DateTime(2013,04,23))
let range = Range(DateTime(2013,04,23), DateTime(2013,04,26))

Main advantage of working with discriminated unions is that we can decompose them using pattern matching:

let describeBooking b =
    match b with
        | Single day -> "vacation on " + day.ToShortDateString()
        | Range (startDay, endDay)  -> "from " + startDay.ToShortDateString() + " to " + endDay.ToShortDateString()
        | _ -> "no vacation"

The function describeBooking matches against a Booking type and returns a descriptive string.

Obviously we only scratched the surface on the subject, so I invite you to read F# documentation or this wiki book.

Discriminated Unions in CSharp

Finally we get to the core of the post, where we I’ll follow the tecnique described in Real World Functional Programming to define discriminated unions in C#.

As you can imagine the OO construct we’ll use is inheritance.

As first we need define an enumeration with all cases:

enum BookingType { Free, Single, Range }

Then an abstract class that accepts the discriminator in the constructor and expose it publicly:

abstract class Booking
  private readonly BookingType tag;
protected Booking(BookingType tag) { this.tag = tag; }
public BookingType Tag { get { return this.tag; } } }

Now we define one sealed derived class for each case:

sealed class Free : Booking { public Free() : base(BookingType.Free) }
sealed class Single : Booking { private readonly DateTime date;
public Single(DateTime date) : base(BookingType.Single) { this.date = date; }
public DateTime Date { get { return this.date; } } }
sealed class Range : Booking { private readonly DateTime fromDate; private readonly DateTime toDate;
public Single(DateTime fromDate, DateTime toDate) : base(BookingType.Range) { this.fromDate = fromDate; this.toDate = toDate; }
public DateTime FromDate { get { return this.fromDate; } }
public DateTime ToDate { get { return this.toDate; } } }

Since C# lacks match constuct we can use switch against Tag discriminator and cast specific derivates:

string describeBooking(Booking booking)
  switch (booking.Tag)
    case Booking.Single:
      return "vacation on " + ((Single)booking).Date.ToShortDateString();
    case Booking.Range:
      var range = (Range)booking;
      return "from " + range.FromDate.ToShortDateString() + " to "
        + range.ToDate.ToShortDateString()
      return "no vacation";


It’s clear that this is a particular use of inheritance intended to mimic discriminated unions. Here the lack of extensibility is by design.

I suggest you such construct when the number of cases is predefined or will change little over the time.

I’ll report the same BCL usage of this pattern as in the book quoted above, System.Linq.Expression. In this type the desciminator is named NodeType and is defined as ExpressionType enumeration.

This post is part of YES! to NOOO initiative.

Handling Nulls

Monday, 25 March 2013 16:49:00 GMT
Avoid returning null…

…is all you need to avoid handling them. Quoting NOOO:

Options over nulls

Before digging into the argument, let’s take something simpler.

One of the worst thing of imperative code is all that ugly null checks.

Anyway please don’t feel disappointed, before realizing and getting in touch with FP; I as first filled my code with these.

For example take a C# code snippet like this that returns a collection of Order types.

var orders = DB.GetOrdersByDate(DateTime.Now);
if (orders != null)
  foreach (var order in orders)

    // do something with order

There’s no reason to design DB.GetOrdersByDate() to returns a null when no Order satisfies the request. An empty collection, easly obtainable with

return Enumerable.Empty<Order>();

would be great, the following code could became

var orders = DB.GetOrdersByDate(DateTime.Now);
foreach (var order in orders)
  // do something with order

When orders value is empty (or better an empty collection) no iteration will be performed, hence no kind of check is required.

Anyway cases could present in which you must check for order presence (in the old semantic the null check). Now we can elegantly write:

var orders = DB.GetOrdersByDate(DateTime.Now);
if (!orders.Any())
  // no orders

Because this code is semantically correct, hence is intrinsically more robust.

MayBe monad

As Mark Seemann says in this article: the BCL already has maybe monad.

He proposes the following construct through extension method:

public static class LightweightMaybe
    public static IEnumerable<T> Maybe<T>(this T value)
        return new[] { value };

So when you face an API (which you can change or not wrote by you) you can treat it like the sample above.

var client = LegacyDB.GetSingleClient(id: “101”);

if (client.Maybe().Any())
  // result is not null

As you can see this extension method put the T value inside a generic IEnumerable<T>, in this way you can use the beatiful Linq syntax to write readable code that clearly states its intent.

But this mean you should design code that returns null? No, you shouldn’t. I take the extreme position that returning a null is comparable to having a bug in the code.

If you can refactor LegacyDB.GetSingleClient() change its signature from:

public Client GetSingleClient(string id)
  if (found)
    return new Client(...);

  return null;


public IEnumerable<Client> GetSingleClient(string id)
  if (found)
    return new Client[] { new Client(...) };

  return Enumerable.Empty<Client>();

There’s nothing bad neither logically neither semantically to have a method handling one item returns a collection containing one item or otherwise an empty collection.

To me it’s wonderfully clean, clear and concise!


However I can understand criticism to this design, that could distract you from the main argument of this post: not returning null to avoid handling it.

You can design the method above using a singleton like string.Empty following the Write once immutability pattern, as explained in this Eric Lippert article.

public Client GetSingleClient(string id)
  if (found)
    return new Client(...);

  return Client.Empty;

The fundamental point here is that having a value, is always better than handling a null.

This is the reason why functional language like F# use option monad to describe if a result has or has not a value.

When keep it

New compiler constructs and projects like Code Contracts could remove also this necessity.

But for now there’s nothing bad to check null to validate method parameters.

public Client GetSingleClient(string id)
  if (id == null)
    throw new ArgumentNullException("id");

  if (found)
    return new Client(...);

  return Client.Empty;

However also here my opinion is a bit extreme: guard clauses are just against null; everything else falls into other application concerns such as validation.

But deepen it goes beyond the purpose of this post.


This blog post starts with a reference to NOOO. This is because this work is extracted from an unfinished and partly unpublished document.

The project aims to defined guidelines for developers who want to design API adhering to functional concepts from multi-paradigm languages like C#.

If you’re interested in this collaborative work, write to me (gsscoder AT gmail DOT com) or ping me via Twitter (@gsscoder).

Or visit this web site in status of work in progress.

Compiler Errors and Decoupling

Tuesday, 05 March 2013 21:51:00 GMT

With this post I want to share and reason about a brutal tecnique, that helped me when refactoring some code smells.

I could have called this post also Compiler Errors and Refactoring, but I’ll ask you license to use the term decoupling in broad sense.


It’s not hard to be called for a consulence and discover customer code into an highly disorganized state.

As a side note people always blame programmers and designers that preceded, and I’m tempted to ask why don’t you attempted to bring some order?. But this question often lacks a concrete reply…

Often customers pretend a fast evaluation of the problem that always resolved in three options:

  • Reverse engineer it, rewrite a specification with TDD and rebuild it (if budget allows)

  • Re-iterate refactorings with the help of your testing framework of choice, a sort of TDR; again with licence, Test-Driven-Refactoring (if budget allows)

  • And if budget doesn’t allow, choose the more diplomatic way to quit (if you can).

Quick Metrics

One of the most generalized code smells I encouter is Contrived complexity (from Wikipedia):

forced usage of overly complicated design patterns where simpler design would suffice

In my expierience this is got with tightly coupling (who inspired post title) and Inappropriate intimacy smell (from Wikipedia):

a class that has dependencies on implementation details of another class

In such cases the first thing I do, is enabling Show All Files from Visual Studio Solution Explorer and start excluding .cs source file from various projects.

There’s no need to explain what happens next. C# compiler start spitting out errors like:

Error 6 The name 'XyzFactory' does not exist in the current context X:\CustProj\Proj1\CoreFeature.cs 326 30 Proj1

Normally errors are not best friend of developers, but in this case the compiler is giving you useful information.

Also if some error can mask others, you’ve a good outlook of the number of times XyzFactory type is used in that codebase.

As always by selecting the File column you can reorder the error list, making even clear in which source file XyzFactory is used.

If the convention of putting one class for file is complied, this is also a list of types that depends on XyzFactory.


Never to mention that such way of proceeding, doesn’t free you from properly anlyze code and use your expierience to measure how the code base differs SOLID principles.

Bootstrapping a new blog

Tuesday, 05 March 2013 13:52:00 GMT

Saying that I’m moving my blog from Blogger because I find it uncomfortable, I would say only a half-truth.

After all you’ll not find old posts here. In such case the first post wuold have been titled Moving the blog to… or something similar. I admit, I’ve misused the old blog: creating short article that would have been placed in Twitter and creating posts just to highlight something interesting.

However some articles had good consensus and one day may will be migrated here.


So it’s clear that this is a statement of intent: create articles that let me understand things better during the process of sharing.

It’ll try to focus programming concepts both from implementation and design perspective. The most of samples will be for .NET Framework in C# (with the hope to cover some F# in near future).

But I want point out that I’m not here to teach, I’m here to learn.


If you want you can follow me on Twitter as @gsscoder, where I’ll post when a new article is created.


It’s extremely easy to use, requires few tools to get a blog up and running and can be hosted hassle free in an a GitHub repository (of which I’m a big fan).

I made ​​the final decision when I found this guide and when Mark Seemann talked about its switch to this platform in Twitter. By the way don’t miss to read his blog.

Page 1 of 1