There are two uses for the C# using keyword:
-
The using statement:
Defines a scope, outside of which an object or objects will be disposed.
using (TransactionScope transactionScope = new TransactionScope())
{
// ...
}
-
The using directive:
The using directive has two uses:
-
To permit the use of types in a namespace so you do not have to qualify the use of a type in that namespace:
-
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 = from s in ml
select s.ToUpper();
will expand into:
IEnumerable<string> qm = ml.Select<string>(delegate(string s)
{
return s.ToUpper();
});
And this query:
var qi = from s in 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 = from s in ml
select using(System.Linq.Enumerable) s.ToUpper();
Just like table hints on TSQL.