An example of using an expression is as follows:
var stream = new MemoryStream(); using(stream) { //Perform operations with stream here. } //Stream is now disposed.
Here, the stream variable is declared outside the using, but wrapped by the using. It will then dispose the stream variable upon completion.
This isn't a very common pattern, but it is useful for where you may need to perform other operations on the resource after it has been disposed of.
This can be used with method calls, etc. Essentially any expression that evaluates to a type of IDisposable can be used. Generally, not having access to the IDisposable inside the using statement isn't that useful.
The only scenario where I have seen it used this way is in ASP.NET MVC with the form helpers such as.
@using(Html.BeginForm()) { @Html.TextBox("Name"); }
var res = GetResource(); using (res) { ... }This style is not recommended becauseresis still in scope after theusingblock, but has been disposed.using (GetResource())orusing (flag ? resA : resB)etc.