Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return the variable used for using inside the using C#

I am returning the variable I am creating in a using statement inside the using statement (sounds funny):

public DataTable foo ()
{
    using (DataTable properties = new DataTable())
    {
       // do something
       return properties;
    }
}

Will this Dispose the properties variable??

After doing this am still getting this Warning:

Warning 34 CA2000 : Microsoft.Reliability : In method 'test.test', call System.IDisposable.Dispose on object 'properties' before all references to it are out of scope.

Any Ideas?

Thanks

like image 614
di3go Avatar asked May 12 '10 20:05

di3go


People also ask

Can I return local variable in C?

It is possible to return a pointer to a local variable, but a good compiler will warn you, and actually doing it is likely to trigger undefined behavior. What is the main difference between pointer and reference in C++? You can update the value of a pointer, but not the value of a reference.

What is using () in C#?

The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned. A variable declared with a using declaration is read-only.

What does returning a value mean in C?

A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.

Can we return a local variable from a function?

How to return a local variable from a function? But there is a way to access the local variables of a function using pointers, by creating another pointer variable that points to the variable to be returned and returning the pointer variable itself.


2 Answers

If you want to return it, you can't wrap it in a using statement, because once you leave the braces, it goes out of scope and gets disposed.

You will have to instantiate it like this:

public DataTable Foo() 
{ 
    DataTable properties = new DataTable();
    return properties; 
} 

and call Dispose() on it later.

like image 99
Robert Harvey Avatar answered Nov 01 '22 18:11

Robert Harvey


Yes, it will dispose it - and then return it. This is almost always a bad thing to do.

In fact for DataTable, Dispose almost never does anything (the exception being if it's remoted somewhere, IIRC) but it's still a generally bad idea. Normally you should regard disposed objects as being unusable.

like image 33
Jon Skeet Avatar answered Nov 01 '22 17:11

Jon Skeet