Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I using the "using" statement correctly?

I would like to know whether my use of using is correct. In the using statmement, I am deciding whether or not the image should be used in the game.

Image imageOfEnemy;
using(imageOfEnemy=Bitmap.FromFile(path))
{
   // some stuff with the imageOfEnemy variable

}

From my understanding, I do not need to call Dispose now.

like image 288
Tray13 Avatar asked Sep 05 '26 16:09

Tray13


2 Answers

Yes, you are using it correctly. You don't need to dispose explicitly the Bitmap as it wil be disposed by the using statement. You could simplify even further by declaring the image variable inside:

using(var imageOfEnemy = Bitmap.FromFile(path))
{
    // some stuff with the imageOfEnemy variable
}

which is roughly equivalent to:

{
    var imageOfEnemy = Bitmap.FromFile(path);
    try 
    {
        // some stuff with the imageOfEnemy variable
    }
    finally 
    {
        ((IDisposable)imageOfEnemy).Dispose();
    }
}
like image 121
Darin Dimitrov Avatar answered Sep 07 '26 07:09

Darin Dimitrov


using is a shorthand statement for IDisposable objects to simplify the try-finally block, with Dispose in the finally block.

http://msdn.microsoft.com/en-us/library/yh598w02.aspx

So yes, you don't have to call Dispose 'manually' in this case.

using System;
namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var example = new Example())
            {
                //do something
            }
        }
    }

    class Example : IDisposable
    {

        public void Dispose()
        {
            //Do something
        }
    }
}

the Main method will be this in MSIL:

.method private hidebysig static void Main(string[] args) cil managed
{
    .entrypoint
    .maxstack 2
    .locals init (
        [0] class ConsoleApplication3.Example example,
        [1] bool CS$4$0000)
    L_0000: nop 
    L_0001: newobj instance void ConsoleApplication3.Example::.ctor()
    L_0006: stloc.0 
    L_0007: nop 
    L_0008: nop 
    L_0009: leave.s L_001b
    L_000b: ldloc.0 
    L_000c: ldnull 
    L_000d: ceq 
    L_000f: stloc.1 
    L_0010: ldloc.1 
    L_0011: brtrue.s L_001a
    L_0013: ldloc.0 
    L_0014: callvirt instance void [mscorlib]System.IDisposable::Dispose()
    L_0019: nop 
    L_001a: endfinally 
    L_001b: nop 
    L_001c: ret 
    .try L_0007 to L_000b finally handler L_000b to L_001b
}

You can see the try-finally handler and the Dispose call even if you are new to MSIL.

like image 28
Peter Porfy Avatar answered Sep 07 '26 06:09

Peter Porfy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!