JR <an*******@discussions.microsoft.com> wrote:
What are the rules regarding ref parameters and interface types?
The reason I ask is that I found myself writing code like this several times:
if (something != null)
{
something.Dispose();
something = null;
}
So I had the "clever" idea of writing a routine like this:
public static void MyDispose(IDisposable disposable)
{
if (disposable != null)
{
disposable.Dispose();
disposable = null;
As it stands, this line is pointless.
}
}
I can pass variables of type IDisposable to this routine, but I cannot pass class
types that implement IDisposable. E.g. I wanted to do something like:
Bitmap MyBitmap = ....
...
MyDispose(MyBitmap);
You certainly should be able to do that.
It seems to me that the compiler should be able to figure out what I
want (i.e. pass my bitmap to the method, just like it does if its not
a ref parameter) then set MyBitmap to null. The compiler disagrees
with this plan, and gives an error.
Hang on - you *don't* have a ref parameter at the moment...
Is there any way to ahieve what I want?
Assuming that you meant:
public static void MyDispose(ref IDisposable disposable)
{
if (disposable != null)
{
disposable.Dispose();
disposable = null;
}
}
there's a very good reason why you can't do what you want - the
compiler doesn't know that your method doesn't look like this:
public static void MyDispose(ref IDisposable disposable)
{
disposable = new MemoryStream();
}
Your MyBitmap variable would then contain a reference to a
MemoryStream, which is definitely not a good thing!
You *could* adopt a pattern of:
MyBitmap = MyDispose(MyBitmap);
and make MyDispose always return null. However, to be honest, I would
personally just stick with the "using" construct for almost all uses of
IDisposable. I rarely find I need anything else, and it makes it *so*
much easier to get right.
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too