Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you use the using statement this way in ASP.NET?

Refactoring some code again. Seeing some of this in one of the ASP.NET pages:

using (TextBox txtBox = e.Row.Cells[1].FindControl("txtBox") as TextBox)
{
}

There is no need to dispose txtBox, because it's just a reference to an existing control. And you don't want the control disposed at all. I'm not even sure this isn't harmful - like it would appear to ask for the underlying control to be disposed inappropriately (although I have not yet seen any ill effects from it being used this way).

like image 452
Cade Roux Avatar asked Mar 11 '11 16:03

Cade Roux


People also ask

What is the purpose of using statement?

The using statement is used to set one or more than one resource. These resources are executed and the resource is released. The statement is also used with database operations. The main goal is to manage resources and release all the resources automatically.

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 is the use of using?

The "using" statement allows you to specify multiple resources in a single statement. The object could also be created outside the "using" statement. The objects specified within the using block must implement the IDisposable interface.

Why do we need using in C#?

In C#, the using keyword has two purposes: The first is the using directive, which is used to import namespaces at the top of a code file. The second is the using statement. C# 8 using statements ensure that classes that implement the IDisposable interface call their dispose method.


1 Answers

TextBox inherits its implementation of IDisposable from its Component superclass. That implementation removes the component from its site container if it has one.

So, doing that might have nefarious effects if the text box actually resides in a site container. Also, after calling Dispose() on an object, you should not use it again, no matter what (it's not in a usable state anymore).

I'd suggest you avoid that pattern with ASP.NET web controls.

like image 181
Frédéric Hamidi Avatar answered Sep 28 '22 07:09

Frédéric Hamidi