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)
Variables declared in
usingstatements are read-only;outandrefparameters aren’t. So you can do this:… but fundamentally you’re not using the fact that it’s a
refparameter anyway…It’s possible that you’ve misunderstood what
refreally means. It would be a good idea to read my article on parameter passing to make sure you really understand.