Just as the community got used to using using...

I think that the using statement in C# is a really nice invention. It’s an excellent syntactic sugar for handling IDisposables in a correct fashion. I get the impression that it took a while for the community to make it part of their daily routine to use it and now, as we are coming there, there is a shift towards asynchronous programming that may render the using block useless (or at least temporarily so, I hope to see C# 5 handling this in conjunction with the await keyword).

Recently I ran into a situation where the asynchronous approach made the using block less ideal. I still like the simplicity of it, so I started thinking about creating a pattern that would only mean a minor shift away from it; an asynchronous using block. This pattern should ideally be close enough to a regular using block so that you could make some sort of (probably regex-based) search replace approach for moving to the asynchronous version.

This blog post is also written in a way so that it follows the thought process that I went through when making the code.

Executive summary

If you don’t want to wade through the whole thought process of creating the asynchronous using approach along with tests, skip ahead to the solution.

Let’s start from the beginning

As a starting point, let’s say that you a class that can save its contents to a Stream, and that you have some code doing that, nicely wrapped in a using block:

using (Stream stream = File.OpenWrite(@”\\slowserver\share\file.txt”))
{
    someClass.Save(stream);
}

...and then you figure that "nah, blocking this thread for that save... on that slow server… no thanks", and as it happens there is an asynchronous version of the method returning a Task:

using (Stream stream = File.OpenWrite(@”\\slowserver\share\file.txt”))
{
    // Disclaimer: in real code you would want to get hold of that Task, observing
    // any errors on it and handle them. This is omitted from the code samples for
    // the sake of focusing on the topic at hand.
    someClass.SaveAsync(stream);
}

And now you have a bug instead. You create a Stream, pass it to the asynchronous method and then immediately dispose the stream. When the save method comes around to writing to the Stream, it's is quite likely already disposed, and you will have an exception.

I imagined that rewriting the code to work with Task but without using blocks could look like this:

Stream stream = File.OpenWrite(@”\\slowserver\share\file.txt”);

someClass.SaveAsync(stream)
    .ContinueWith(task => 
    {
        if (stream != null)
        {
            stream.Dispose();
        }
    });

Simply put, this code consists of three things:

  1. Acquire the IDisposable resource
  2. Perform some action that uses that resource
  3. Dispose the resource

The goal was to encapsulate these steps into a reusable form.

Setting the stage

First I needed to figure out how to test this. The first test I wanted to write was one that used a regular using block, and that waited for the task to finish within the block. The reason was that this is a known and simple scenario where I knew the expected outcome.

[Test]
public void NormalUsingBlock_WaitForTask()
{
    var instance = new Disposable();
    using (instance)
    {
        Task.Factory.StartNew(() =>
        {
            if (instance.IsDisposed)
            {
                throw new ObjectDisposedException("The Disposable is already disposed.");
            }
        }).Wait();
    }
    Assert.IsTrue(instance.IsDisposed);
}

This is the bare minimum that I needed for the test: a class that implements IDisposable that contains a property indicating whether it’s disposed or not, and a task using that resource. If the resource is disposed before the tasks executes, an exception is thrown. Finally I verify that the resource has indeed become disposed.

The implementation of the Disposable class is the simplest possible:

public class Disposable : IDisposable
{
    public void Dispose()
    {
        IsDisposed = true;
    }

    public bool IsDisposed { get; private set; }
}

There, with that in place the first test passed as it should. Time for the next test. Now I wanted to create a scenario where the test consistently would fail if not waiting for the task within the using block; a test that would guarantee that the resource is disposed before the task tries to use it. This could probably be achieved by putting a Thread.Sleep inside the task, before checking the IsDisposed property, but Thread.Sleep is a thin ice to walk on. It can give you a reasonable chance that Dispose is invoked while sleeping, but there is no such guarantee. So I decided to use a wait handle instead, so that I can signal things in a deterministic way. I also decided to use an event to get notified when the object was disposed.

[Test]
public void NormalUsingBlock_AsyncFails()
{
    // arrange
    var instance = new Disposable();
    ManualResetEvent mre = new ManualResetEvent(false);
    EventHandler disposedHandler = (s, e) => mre.Set();
    instance.Disposed += disposedHandler;

    // act
    Task task;
    using (instance)
    {
        task = Task.Factory.StartNew(() =>
        {
            mre.WaitOne();
            if (instance.IsDisposed)
            {
                throw new ObjectDisposedException("The Disposable is already disposed.");
            }
        });
    }

    // assert
    Assert.Throws<AggregateException>(() => task.Wait());

    // clean up
    instance.Disposed -= disposedHandler;
}

For this to work I needed to add the event code to the Disposable class, and raise the event when Dispose was invoked:

public class Disposable : IDisposable
{
    public event EventHandler Disposed;

    protected void OnDisposed(EventArgs e)
    {
        EventHandler handler = Disposed;
        if (handler != null) handler(this, e);
    }

    public void Dispose()
    {
        IsDisposed = true;
        OnDisposed(EventArgs.Empty);
    }

    public bool IsDisposed { get; private set; }
}

Now I was in a position where I could verify that a regular using block would dispose my resource as expected, and also that a regular using block could dispose my resource before the task was finished, if I didn’t wait for the task inside the block. Perfect, now I had the tools to create the asynchronous using functionality.

Making it work

I realized at this point that I would needed to write a few different tests to make sure things work as I wanted them to. I also realized setting up the tests will be quite similar for each test. Since I am not a huge fan of copy/pasting large portions of code that does the same thing, I decided to encapsulate the task creation into a method:

private static Task GetTask(Disposable disposable, WaitHandle waitHandle = null)
{
    return Task.Factory.StartNew(() =>
    {
        if (waitHandle != null)
        {
            // Wait for a signal. This enables us to wait in a deterministic
            // way before checking the disposed state.
            waitHandle.WaitOne();
        }

        if (disposable.IsDisposed)
        {
            throw new ObjectDisposedException("The Disposable is already disposed.");
        }
    });
}

There, now that I had a disposable resource and an asynchronous consumer, I could write a test for an asynchronous approach to using disposable resources.

As mentioned before, there are three steps involved; acquiring the disposable resource, invoking some code that uses the resource and finally disposing the resource. Disposing the resource is done in the exact same way regardless of what resource it is. This is also reflected by the regular using block; you as a developer never supply any code for that part. The other two however must be supplied by the developer.

With that in mind, I thought out the following approach:

[Test]
public void Using_WithTask()
{
    // act
    var task = Async.Using(() => new Disposable(),
        disposable => 
        {
            return GetTask(disposable);
        });
    task.Wait();

    // assert
    Assert.IsFalse(task.IsFaulted);
}

I imagined making an Async class (for functionality facilitating some async headaches), containing a Using method that takes two parameters; a Func that produces a disposable resource, and a Func taking such a resource as input and returning a task. Since I didn’t want to be forced to unnecessary type casting, I decided to make the method generic.

Do you see the similarity of this code construction, compared to the regular using block? First we have a statement that will produce an IDisposable object of some kind, then we have a code block where we can use that object, and in this case we call the variable holding the reference to that object disposable. We use it for whatever it’s needed for, and then we return a Task (so that we can chain ContinueWith calls on it, check the result, observe exceptions and so on).

By refactoring the code sample from above (that showed using a disposable resource with tasks, but without the help of any syntactic sugar or helper methods), I came to this implementation:

public static Task Using<T>(
    Func<T> disposableAcquisition, Func<T, Task> taskFunc)
    where T : IDisposable
{
    T instance = disposableAcquisition();

    return taskFunc(instance)
        .ContinueWith(task =>
        {
            if (!ReferenceEquals(instance, null))
            {
                instance.Dispose();
            }
            return task;
        });
}

…and the test passed! There it was, the first incarnation of the async using method.

My next step would be to create a version of the async using block for when I would want to execute any piece of code inside an asynchronous using block, but that where the code does not necessarily return a Task object. It could be that you just want to push some work off the UI thread to keep the UI responsive, for instance.

As always, test comes first. By now I realized that the structure of the following tests would be quite similar to the first one, in terms of necessary setups and such, so next step was to move some setup and teardown work to separate methods, moving some noise away from the tests:

[TestFixture]
public class AsyncTests
{
    private Disposable disposableInstance;
    private ManualResetEvent manualResetEvent;

    [SetUp]
    public void Setup()
    {
        disposableInstance = new Disposable();
        manualResetEvent = new ManualResetEvent(false);
        disposableInstance.Disposed += DisposedHandler;
    }

    private void DisposedHandler(object s, EventArgs e)
    {
        manualResetEvent.Set();
    }

    // the tests go here (removed for brevity)
}

Now the disposable class instance was created with all necessary wiring set up automatically before each tests was executed, so that code did not need to reside inside each test. I like how that makes the test code more focused on its purpose. So with that in place, I could make a simple test to make sure that I could execute code that does not involve a Task in the same sort of asynchronous manner:

[Test]
public void Using_WithAction()
{
    // act
    var task = Async.Using(() => disposableInstance,
        disposable =>
        {
            // wait for the wait handle to be signaled
            manualResetEvent.WaitOne();

            if (disposable.IsDisposed)
            {
                throw new ObjectDisposedException("The Disposable is already disposed.");
            }
        });

    manualResetEvent.Set();
    task.Wait();

    // assert
    Assert.IsFalse(task.IsFaulted);
}

Same approach as before, only this time without a Task. The code will throw an exception if the disposable object is disposed prior to the wait handle being signaled. The wait handle is signaled after the Async.Using method call returns. Finally the test verifies that the disposable resource is properly disposed, and that the resulting Task does not fail.

"Wait a minute..., didn't you just say that this test scenario did not involve any Task!?"  Yes I did, and I meant it ;-) The code that executes asynchronously within the block does not use or return any Task, but the construct itself, the Async.Using method, wraps the whole thing in a new Task that is returned so that your code can wait for it, chain other operations to follow on it, observe exceptions and so on. Let's looks at the implementation and it will be more clear:

public static Task Using<T>(
    Func<T> disposableAcquisition, Action<T> action)
    where T : IDisposable
{
    T disposable = disposableAcquisition();

    return Task.Factory.StartNew(() => action(disposable))
        .ContinueWith(task =>
        {
            if (!ReferenceEquals(disposable, null))
            {
                disposable.Dispose();
            }
            return task;
        });
}

As you can see, it's very similar to the one we created first, but it creates a new Task that invokes the Action<T> delegate that is passed into the method, and returns that Task object.

At this point, the Async class started to fulfill the needs that I had, so I didn't do much more work on it, but there are of course a lot more that code be done with it.

The final Async class

Here is the the "full" Async class, should you want to use it. I say "full", since it is in no way complete; there are many overloads that you could wish for, supporting Action and Func delegates with various number of type arguments, for instance.

You can also grab a full Visual Studio solution (containing both the class and some tests) from my BitBucket repository.

/*
 * This file is created by Fredrik Mörk, twitter.com/fmork
 *
 * It comes without any warranty of any kind. Use it at your own risk.
 * But feel free to do so.
 */

using System;
using System.Threading.Tasks;

namespace Alcedo.AsyncUsing
{
    /// <summary>
    /// Contains functionality for asynchronous operations.
    /// </summary>
    public static class Async
    {
        /// <summary>
        /// Emulates a using block with asynchronous support.
        /// </summary>
        /// <typeparam name="T">A type that implements <see cref="IDisposable"/></typeparam>
        /// <param name="disposableAcquisition">A <see cref="Func{TResult}"/> that gets
        /// an object that implements <see cref="IDisposable"/>.</param>
        /// <param name="action">The action to perform asynchronously.</param>
        public static Task Using<T>(
            Func<T> disposableAcquisition, Action<T> action)
            where T : IDisposable
        {
            T disposable = disposableAcquisition();

            return Task.Factory.StartNew(() => action(disposable))
                .ContinueWith(task =>
                {
                    if (!ReferenceEquals(disposable, null))
                    {
                        disposable.Dispose();
                    }
                    return task;
                });
        }

        /// <summary>
        /// Emulates a using block with asynchronous support.
        /// </summary>
        /// <typeparam name="T">A type that implements <see cref="IDisposable"/></typeparam>
        /// <param name="disposableAcquisition">A <see cref="Func{TResult}"/> that gets
        /// an object that implements <see cref="IDisposable"/>.</param>
        /// <param name="taskFunc">A <see cref="Func{T,Task}"/> that
        /// uses the <see cref="IDisposable"/> object.</param>
        /// <returns></returns>
        public static Task Using<T>(
            Func<T> disposableAcquisition, Func<T, Task> taskFunc)
            where T : IDisposable
        {
            T instance = disposableAcquisition();

            return taskFunc(instance)
                .ContinueWith(task =>
                {
                    if (!ReferenceEquals(instance, null))
                    {
                        instance.Dispose();
                    }
                    return task;
                });
        }

        /// <summary>
        /// Emulates a using block with asynchronous support for a task that returns a result.
        /// </summary>
        /// <typeparam name="T">A type that implements <see cref="IDisposable"/></typeparam>
        /// <typeparam name="TResult">The type or the result produced by the task.</typeparam>
        /// <param name="disposableAcquisition">A <see cref="Func{TResult}"/> that gets
        /// an object that implements <see cref="IDisposable"/>.</param>
        /// <param name="taskFunc">A <see cref="Func{T,Task}"/> that uses
        /// the <see cref="IDisposable"/> object.</param>
        public static Task<TResult> Using<T, TResult>(
            Func<T> disposableAcquisition, Func<T, Task<TResult>> taskFunc)
            where T : IDisposable
        {
            T instance = disposableAcquisition();

            return taskFunc(instance)
                .ContinueWith(task =>
                {
                    if (!ReferenceEquals(instance, null))
                    {
                        instance.Dispose();
                    }
                    return task.Result;
                });
        }
    }
}

kick it on DotNetKicks.com


I am working for a great consultancy company called Diversify, located in Sweden. We are hiring skilled .NET developers. If you are interested, don't hesitate to get in touch with me.

This article deals with the basic concept of bitmasks, something that still causes some confusion at times. I assume you are familiar with C# enums in general and aware of how they represent numerical values and such. If you feel uncertain about this, please read about enums at MSDN first, and then continue here.

- Hey, I’d like a value that is a combination of A and B.
- Sure, here it is: ‘A or B’
- Um... I think you got that wrong… shouldn’t it be ‘A and B’?

I have noticed that using bitmasks is something seems quite confusing for many developers. One source of that confusion might be the name of the operators used when dealing with them. It simply seems backwards for many that the ‘OR’ operator is used for producing a combined bitmask value, while the ‘AND’ operator is used for pulling out a single value from a bitmask. One reason might be that the meaning of and and or in the spoken language seem (but really is not) sort of opposite the meaning when dealing with bitwise operations in programming, where we use the bitwise OR operator (| in C#) for combining values into a bitmask, and the bitwise AND operator (&) to pull out a single value from a bitmask.

The typical use of bitmasks in .NET is with flags enumerations. An example of such an enumeration from the base class library is FileAttributes:

[Flags]
public enum FileAttributes
{
    Archive = 32,
    Compressed = 2048,
    Device = 64,
    Directory = 16,
    Encrypted = 16384,
    Hidden = 2,
    Normal = 128,
    NotContentIndexed = 8192,
    Offline = 4096,
    ReadOnly = 1,
    ReparsePoint = 1024,
    SparseFile = 512,
    System = 4,
    Temporary = 256
}

Note: for the sake of simplicity I have removed a couple of attributes from the declaration that is of no importance for the content of this article.

There are two characteristics that are important in the declaration of this enum:

  • The Flags attribute
  • The values given to each member

The Flags attribute indicates for the compiler that the enum may be used as a bitmask, so it will allow bitwise operations on values of that type.

The sequence of values is also very important. If you sort the numbers, you will see that the used values are 1, 2, 4, 8, 16, 32, 64 and so on. All these are powers of two. By using that particular sequence of numbers, you ensure that any bitwise combination of values will produce a unique result (and the reason for this will become clear in a moment).

Let’s look at a code sample of using the FileAttributes enum:

File.SetAttributes(path, FileAttributes.System | FileAttributes.ReadOnly);

What does FileAttributes.System | FileAttributes.ReadOnly in the above code sample really mean? First, let’s look up the value for the members in the enum declaration.

[Flags]
public enum FileAttributes
{
    [...]
    ReadOnly = 1,
    System = 4,
    [...]
}

So, ReadOnly is 1 and System is 4. As you know, an enum represents values of the type int (unless otherwise stated). This means that we can cast any FileAttributes value to an int and get a numerical representation of the value. In our case (int)(FileAttributes.System | FileAttributes.ReadOnly) gives the value 5. You might think that this happened through a regular addition. After all, 4+1=5, right? Well, it’s not quite that simple. Consider the following sample:

[Flags]
public enum WierdEnum
{
    First = 5,
    Second = 5
}


Console.WriteLine((int)(WierdEnum.First | WierdEnum.Second));

The code above prints 5 and not 10, so obviously we are not talking about addition here. If we move back to our FileAttributes sample, we had two members with the values 4 and 1. Let’s examine what those values look like on the bit level (showing the lowest 8 bits of the int values):

bits for the values 4 and 1

Did you notice something special with those two values? In each value, exactly one bit was set to 1. Each bit represents a value that is a power of two. Here is an 8 bit number, showing the value of each bit.

Values for 8 lowest bits

As you see, if all 8 bits are set this represents the number 255, the largest number that can be stored in a byte.

The | operator will produce a value where each bit in the result becomes 1 if it is 1 in one or the other operand (or in both). In our case:

logical-OR

Now it should be quite clear why we use bitwise OR to combine values. Let’s move on to checking whether the value of a certain enum member is present in the bitmask.

Note that as of .NET 4, you can use the Enum.HasFlag method to determine whether a certain flag is present. For the purpose of examining the underlying mechanics, I will stick to the old fashioned way of doing it here.

Let’s say we have a method that returns a value indicating whether a file is ReadOnly or not:

public static bool FileIsReadOnly(string path)
{
    return (File.GetAttributes(path) & FileAttributes.ReadOnly) != 0;
}

Now we use the & operator instead. We take the FileAttributes value from the file (which may contain a combination of flags), and we perform a bitwise AND operation using that value and the flag we want to check (FileAttributes.ReadOnly). If the result is not zero, the flag is set. This works just like with the | operation described above, but with &, each bit in the result is 1 only if it is 1 in both operands. If the bit is 0 in one or both of the operands, the bit is 0 in the result as well.

Let's assume that the File.GetAttributes call returns FileAttributes.System | FileAttributes.ReadOnly (which we already determined corresponds to the int value 5), and we want to test for the ReadOnly flag (which has the value 1):

logical-AND

As you can see, only the lowest bit is 1 in both operands, so only that bit is 1 in the result. If we were instead to test for the flag FileAttributes.Hidden (having the int value 2), we would get this:

logical-AND-flag-not-set

…which should be expected; the flag value was FileAttributes.System | FileAttributes.ReadOnly, and FileAttributes.Hidden is not part of that value.

So in the end, using a bitwise or operation to combine values, and a bitwise and operation to split them up is not weird at all. Quite the contrary, it’s rather logical.


I am working for a great consultancy company called Diversify, located in Sweden. We are hiring skilled .NET developers. If you are interested, don't hesitate to get in touch with me.

Is stubbing time overkill? If it is required for your tests to be reliable, I would say no, it’s not overkill. In this text I will discuss why and how to stub time to make your coded tests break free from the constraints of time. Wish it was as easy to do outside of the code world as well…

I use the term stub here. I usually make the distinction between mocks and stubs, in that a stub simply returns a hard-coded response, while the mock will also register the interaction as such, so that the test can verify that the mock was indeed invoked.

An important part of writing tests is to always be aware of what it is that you are actually testing. One side effect of this is that you will need to fake anything that is not currently under test. For instance, if you have code that processes data from some data store, your test should fake the data store and feed hard-coded input to the processing code. This will give your test code at least three advantages:

  • It does not require extra dependencies on the data layer
  • It makes the test reliable since you always execute it using the exact same input
  • The tests will take less time to run

If you run your test on input that can change over time, the test may fail for two different reasons:

  • there is something wrong with the code that you are testing
  • your test is making a false assumption on the result based on the expected input

This is bad since you want reliable tests. The test should fail only if the code under test does not behave in an expected manner, not for any other reason.

In many cases this comes rather naturally in your code, since you may introduce various abstractions anyway, typically around your data access layer and similar. However, there is one obvious dependency that many systems have, but not many create an abstraction for: time.

Consider that you have a piece of code that validates whether a certain action is valid to perform, and that the rule is that it is OK to perform this action between noon and 6 PM. How do you create a test that tests this in a reliable manner, no matter at what time of day it is executed?

Let’s take it step by step:

[Test]
public void IsValid_Returns_True_At_5PM()
{
    ActionValidator dep = new ActionValidator();
    Assert.IsTrue(dep.IsValid());
}

public class ActionValidator
{
    public bool IsValid()
    {
        DateTime now = DateTime.Now;

        return now.Hour >= 12 && now.Hour < 18;
    }
}

As it happens, I wrote this at 5PM so the test passes as it should, but about one hour later it would fail. This is of course not a reliable test. It’s reliable in the same way as a broken watch; it will still show the correct time twice a day.

What we want here is an abstraction of time, so that we can represent any time of day, at any time of day. One way to do this is to change the IsValid method signature to accept a DateTime value as input and validate against that. However, this can create a class interface that is cluttered with parameters into methods, and that may be quite cumbersome to consume. A better approach would be to create an abstraction that can be injected into the types that need time related data:

public interface IDateTime
{
    DateTime Now { get; }
}


class SystemDateTime : IDateTime
{
    public DateTime Now
    {
        get { return DateTime.Now; }
    }
}


public class ActionValidator
{
    private readonly IDateTime dateTime;

    public ActionValidator() : this(new SystemDateTime()) { }
    public ActionValidator(IDateTime dateTime)
    {
        this.dateTime = dateTime;
    }
    public bool IsValid()
    {
        DateTime now = dateTime.Now;

        return now.Hour >= 12 && now.Hour < 18;
    }
}

Now we can inject an IDateTime provider into the ActionValidator, and have it perform its work. If no IDateTime is expiciltly injected, the ActionValidator will default to using SystemDateTime. But in order to drive our tests, let's create a fake one:

class DateTimeStub : IDateTime
{
    public DateTime NowValue { get; set; }
    public DateTime Now
    {
        get { return NowValue; }
    }
}

The fake provider has an extra property, NowValue. This enables us to set a hard-coded DateTime value that will be returned by the Now property. This way we can represent any time of day (and date) at any time, and write tests that repeatedly will test how our code behaves at that exact instant:

[Test]
public void IsValid_Returns_True_At_5PM()
{
    var dateTime = new DateTimeStub()
    {
        NowValue = new DateTime(2011, 3, 30, 17, 00, 00)
    };
    var actionValidator = new ActionValidator(dateTime);
    Assert.IsTrue(actionValidator.IsValid());
}

Of course, we want to make sure that it does not always return true, but that the validation fails for invalid times as well:

[Test]
public void IsValid_Returns_False_At_7PM()
{
    var dateTime = new DateTimeStub()
    {
        NowValue = new DateTime(2011, 3, 30, 19, 00, 00)

    };
    var actionValidator = new ActionValidator(dateTime);
    Assert.IsFalse(actionValidator.IsValid());
}

Now, while this is a very simple example, it points at something that I find quite important to think about when writing tests, and designing your code: be aware of what it is that you are actually testing. Only the code that you intend to test should be able to make the test fail. Antyhing else is an unwanted side effect.


I am working for a great consultancy company called Diversify, located in Sweden. We are hiring skilled .NET developers. If you are interested, don't hesitate to get in touch with me.

Without hesitation, let's just start off with a code sample. When running this program, what output would you expect?

using System;
namespace Alcedo.Demo
{
    class Base { }
    class Derived : Base { }

    class Worker
    {
        public virtual void Work(Derived param)
        {
            Console.WriteLine("Worker.Work(Derived)");
        }
    }

    class SpecializedWorker : Worker
    {
        public override void Work(Derived param)
        {
            Console.WriteLine("SpecializedWorker.Work(Derived)");
        }

        public void Work(Base param)
        {
            Console.WriteLine("SpecializedWorker.Work(Base)");
        }
    }

    class Program
    {
        public static void Main()
        {
            Derived param = new Derived();
            SpecializedWorker worker = new SpecializedWorker();
            worker.Work(param);
        }
    }   
}

Think about it for a while before reading on.

.

.

.

.

.

.

.

That should do. The output is SpecializedWorker.Work(Base). If that was what you expected (and you know why) you can stop reading here. If not, keep reading for the explanation.

The decision of what method to call can happen in one of two places; either it is done by the compiler, or it is done by the run-time. Well, the compiler is always involved, but in the case of virtual methods, it is ultimately the run-time that decides, based on the actual run-time types of the objects involved. That reasoning seems to indicate that the output of the program really ought to be SpecializedWorker.Work(Derived). After all, we invoke a method called Work on an object of the type SpecializedWorker, passing an object of the type Derived to it. Surely the run-time should have called SpecializedWorker.Work(Derived)?

It turns out the run-time is not even involved in the decision.

Given the code above, the compiler will make an attempt to decide what method to call. This follows a rather detailed specification (that you can read here: C# Language Specification, Method invocations).

In brief, it starts off by identifying all possible candidate methods. A method is a candidate if it:

  • Has the same name (in our case Work)
  • It is declared in the type (in our case SpecializedWorker) or one of its base types
  • It is not declared with the override modifier
At this point there are two candidates to choose from:
public virtual void Worker.Work(Derived)
public void SpecializedWorker.Work(Base)

OK, so at this point SpecializedWorker.Work(Derived param) is not in the candidate list any longer. In fact calls to override methods should never be; they are called as a result of overload resolution at run-time, not based on a decision of the compiler. It would still be called if the compiler decided on using the virtual Worker.Work(Derived) method. But the compiler does not choose the virtual method. Why?

The answer is found in the Method Invocations document linked above:

If N is applicable with respect to A (Section 7.4.2.1), then all methods declared in a base type of T are removed from the set.

According to the section linked above, a method is considered to be applicable if the number of arguments to the method is identical to the argument list in the call, and if there is an implicit conversion from each argument's type, to the corresponding argument of the method.

Both candidates meet this requirement; both have exactly one argument, and the type Derived can implicitly be converted to the argument type of each of the two methods. The result of the quoted text from the specification is that in this case the virtual Worker.Work(Derived) method will be removed from the list of candidates since it is declared in a base type of SpecializedWorker.

And now the list of candidates is reduced to one single method: SpecializedWorker.Work(Base).

kick it on DotNetKicks.com


I am working for a great consultancy company called Diversify, located in Sweden. We are hiring skilled .NET developers. If you are interested, don't hesitate to get in touch with me.