C# Puzzle 2

Very poorPoorAverageGoodExcellent (No Ratings Yet) 

Just another little puzzle based on an issue I had at work…

Consider this piece of code :

Console.WriteLine($"x > y is {x > y}");
Console.WriteLine($"!(x <= y) is {!(x <= y)}");

How would you declare and initialize x and y for the program to produce the following, apparently illogical, output?

x > y is False
!(x <= y) is True
Posted in Puzzles. Tags: , . 2 Comments »

How to retrieve dates as UTC in SQLite

Very poorPoorAverageGoodExcellent (No Ratings Yet) 

SQLite is a nice in-process database engine: it’s very lightweight, doesn’t require any server or configuration, and runs on all platforms. There is even an official ADO.NET provider that’s very well made. However, if you store dates as UTC with this provider, you will probably encounter a serious issue: even though the date is properly stored as UTC (it’s stored in a form similar to ISO8601, with a ‘Z’ to indicate the UTC timezone), when you read it back from the database, you will get a DateTime converted to local time, with Kind = Unspecified. Here’s an example that exhibits the problem (using Dapper in LINQPad):

void Main()
    string connectionString = @"Data Source=D:\tmp\testSQLiteDate.db";
    using (var connection = new SQLiteConnection(connectionString))
        connection.Execute("create table Foo(Id integer not null primary key, CreationDateUtc datetime not null)");
        var foo = new Foo{Id = 42, CreationDateUtc = DateTime.UtcNow};
        foo.Dump("Original object");
        connection.Execute("insert into Foo(Id, CreationDateUtc) values (@Id, @CreationDateUtc)", foo);
        var foo2 = connection.Query<Foo>("select * from Foo where Id = @Id", new{ Id = 42 }).SingleOrDefault();
        foo2.Dump("After reading from DB");

class Foo
    public int Id { get; set; }
    public DateTime CreationDateUtc { get; set; }
    public DateTimeKind Kind { get { return CreationDateUtc.Kind; } }

Here’s the output:


As you can see, after reading it from the database, the date is no longer in UTC, and doesn’t even contain an indication that it’s a local date. This can cause all kinds of bugs if your code is comparing dates that are supposed to be UTC.

I initially tried to fix that in my code by manually converting the date, before I realized that the solution was much simpler (although not very well documented): there is a connection string setting to control how dates are handled. You just need to specify DateTimeKind=Utc in your connection string:

string connectionString = @"Data Source=D:\tmp\testSQLiteDate.db;DateTimeKind=Utc";

If you’re using SqliteConnectionStringBuilder to build the connection string, just set the DateTimeKind property to DateTimeKind.Utc.

As you can see, the date kind is now preserved:



Important caveat: this setting will apply to all dates read from this connection. If you have dates that were not stored as UTC, the provider will assume that they are UTC dates anyway, which will produce incorrect results. So, only do this if you store all dates as UTC.

Create an auto-mocking container with Unity and FakeItEasy

Very poorPoorAverageGoodExcellent (No Ratings Yet) 

Unit testing can be tedious sometimes, especially when testing classes that have complex dependencies. Fortunately, some tools make it somewhat easier. I’ve been using FakeItEasy a lot recently; it’s a very easy to use mocking framework for .NET. It has a very lean and simple API based on generics and lambda expressions, and is a real pleasure to work with. It came as a breath of fresh air compared to the old RhinoMocks I had been using before.

But as nice as FakeItEasy is, the process of registering all the fake dependencies for the class you are testing is still a bit tedious. Wouldn’t it be nice if the IoC container could automatically create the fakes on demand ? So this code:

var container = new UnityContainer();

// Setup dependencies
var fooProvider = A.Fake<IFooProvider>();
var barService = A.Fake<IBarService>();
var bazManager = A.Fake<IBazManager>();

var sut = container.Resolve<SystemUnderTest>();

Could be reduced to this:

var container = new UnityContainer();

// This will cause the container to provide fakes for all dependencies

var sut = container.Resolve<SystemUnderTest>();

Well, it’s actually pretty easy to do with Unity. Unity is usually not considered the “cool kid” in the small world of IoC containers, but it’s well supported, easy to use, and extensible. I came up with the following extension to enable the above scenario:

public class AutoFakeExtension : UnityContainerExtension
    protected override void Initialize()
    private class AutoFakeBuilderStrategy : BuilderStrategy
        private static readonly MethodInfo _fakeGenericDefinition;
        static AutoFakeBuilderStrategy()
            _fakeGenericDefinition = typeof(A).GetMethod("Fake", Type.EmptyTypes);
        public override void PreBuildUp(IBuilderContext context)
            if (context.Existing == null)
                var type = context.BuildKey.Type;
                if (type.IsInterface || type.IsAbstract)
                    var fakeMethod = _fakeGenericDefinition.MakeGenericMethod(type);
                    var fake = fakeMethod.Invoke(null, new object[0]);
                    context.PersistentPolicies.Set<ILifetimePolicy>(new ContainerControlledLifetimeManager(), context.BuildKey);
                    context.Existing = fake;
                    context.BuildComplete = true;

A few comments on this code:

  • The logic is a bit crude (it generates fakes only for interfaces and abstract classes), but can easily be adjusted if necessary.
  • The ugly reflection hack is due to the fact that FakeItEasy doesn’t have an non-generic overload of A.Fake that accepts a Type as a parameter. Well, nobody’s perfect…
  • The lifetime is set to “container controlled”, because if you need to configure method calls, you will need to access the same instance that is injected into the system under test:
var fooProvider = container.Resolve<IFooProvider>();
A.CallTo(() => fooProvider.GetFoo(42)).Returns(new Foo { Id = 42, Name = “test” });

Note that if you register a dependency explicitly, it will take precedence and no fake will be created. So you can use this extension and still be able to manually specify a dependency:

var container = new UnityContainer();
container.RegisterType<IFooProvider, TestFooProvider>();
var sut = container.Resolve<SystemUnderTest>();

Of course, this extension could easily be modified to use a different mocking framework. I guess the same principle could be applied to other IoC containers as well, as long as they have suitable extension points.

What about AutoFixture?

Before you ask: yes, I know about AutoFixture. It’s a pretty good library, and I actually tried to use it as well, with some success. The resulting code is very similar to the examples above. The main reason why I didn’t keep using it is that AutoFixture is not really an IoC container (though it does some of the things an IoC container does), and I prefer to use the same IoC mechanism in my unit tests and in the actual application. Also, I’m not very comfortable with the way it handles properties when creating an instance of the SUT. By default, it sets all public writable properties to dummy instances of their type; this is fine if those properties are used for dependency injection, but IMO it doesn’t make sense for other properties. I know I can suppress this behavior for specific properties, but I have to do it manually on a case by case basis; it doesn’t take IoC container specific attributes like [Dependency] into account. So eventually I found it easier to use my custom Unity extension.

Async and cancellation support for wait handles

Very poorPoorAverageGoodExcellent (No Ratings Yet) 

The .NET framework comes with a number of low-level synchronization primitives. The most commonly used are collectively known as “wait handles”, and inherit the WaitHandle class: Semaphore, Mutex, AutoResetEvent and ManualResetEvent. These classes have been there since at least .NET 2.0 (1.1 for some of them), but they haven’t evolved much since they were introduced, which means they don’t support common features that were introduced later. In particular, they don’t provide support for waiting asynchronously, nor do they support cancelling the wait. Fortunately, it’s actually quite easy to add these features via extension methods.


Let’s start with the easiest one: cancellation. There are cases where it would be useful to pass a CancellationToken to WaitHandle.WaitOne, but none of the overloads supports it. Note that some more recent variants of the synchronization primitives, such as SemaphoreSlim and ManualResetEventSlim, do support cancellation; however, they’re not necessarily suitable for all use cases, because they’re designed for when the wait times are expected to be very short.

A CancellationToken exposes a WaitHandle, which is signaled when cancellation is requested. We can take advantage of this to implement a cancellable wait on a wait handle:

    public static bool WaitOne(this WaitHandle handle, int millisecondsTimeout, CancellationToken cancellationToken)
        int n = WaitHandle.WaitAny(new[] { handle, cancellationToken.WaitHandle }, millisecondsTimeout);
        switch (n)
            case WaitHandle.WaitTimeout:
                return false;
            case 0:
                return true;
                return false; // never reached

We use WaitHandle.WaitAny to wait for either the original wait handle or the cancellation token’s wait handle to be signaled. WaitAny returns the index of the first wait handle that was signaled, or WaitHandle.WaitTimeout if a timeout occurred before any of the wait handles was signaled. So we can have 3 possible outcomes:

  • a timeout occurred: we return false (like the standard WaitOne method);
  • the original wait handle is signaled first: we return true (like the standard WaitOne method);
  • the cancellation token’s wait handle is signaled first: we throw an OperationCancelledException.

    For completeness, let’s add some overloads for common use cases:

        public static bool WaitOne(this WaitHandle handle, TimeSpan timeout, CancellationToken cancellationToken)
            return handle.WaitOne((int)timeout.TotalMilliseconds, cancellationToken);
        public static bool WaitOne(this WaitHandle handle, CancellationToken cancellationToken)
            return handle.WaitOne(Timeout.Infinite, cancellationToken);

    And that’s it, we now have a cancellable WaitOne method!

    Asynchronous wait

    Now, what about asynchronous wait? That’s a bit harder. What we want here is a WaitOneAsync method that returns a Task<bool> (and since we’re at it, we might as well include cancellation support). The typical approach to create a Task wrapper for a non-task-based asynchronous operation is to use a TaskCompletionSource<T>, so that’s what we’ll do. When the wait handle is signaled, we’ll set the task’s result to true; if a timeout occurs, we’ll set it to false; and if the cancellation token is signaled, we’ll mark the task as cancelled.

    I struggled a bit to find a way to execute a delegate when a wait handle is signaled, but I eventually found the ThreadPool.RegisterWaitForSingleObject method, which exists for this exact purpose. I’m not sure why it’s in the ThreadPool class; I think it would have made more sense to put it in the WaitHandle class, but I assume there’s a good reason.

    So here’s what we’ll do:

  • create a TaskCompletionSource<bool>;
  • register a delegate to set the result to true when the wait handle is signaled, or false if a timeout occurs, using ThreadPool.RegisterWaitForSingleObject;
  • register a delegate to mark the task as cancelled when the cancellation token is signaled, using CancellationToken.Register;
  • unregister both delegates after the task completes

    Here’s the implementation:

        public static async Task<bool> WaitOneAsync(this WaitHandle handle, int millisecondsTimeout, CancellationToken cancellationToken)
            RegisteredWaitHandle registeredHandle = null;
            CancellationTokenRegistration tokenRegistration = default(CancellationTokenRegistration);
                var tcs = new TaskCompletionSource<bool>();
                registeredHandle = ThreadPool.RegisterWaitForSingleObject(
                    (state, timedOut) => ((TaskCompletionSource<bool>)state).TrySetResult(!timedOut),
                tokenRegistration = cancellationToken.Register(
                    state => ((TaskCompletionSource<bool>)state).TrySetCanceled(),
                return await tcs.Task;
                if (registeredHandle != null)
        public static Task<bool> WaitOneAsync(this WaitHandle handle, TimeSpan timeout, CancellationToken cancellationToken)
            return handle.WaitOneAsync((int)timeout.TotalMilliseconds, cancellationToken);
        public static Task<bool> WaitOneAsync(this WaitHandle handle, CancellationToken cancellationToken)
            return handle.WaitOneAsync(Timeout.Infinite, cancellationToken);

    Note that the lambda expressions could have used the tcs variable directly; this would make the code more readable, but it would cause a closure to be created, so as a small performance optimization, tcs is passed as the state parameter.

    We can now use the WaitOneAsync method like this:

    var mre = new ManualResetEvent(false);
    if (await mre.WaitOneAsync(2000, cancellationToken))

    Important note: this method will not work for a Mutex, because it relies on RegisterWaitForSingleObject, which is documented to work only on wait handles other than Mutex.


    We saw that with just a few extension methods, we made the standard synchronization primitives much more usable in typical modern code involving asynchrony and cancellation. However, I can hardly finish this post without mentioning Stephen Cleary’s AsyncEx library; it’s a rich toolbox which offers async-friendly versions of most standard primitives, some of which will let you achieve the same result as the code above. I encourage you to have a look at it, there’s plenty of good stuff in it.

  • Posted in Code sample. Tags: , , . 4 Comments »

    C# Puzzle 1

    Very poorPoorAverageGoodExcellent (6 votes) 

    I love to solve C# puzzles; I think it’s a great way to gain a deep understanding of the language. And besides, it’s fun!

    I just came up with this one:

    static void Test(out int x, out int y)
        x = 42;
        y = 123;
        Console.WriteLine (x == y);

    What do you think this code prints? Can you be sure? Post your answer in the comments!

    I’ll try to post more puzzles in the future if I can come up with others.

    Posted in Puzzles. Tags: , . 12 Comments »

    Async unit tests with NUnit

    Very poorPoorAverageGoodExcellent (No Ratings Yet) 

    Recently, my team and I started writing unit tests on an application that uses a lot of async code. We used NUnit (2.6) because we were already familiar with it, but we had never tried it on async code yet.

    Let’s assume the system under test is this very interesting Calculator class:

        public class Calculator
            public async Task<int> AddAsync(int x, int y)
                // simulate long calculation
                await Task.Delay(100).ConfigureAwait(false);
                // the answer to life, the universe and everything.
                return 42;

    (Hint: this code has a bug… 42 isn’t always the answer. This came to me as a shock!)

    And here’s a unit test for the AddAsync method:

            public async void AddAsync_Returns_The_Sum_Of_X_And_Y()
                var calculator = new Calculator();
                int result = await calculator.AddAsync(1, 1);
                Assert.AreEqual(2, result);

    async void vs. async Task

    Even before trying to run this test, I thought to myself: This isn’t gonna work! an async void method will return immediately on the first await, so NUnit will think the test is complete before the assertion is executed, and the test will always pass even if the assertion fails. So I changed the method signature to async Task instead, thinking myself very clever for having avoided this trap…

            public async Task AddAsync_Returns_The_Sum_Of_X_And_Y()

    As expected, the test failed, confirming that NUnit knew how to handle async tests. I fixed the Calculator class, and stopped thinking about it. Until one day, I noticed that my colleague was writing test methods with async void. So I started to explain to him why it couldn’t work, and tried to demonstrate it by introducing an assertion that would fail… and to my surprise, the test failed, proving that I was wrong. Mind blown!

    Having an inquisitive mind, I immediately started to investigate… My first idea was to check the current SynchronizationContext, and indeed I saw that NUnit had changed it to an instance of NUnit.Framework.AsyncSynchronizationContext. This class maintains a queue of all the continuations that are posted to it. After the async void test method has returned (i.e., the first time a not-yet-completed task is awaited), NUnit calls the WaitForPendingOperationsToComplete method, which executes all the continuations in the queue, until the queue is empty. Only then is the test considered complete.

    So, the moral of the story is: you can write async void unit tests in NUnit 2.6. It also works for delegates passed to Assert.Throws, which can have an async modified. Now, just because you can doesn’t mean you should. Not all test frameworks seem to have the same support for this. The next version of NUnit (3.0, still in alpha) will not support async void tests.

    So, unless you plan on staying with NUnit 2.6.4 forever, it’s probably better to always use async Task in your unit tests.

    Posted in Unit testing. Tags: , , , . 2 Comments »

    Optimize ToArray and ToList by providing the number of elements

    Very poorPoorAverageGoodExcellent (2 votes) 

    The ToArray and ToList extension methods are convenient ways to eagerly materialize an enumerable sequence (e.g. a Linq query) into an array or a list. However, there’s something that bothers me: both of these methods are very inefficient if they don’t know the number of elements in the sequence (which is almost always the case when you use them on a Linq query). Let’s focus on ToArray for now (ToList has a few differences, but the principle is mostly the same).

    Basically, ToArray takes a sequence, and returns an array that contains all the elements from the sequence. If the sequence implements ICollection<T>, it uses the Count property to allocate an array of the right size, and copy the elements into it; here’s an example:

    List<User> users = GetUsers();
    User[] array = users.ToArray();

    In this scenario, ToArray is fairly efficient. Now, let’s change that code to extract just the names from the users:

    List<User> users = GetUsers();
    string[] array = users.Select(u => u.Name).ToArray();

    Now, the argument of ToArray is an IEnumerable<User> returned by Select. It doesn’t implement ICollection<User>, so ToArray doesn’t know the number of elements, so it cannot allocate an array of the appropriate size. So here’s what it does:

    1. start by allocating a small array (4 elements in the current implementation)
    2. copy elements from the source into the array until the array is full
    3. if there are no more elements in the source, go to 7
    4. otherwise, allocate a new array, twice as large as the previous one
    5. copy the items from the old array to the new array
    6. repeat from step 2
    7. if the array is longer than the number of elements, trim it: allocate a new array with exactly the right size, and copy the elements from the previous array
    8. return the array

    If there are few elements, this is quite painless; but for a very long sequence, it’s very inefficient, because of the many allocations and copies.

    What is annoying is that, in many cases, we know the number of elements in the source! In the example above, we only use Select, which doesn’t change the number of elements, so we know that it’s the same as in the original list; but ToArray doesn’t know, because the information was lost along the way. If only we had a way to help it by providing this information ourselves….

    Well, it’s actually very easy to do: all we have to do is create a new extension method that accepts the count as a parameter. Here’s what it might look like:

    public static TSource[] ToArray<TSource>(this IEnumerable<TSource> source, int count)
        if (source == null) throw new ArgumentNullException("source");
        if (count < 0) throw new ArgumentOutOfRangeException("count");
        var array = new TSource[count];
        int i = 0;
        foreach (var item in source)
            array[i++] = item;
        return array;

    Now we can optimize our previous example like this:

    List<User> users = GetUsers();
    string[] array = users.Select(u => u.Name).ToArray(users.Count);

    Note that if you specify a count that is less than the actual number of elements in the sequence, you will get an IndexOutOfRangeException; it’s your responsibility to provide the correct count to the method.

    So, what do we actually gain by doing that? From my benchmarks, this improved ToArray is about twice as fast as the built-in one, for a long sequence (tested with 1,000,000 elements). This is pretty good!

    Note that we can improve ToList in the same way, by using the List<T> constructor that lets us specify the initial capacity:

    public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source, int count)
        if (source == null) throw new ArgumentNullException("source");
        if (count < 0) throw new ArgumentOutOfRangeException("count");
        var list = new List<TSource>(count);
        foreach (var item in source)
        return list;

    In this case, the performance gain is not as as big as for ToArray (about 25% instead of 50%), probably because the list doesn’t need to be trimmed, but it’s not negligible.

    Obviously, a similar optimization could be made to ToDictionary as well, since the Dictionary<TKey, TValue> class also has a constructor that lets us specify the initial capacity.

    The improved ToArray and ToList methods are available in my Linq.Extras library, which also provides many useful extension methods for working on sequences and collections.

    Easily convert file sizes to human-readable form

    Very poorPoorAverageGoodExcellent (No Ratings Yet) 

    If you write an application that has anything to do with file management, you will probably need to display the size of the files. But if a file has a size of 123456789 bytes, it doesn’t mean that you should just display this value to the user, because it’s hard to read, and the user usually doesn’t need 1-byte precision. Instead, you will write something like 118 MB.

    This should be a no-brainer, but there are actually a number of different ways to display byte sizes… For instance, there are several co-existing conventions for units and prefixes:

    • The SI (International System of Units) convention uses decimal multiples, based on powers of 10: 1 kilobyte is 1000 bytes, 1 megabyte is 1000 kilobytes, etc. The prefixes are the one from the metric system (k, M, G, etc.).
    • The IEC convention uses binary multiples, based on powers of 2: 1 kibibyte is 1024 bytes, 1 mebibyte is 1024 kibibytes, etc. The prefixes are Ki, Mi, Gi etc., to avoid confusion with the metric system.
    • But neither of these conventions is commonly used: the customary convention is to use binary mutiples (1024), but decimal prefixes (K, M, G, etc.).

    Depending on the context, you might want to use either of these conventions. I’ve never seen the SI convention used anywhere; some apps (I’ve seen it in VirtualBox for instance) use the IEC convention; most apps and operating systems use the customary convention. You can read this Wikipedia article if you want more details: Binary prefix.

    OK, so let’s chose the customary convention for now. Now you have to decide which scale to use: do you want to write 0.11 GB, 118 MB, 120564 KB, or 123456789 B? Typically, the scale is chosen so that the displayed value is between 1 and 1024.

    A few more things you might have to consider:

    • Do you want to display integer values, or include a few decimal places?
    • Is there a minimum unit to use (for instance, Windows never uses bytes: a 1 byte file is displayed as 1 KB)?
    • How should the value be rounded?
    • How do you want to format the value?
    • for values less than 1KB, do you want to use the word “bytes”, or just the symbol “B”?

    OK, enough of this! What’s your point?

    So as you can see, displaying a byte size in human-readable form isn’t as straightforward as you might have expected… I’ve had to write code to do it in a number of apps, and I eventually got tired of doing it again over and over, so I wrote a library that attempts to cover all use cases. I called it HumanBytes, for reasons that should be obvious… It is also available as a NuGet package.

    Its usage is quite simple. It’s based on a class named ByteSizeFormatter, which has a few properties to control how the value is rendered:

    var formatter = new ByteSizeFormatter
        Convention = ByteSizeConvention.Binary,
        DecimalPlaces = 1,
        NumberFormat = "#,##0.###",
        MinUnit = ByteSizeUnit.Kilobyte,
        MaxUnit = ByteSizeUnit.Gigabyte,
        RoundingRule = ByteSizeRounding.Closest,
        UseFullWordForBytes = true,
    var f = new FileInfo("TheFile.jpg");
    Console.WriteLine("The size of '{0}' is {1}", f, formatter.Format(f.Length));

    In most cases, though, you will just want to use the default settings. You can do that easily with the Bytes extension method:

    var f = new FileInfo("TheFile.jpg");
    Console.WriteLine("The size of '{0}' is {1}", f, f.Length.Bytes());

    This method returns an instance of the ByteSize structure, whose ToString method formats the value using the default formatter. You can change the default formatter settings globally through the ByteSizeFormatter.Default static property.

    A note on localization

    Not all languages use the same symbol for “byte”, and obviously the word “byte” itself is different across languages. Currently the library only supports English and French; if you want your language to be supported as well, please fork, add your translation, and make a pull request. There are only 3 terms to translate, so it shouldn’t take long Winking smile.

    Posted in Libraries. Tags: , , . No Comments »

    Passing parameters by reference to an asynchronous method

    Very poorPoorAverageGoodExcellent (2 votes) 

    Asynchrony in C# 5 is awesome, and I’ve been using it a lot since it was introduced. But there are few annoying limitations; for instance, you cannot pass parameters by reference (ref or out) to an asynchronous method. There are good reasons for that; the most obvious is that if you pass a local variable by reference, it is stored on the stack, but the current stack won’t remain available during the whole execution of the async method (only until the first await), so the location of the variable won’t exist anymore.

    However, it’s pretty easy to work around that limitation : you only need to create a Ref<T> class to hold the value, and pass an instance of this class by value to the async method:

    async void btnFilesStats_Click(object sender, EventArgs e)
        var count = new Ref<int>();
        var size = new Ref<ulong>();
        await GetFileStats(tbPath.Text, count, size);
        txtFileStats.Text = string.Format("{0} files ({1} bytes)", count, size);
    async Task GetFileStats(string path, Ref<int> totalCount, Ref<ulong> totalSize)
        var folder = await StorageFolder.GetFolderFromPathAsync(path);
        foreach (var f in await folder.GetFilesAsync())
            totalCount.Value += 1;
            var props = await f.GetBasicPropertiesAsync();
            totalSize.Value += props.Size;
        foreach (var f in await folder.GetFoldersAsync())
            await GetFilesCountAndSize(f, totalCount, totalSize);

    The Ref<T> class looks like this:

    public class Ref<T>
        public Ref() { }
        public Ref(T value) { Value = value; }
        public T Value { get; set; }
        public override string ToString()
            T value = Value;
            return value == null ? "" : value.ToString();
        public static implicit operator T(Ref<T> r) { return r.Value; }
        public static implicit operator Ref<T>(T value) { return new Ref<T>(value); }

    As you can see, it’s pretty straightforward. This approach can also be used in iterator blocks (i.e. yield return), that also don’t allow ref and out parameters. It also has an advantage over standard ref and out parameters: you can make the parameter optional, if for instance you’re not interested in the result (obviously, the callee must handle that case appropriately).

    Easy unit testing of null argument validation

    Very poorPoorAverageGoodExcellent (No Ratings Yet) 

    When unit testing a method, one of the things to test is argument validation : for instance, ensure that the method throws a ArgumentNullException when a null argument is passed for a parameter that isn’t allowed to be null. Writing this kind of test is very easy, but it’s also a tedious and repetitive task, especially if the method has many parameters… So I wrote a method that automates part of this task: it tries to pass null for each of the specified arguments, and asserts that the method throws an ArgumentNullException. Here’s an example that tests a FullOuterJoin extension method:

    public void FullOuterJoin_Throws_If_Argument_Null()
        var left = Enumerable.Empty<int>();
        var right = Enumerable.Empty<int>();
            () => left.FullOuterJoin(right, x => x, y => y, (k, x, y) => 0, 0, 0, null),
            "left", "right", "leftKeySelector", "rightKeySelector", "resultSelector");

    The first parameter is a lambda expression that represents how to call the method. In this lambda, you should only pass valid arguments. The following parameters are the names of the parameters that are not allowed to be null. For each of the specified names, AssertThrowsWhenArgumentNull will replace the corresponding argument with null in the provided lambda, compile and invoke the lambda, and assert that the method throws a ArgumentNullException.

    Using this method, instead of writing a test for each of the arguments that are not allowed to be null, you only need one test.

    Here’s the code for the TestHelper.AssertThrowsWhenArgumentNull method (you can also find it on Gist):

    using System;
    using System.Linq;
    using System.Linq.Expressions;
    using NUnit.Framework;
    namespace MyLibrary.Tests
        static class TestHelper
            public static void AssertThrowsWhenArgumentNull(Expression<TestDelegate> expr, params string[] paramNames)
                var realCall = expr.Body as MethodCallExpression;
                if (realCall == null)
                    throw new ArgumentException("Expression body is not a method call", "expr");
                var realArgs = realCall.Arguments;
                var paramIndexes = realCall.Method.GetParameters()
                    .Select((p, i) => new { p, i })
                    .ToDictionary(x => x.p.Name, x => x.i);
                var paramTypes = realCall.Method.GetParameters()
                    .ToDictionary(p => p.Name, p => p.ParameterType);
                foreach (var paramName in paramNames)
                    var args = realArgs.ToArray();
                    args[paramIndexes[paramName]] = Expression.Constant(null, paramTypes[paramName]);
                    var call = Expression.Call(realCall.Method, args);
                    var lambda = Expression.Lambda<TestDelegate>(call);
                    var action = lambda.Compile();
                    var ex = Assert.Throws<ArgumentNullException>(action, "Expected ArgumentNullException for parameter '{0}', but none was thrown.", paramName);
                    Assert.AreEqual(paramName, ex.ParamName);

    Note that it is written for NUnit, but can easily be adapted to other unit test frameworks.

    I used this method in my Linq.Extras library, which provides many additional extension methods for working with sequences and collections (including the FullOuterJoin method mentioned above).