Posts tagged delegate

Extension method of the day: Inline using() { } block in C#

Linq-to-SQL is our ORM of choice until the Entity Framework matures – and in our projects we use a factory method to get a new reference to our database data context. Here’s what I mean:

var db = Database.GetDataContext();


The DataContext class implements IDisposable, which means that (usually) it should be wrapped in an using block:

using (var db = Database.GetDataContext())
{
    ... code that uses the database here ...
}

We discovered that we frequently have one liners inside the using block, and in most of these cases, we just return some quick value from the database.

This made me think if there was something I could do about this to make it into a more compact construct. The result is an extension method that lets me do all of this on one line, while also taking care of object disposal.

Introducing <IDisposable>.Using() extension method:

int userCount = Database.GetDataContext().Using(db => db.Users.Count()); // get a quick user count


Of course, this applies to any object implementing IDisposable, not just Linq-to-SQL – so it has lots of possible uses. Here’s another example:


foreach (string file in Directory.GetFiles(@"C:\TextFiles", "*.txt"))
{

    string firstLine = new StreamReader(file).Using(f => f.ReadLine());
    Console.WriteLine(firstLine);
}

We’re reading the first line of every file and making sure the file gets closed immediately afterwards. The extension method takes care of disposing the StreamReader, and allows you to focus on the functionality rather than the implementation.

That’s what functional programming is all about!

Extension method follows:

public static class DisposableExtensions
{
   /// <summary>
   /// Runs a delegate on the specified <see cref="IDisposable"/> and returns its value.
   /// </summary>
   /// <typeparam name="T">Type of the object implementing <see cref="IDisposable"/></typeparam>
   /// <typeparam name="TOut">The type of the return value.</typeparam>
   /// <param name="disposable">The object implementing <see cref="IDisposable"/>.</param>
   /// <param name="func">A delegate that takes <paramref name="disposable"/> as a parameter and returns a value.</param>
   /// <returns>Value returned by <paramref name="func"/> delegate.</returns>
   public static TOut Using<T, TOut>(this T disposable, Func<T, TOut> func) where T : IDisposable
   {
       using (disposable)
       {
           return func(disposable);
       }
   }

   /// <summary>
   /// Runs a delegate on the specified <see cref="IDisposable"/> and does not return anything.
   /// </summary>
   /// <typeparam name="T">Type of the object implementing <see cref="IDisposable"/></typeparam>
   /// <param name="disposable">The object implementing <see cref="IDisposable"/>.</param>
   /// <param name="action">A delegate that takes <paramref name="disposable"/> as a parameter.</param>
   public static void Using<T>(this T disposable, Action<T> action) where T : IDisposable
   {
       using (disposable)
       {
           action(disposable);
       }
   }
}

Beware of the Lazy<T> .NET 4.0 type. The closure trap.

The System.Lazy<T> type in the new .NET 4.0 framework came to my attention recently. This type is not at all revolutionary. In fact, everyone could have written it themselves in under 10 lines of code going as far back as the .NET 2.0 framework.

Some less experienced programmers won’t realize however, that deferring the call to a delegate could have nasty side effects.

Consider the following code snippet:

static void Main(string[] args)
{
    List<Lazy<string>> lazyInit = new List<Lazy<string>>();
    for (char letter = 'A'; letter <= 'Z'; letter++)
    {
        var lazy = new Lazy<string>(() => letter.ToString());
        lazyInit.Add(lazy);
    }
    foreach (var lazy in lazyInit)
    {
        Console.Write(lazy.Value);
    }
    Console.ReadLine();
}

The code is pretty straight forward, but what gets printed here? Would you think it’s the alphabet? You would be very wrong.

image

The output is exactly ‘ZZZZZZZZZZZZZZZZZZZZZZZZZ’. Go ahead, run it yourself if you don’t trust me.

To understand why this happens, you need to understand how closures work.

In the constructor to the Lazy<> class, you’re passing in a delegate, in the form of a lambda. This delegate captures the letter variable (attention, not its value at the time of the call, but the variable as a whole) and creates a closure class around it behind the scenes. This may be counter-intuitive to the average programmer.  For further information on what happens behind the scenes with captured variables and closures, read this great post by Marc Gravell.

This is not specific behavior of the new Lazy<T> class, it’s what happens every time a delegate is stored for deferred execution.

If you rewrite the code without deferred execution, you’ll see that the problem doesn’t manifest itself:

static void Main(string[] args)
{
    for (char letter = 'A'; letter <= 'Z'; letter++)
    {
        var lazy = new Lazy<string>(() => letter.ToString());
        Console.Write(lazy.Value);
    }
    Console.ReadLine();
}
// Output: ABCDEFGHIJKLMNOPQRSTUVWXYZ

Same delegate is being used, but it is executed immediately. The output is now the complete English alphabet, as you would expect.

This isn’t very useful however, We’ve completely thrown away the advantages of the Lazy<T> class and we might as well not be using it.

So, how can we fix it? We need to use an intermediary variable inside the body of the for loop that is simply a copy of the outer variable. The inner variable’s scope is unique to each loop iteration, so it matters a whole lot where you define your variables.

Fixed code:

static void Main(string[] args)
{
    List<Lazy<string>> lazyInit = new List<Lazy<string>>();

    // char letter2; // <- for the sake of exercise, uncomment this line and remove the ‘char’ keyword from the initialization of the letter2 variable inside the for loop below. the ‘bug’ will manifest itself again
    for (char letter = 'A'; letter <= 'Z'; letter++)
    {
        char letter2 = letter; // value re-captured in inner block (remove ‘char’ keyword and uncomment line above to see the ‘bug’ manifest itself again)
        var lazy = new Lazy<string>(() => letter2.ToString());
        lazyInit.Add(lazy);
    }
    foreach (var lazy in lazyInit)
    {
        Console.Write(lazy.Value);
    }
    Console.ReadLine();
}

One tool that can automatically check for this condition so you can avoid headaches later is JetBrain’s Resharper. With Resharper installed, you’d see a warning underneath () => letter.ToString() which spells ‘Access to modified closure’ and suggests the same fix I described in this blog post.

If anyone’s interested in seeing how the same Lazy<T> class could be implemented in .NET 2.0 and up, leave a comment and I’ll post it here!