Method Chaining in C# or “This is not a post about Monads (yet!)”

Looking at the previous post people unfamiliar with F# might have noticed the copious use of

|>

the ‘pipe’ operator.

Essentially, it allows you to chain methods in a more readable way by giving you a binary operator where the left side is a value v and the right side is a function f, the result of the operator is simply f(v);

This can be nice for expressing operations involving lists and the like, but its usefulness extends to pretty much anytime you have to do Something(ToThis(BecauseOfThis(x)));

I thought about how useful it would be to implement the pipeline operator in C# to give the ability to express those operations cleanly.

A simple implementation could be an extension method like this:

public static U AndThen<T,U>(this T val, Func<T, U> f) { return f(val); }

Which would let you write things like this:

var dateInt = "2009/11/03"
. AndThen(x => x.Replace("/","")
. AndThen(x => Convert.ToInt32(x));

Not bad – but what if the Convert.ToInt32 throws an exception?

In normal C# you would have to write a bunch of nested if statements, each time checking for nulls or exceptions, and handle them with several else blocks.
This problem (and how to handle it) is well-understood in functional programming and people have developed a very elegant solution.
I won’t go into what a Monad is in this post (another time!), but what if we had a wrapper class that could turn any class into one that optionally had a value. Kind of like nullable types in .NET (except they can only be used with structs and value types, which motivates this post).

What if you could have something like List? to represent a value that may or may not contain a list of ints?
Let’s call this class Maybe (this implementation is courtesy of this blogger who did a great post on Monads in C# here)

	public class Maybe<T>
	{
	    public readonly static Maybe<T> Nothing = new Maybe<T>();
		
	    public T Value { get; private set; }
		
	    public bool HasValue { get; private set; }
		
	    Maybe()
	    {
	        HasValue = false;
	    }
		
	    public Maybe(T value)
	    {
	        Value = value;
	        HasValue = true;
	    }
	}	

If we add some methods to Maybe , maybe becomes a Monad, but we will talk about what that means in a later post.

With this Maybe class in hand, we can start to define an interface for method chaining that can handle problems that occur during invoking one method in the chain. If one of them has an issue, the result of the entire expression will be Maybe.Nothing.

We can set it up so that if a method lower down the chain gets passed a Nothing, it knows not to do anything but simply pass along the nothing.

We have now encapsulated the control flow of continuously testing for nulls.
I have a quick implementation up here on GitHub that I will likely develop further because there is lots more to explore in this space.

So we can handle exceptions and nulls silently:

			var val = "1234a ".If()
			.And(x => x.Trim())
			.And(x => Convert.ToInt32(x)); //throws exception
			Assert.IsFalse(val.HasValue); //true

			var val = "1234 ".If()
			.And(x => (string)null) //returns null
			.And(x => Convert.ToInt32(x));
			Assert.IsFalse(blah.HasValue); //true

Haskell being a pure functional language represents Exceptions this way, but we live in the .NET world and even in F# we might want side effects or be interacting with libraries that do.
So we can provide functions that are invoked when the value changes from Something to Nothing:

			string errorLog = String.Empty;
			var val = "1234a ".If()
			.And(x => x.Trim())
			.And(x => Convert.ToInt32(x), (x,e)=> errorLog = "couldn't convert integer" + e.ToString());
			Assert.IsFalse(String.IsNullOrEmpty(errorLog));

We also might want to provide a general failure side effect (for logging, say):

			string errorLog = String.Empty;
			var val = "1234a ".If()
			.And(x => x.Trim())
			.And(x => Convert.ToInt32(x))
			.FailWith(()=> errorLog = "operation failed");
			Assert.IsFalse(String.IsNullOrEmpty(errorLog));

This library is useful for method chaining and handling exceptions and other cases, but if you wanted to put in transparent logging or something similar you would still be forced to put it explicitly in the error continuation functions.
This is something that could be handled monadically but I haven’t thought enough about how to integrate that yet with a fluent interface in C#.

In F# you could use computation expressions (Monads!) and so encase all your statements in, say, log {}, as long as you implemented the monadic axioms for log, but syntactically that would end up pretty ugly in C#.

The source for this library is available on GitHub in a collection of functional utility classes I’ve been playing with here.

Check out the unit test project for more examples if you’re interested.

Tagged , , , , , , ,

2 thoughts on “Method Chaining in C# or “This is not a post about Monads (yet!)”

  1. enrique says:

    thank you for you article”Method Chaining in C# ” that i got what i needed and searched
    Thank you but keep on updating………..

  2. Jayan says:

    Great article. Can you post an example of how you would handle an if .. else statement using the Maybe monad? Especially where in the else part you need to invoke another method.
    Thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: