Yet Another Way for Using the "using" Keyword

There are two uses for the C# using keyword:

  1. The using statement:

    Defines a scope, outside of which an object or objects will be disposed.

    using (TransactionScope transactionScope = new TransactionScope())

    {

        // …

    }

  2. The using directive:

    The using directive has two uses:

    1. To permit the use of types in a namespace so you do not have to qualify the use of a type in that namespace:

      using System.Text;

    2. To create an alias for a namespace or a type:

      using Text = System.Text;

      using SB = System.Text.StringBuilder;

At the last MVP Global Summit, Mads dared the C# MVPs to came up with another way for using the using keyword.

Taking Mads on his dare, here is my proposal: use it on LINQ.

There is some kind of non-determinism (from the developer’s point of view) in the code generated from LINQ queries.

Let’s take, for example, this class:

public class MyList<T> : List<T>

{

    public IEnumerable<T> Select<TResult>(Func<T, TResult> selector)

    {

        return null;

    }

}

Let’s take an instance of this class and reference it with two variable of different types:

MyList<string> ml = new MyList<string>() { “one”, “two”, “three” };

IList<string> il = ml;

The way the C# compiler expands queries depends on the variable being used.

This query:

var qm = fromin ml

         select s.ToUpper();

will expand into:

IEnumerable<string> qm = ml.Select<string>(delegate(string s)

    {

        return s.ToUpper();

    });

And this query:

var qi = fromin il

         select s.ToUpper();

will expand into:

IEnumerable<string> qi = System.Linq.Enumerable.Select<string, string>(il, delegate(string s)

    {

        return s.ToUpper();

    });

What if I wanted to explicitly use System.Ling.Enumerable.Select on ml but using the query syntax?

A nice way to do it would be:

var qm = fromin ml

         select using(System.Linq.Enumerable) s.ToUpper();

Just like table hints on TSQL.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>