5

I want to understand the difference between

public DataTable ExectNonActQuery(string spname, SqlCommand command)
{
    using (DataTable dt = new DataTable())
    {
        cmd = command;
        cmd.Connection = GetConnection();
        cmd.CommandText = spname;
        cmd.CommandType = CommandType.StoredProcedure;
        da.SelectCommand = cmd;
        da.Fill(dt);
        return (dt);
    }
}

and

public DataTable ExectNonActQuery(string spname, SqlCommand command)
{
    DataTable dt = new DataTable();
    cmd = command;
    cmd.Connection = GetConnection();
    cmd.CommandText = spname;
    cmd.CommandType = CommandType.StoredProcedure;
    da.SelectCommand = cmd;
    da.Fill(dt);
    return (dt);
    }
}

I actually want to understand what is the benefit of creating a new object using "using" instead of creating it directly like this

DataTable dt = new DataTable();
Raj Ranjhan
  • 3,869
  • 2
  • 19
  • 29
kashif
  • 3,713
  • 8
  • 32
  • 47
  • 8
    Have you read the documentation on [`using`](http://msdn.microsoft.com/en-us/library/yh598w02(v=vs.80).aspx)? If so, what are your questions? – Damien_The_Unbeliever Apr 28 '12 at 16:21
  • For a DataTable the difference is zero. But a DataTable is one of the rare exceptions in this. – H H Apr 28 '12 at 16:22

6 Answers6

16

Your first example is incorrect: using(var ...) ensures that IDisposable.Dispose is called on the variable declared inside using upon exiting. Therefore your first example returns a disposed object, which is almost certainly wrong.

In general, the using block is roughly equivalent to this:

var x = new MyDisposable();
try {
    // Do something with x
} finally {
    x.Dispose();
}

Since this is a very common pattern in C#, a special syntax is provided for your convenience.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
11

using guarantees that the object is disposed at the end of the using statement

you could call .Dispose() manually instead, but with using, it will be disposed even if you throw an exception

And you are protected from your own mistakes, such as forgetting to call .Dispose, or reassigning the variable before calling Dispose on it.

It's all in the documentation:

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

Edit: also, as dasblinkenlight explains in the other answer, disposing an object as you return it from a function is a bad idea

However, in the special case of DataTable, DataSet and DataView you do not really need to dispose those objects anyway, so in this particular example it is safe to ignore that DataTable is an IDisposable. Moreover, since DataTable's .Dispose() method explicitely does nothing (Finalization is suppressed) your first example should actually work despite returning a disposed object.

See Should I Dispose() DataSet and DataTable?

So in your particular example the practical differences are probably zero.

It is still generally good practise to wrap IDisposables with Using statement wherever practical. (if an object has to be constructed inside a function and then accessed outside that function this is not possible.)

Community
  • 1
  • 1
HugoRune
  • 13,157
  • 7
  • 69
  • 144
  • 1
    what do you mean by disposed brother?? – kashif Apr 28 '12 at 16:22
  • can you tell me what benefit will I get If I use the first Example of my question instead of 2nd – kashif Apr 28 '12 at 16:24
  • @kashif: see [IDisposable](http://msdn.microsoft.com/en-us/library/system.idisposable.aspx) Also see dasblinkenlight's answer on what you get in the first example. nothing good in this case – HugoRune Apr 28 '12 at 16:33
4
using (DataTable dt = new DataTable())

is equal to

DataTable dt = new DataTable();
try
{
}
finally 
{
    if(dt != null)
        dt.Dispose()
}

So in this case if any exception is thrown your datatable object will be disposed. In your case without using it will get disposed only when Garbage Collector will collect it if finalizer is defined for DataTable class

amdmax
  • 771
  • 3
  • 14
1

From msdn,

Defines a scope, outside of which an object or objects will be disposed.

You dont need to worry about disposing the memory/resources of object you used. the using statement will take care of that. Variables defined inside the using block will be automatically disposed once the controls exits the using statements outer block (The scope).

TYpical example is an SQL connection. Usually you have to explicitly close the connection after your transaction by calling the Close method. But by using the using statmenet, You dont need to worry about that.It will be taken care.

CLR usaully does the memory freeingw henever the CLR decides to perform garbage collection.. By using the using statement, we are releasing the memory /resource used ourselves manually.

Shyju
  • 214,206
  • 104
  • 411
  • 497
1

You aren't creating objects differently when using a using statement.

A using statement simply wraps an object which inherits IDisposable. When you type

using (DataTable dt = new DataTable()) { }

the return value from DataTable dt = new DataTable() is a reference to dt, which goes into the using statement.

So this can also be written like

DataTable dt = new DataTable();
using (dt) { }

The reason for the using statement, as stated by the other answers, is that the resources held by the variable can be released prior to when the Garbage collector would normally release them.

Patrick
  • 17,669
  • 6
  • 70
  • 85
1

Declaring a type in using requires a type to implement IDisposable such that once the defined scope of the object ends the object gets cleaned up with the help of disposed method defined in the Type.

This is indeed very interesting because the compiler itself translates using into try..Finally statement, just like it translates constants into their values. So the behavior of using & try..finally is same over the runtime :).

Use the following link to understand more in depth: http://www.codeproject.com/Articles/6564/Understanding-the-using-statement-in-C

I hope it helps.

mannu2050
  • 403
  • 3
  • 11