Jacob Carpenter’s Weblog

March 3, 2008

Chained generic argument dependence revisited

Filed under: csharp — Jacob @ 6:36 pm

My last post had a fatal flaw: it looked like it was about F# and pattern matching.

The bit I was most proud of was the interesting application of generic parameters, constraints, and type inference—a sort of chained generic argument dependence. But I tricked you into thinking I was solving a very specific problem (that precious few of you care about).

But just today, I encountered a more generalized case where this type of generic abuse makes perfect sense!

A brief interruption

Raise your hand if you know what “functional composition” is.

For those of you with your hands firmly planted on your mice, functional composition is a really simple concept:

Say you have a function, let’s call it f, that takes an x and returns a y. You have another function, g, which takes a y and returns a z. Using functional composition, you can create a new function (h, for instance) which takes an x and returns a z.

That is, in C#, given:

Func<TX, TY> F;
Func<TY, TZ> G;

F and G can be composed as:

Func<TX, TZ> H = x => G(F(x));

Simple enough, right? Well, pretend we think this is useful enough to abstract to a utility method.

The definition would look something like:

public static Func<T1, TResult> Compose<T1, T2, TResult>(this Func<T1, T2> func1, Func<T2, TResult> func2)
    return t1 => func2(func1(t1));

Did you notice anything about that method signature?

We’ve introduced a form of chained generic argument dependence. The second parameter’s type depends on the first. Specifically, the second parameter must be a function whose argument matches the type of the return value of the first function.

In the case of Compose, this dependence isn’t a difficult API design decision; it’s merely an outcome of what we’re trying to express. But in some situations harnessing this chained dependence (and the compiler’s type inference capabilities) can result in an interesting API.

Real-world example

I’m surprised more people haven’t included some form of a null propagating operator on their C# 4.0 feature request lists. Well, Ed blogged our take on the operator awhile ago.

Let’s use that definition of IfNotNull to create a “real world” example of chained generic argument dependence. And how much more “real world” can you get than Customers and Orders?

class Customer
    public string Name { get; set; }
    public IList<Order> Orders { get; set; }

class Order
    public string Product { get; set; }

public static class IfNotNullExtension
    public static U IfNotNull<T, U>(this T t, Func<T, U> fn)
        return t != null ? fn(t) : default(U);

Let’s say we want to get the name of the first product of the first order. Using the above IfNotNull extension method, the code would look something like:

static void Main(string[] args)
    var customers = new[] {
        new Customer { Name = "Alejandro C. Dazé", Orders = new [] { new Order { Product = "Widget" } } },
        new Customer { Name = "Brad S. Grahne", Orders = null },

    foreach (Customer cust in customers)
        string productName = cust.IfNotNull(c => c.Orders)
            .IfNotNull(orders => orders.FirstOrDefault())
            .IfNotNull(o => o.Product);

        Console.WriteLine(productName ?? "<null>");

The output of which is:


Works great! But we have an opportunity here to use chained generic argument dependence to remove a couple of those calls to IfNotNull.

Chained generic argument dependence

Using our previous definition of IfNotNull, we can add the following (naively implemented) overload:

public static TResult IfNotNull<T1, T2, T3, TResult>(this T1 t,
    Func<T1, T2> fn1, Func<T2, T3> fn2, Func<T3, TResult> fnResult)
    return t.IfNotNull(fn1).IfNotNull(fn2).IfNotNull(fnResult);

Then, our calling code can become:

string productName = cust.IfNotNull(c => c.Orders,
    orders => orders.FirstOrDefault(), o => o.Product);

And I know I keep showing this, but because of generic type inference, intellisense helps out as you write each lambda expression:


I think that’s pretty cool.


I hope this post held your interest a little longer than the last one did. And I hope you can start to see uses for this sort of chained generic argument dependence in your APIs.

I’d be really interested if you’re already doing something like this or if you have a better name for this pattern. Let me know in the comments.

And finally, if this post was somehow unfulfilling and you still feel like you need to learn something cool, check out how to calculate square roots by hand!



  1. That’s a very clever extension method Jacob. Nice!

    Comment by Dustin Campbell — March 6, 2008 @ 7:17 am

  2. Thanks, Dustin.

    By the way, I probably should’ve linked to your post on function composition.

    I’m sure you’ll receive gobs of traffic from me, now that I’ve remedied that oversight. 😉

    Comment by jacobcarpenter — March 10, 2008 @ 1:35 pm

RSS feed for comments on this post. TrackBack URI

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

Blog at WordPress.com.

%d bloggers like this: