C# - Why can't I pass a class declared in a using statement as a reference type?

c#

Solution

Why is this?

Variables declared in `using` statements are read-only; `out` and `ref` parameters aren't. So you can do this:

DisposableInt theInt = new DisposableInt(1);
using (theInt)
{
    AddOne(ref theInt);
}

... but fundamentally you're not using the fact that it's a `ref` parameter anyway...

It's possible that you've misunderstood what `ref` really means. It would be a good idea to read my article on parameter passing to make sure you really understand.

Problem

Suppose I have the following disposable class and example code to run it: ``` public class DisposableInt : IDisposable { private int? _Value; public int? MyInt { get { return _Value; } set { _Value = value; } } public DisposableInt(int InitialValue) { _Value = InitialValue; } public void Dispose() { _Value = null; } } public class TestAnInt { private void AddOne(ref DisposableInt IntVal) { IntVal.MyInt++; } public void TestIt() { DisposableInt TheInt; using (TheInt = new DisposableInt(1)) { Console.WriteLine(String.Format("Int Value: {0}", TheInt.MyInt)); AddOne(ref TheInt); Console.WriteLine(String.Format("Int Value + 1: {0}", TheInt.MyInt)); } } } ``` Calling `new TestAnInt().TestIt()` runs just fine. However, if I change `TestIt()` so that `DisposableInt` is declared inside of the using statement like so: ``` public void TestIt() { // DisposableInt TheInt; using (DisposableInt TheInt = new DisposableInt(1)) { Console.WriteLine(String.Format("Int Value: {0}", TheInt.MyInt)); AddOne(ref TheInt); Console.WriteLine(String.Format("Int Value + 1: {0}", TheInt.MyInt)); } } ``` I get the following compiler error: ``` Cannot pass 'TheInt' as a ref or out argument because it is a 'using variable' ``` Why is this? What is different, other than the class goes out of scope and to the garbage collector once the `using` statement is finished? (and yeah, I know my disposable class example is quite silly, I'm just trying to keep matters simple)

Original source