Using using statement to avoid memory leaks
It is true that .net tries very hard to efficiently manage memory consumption of the application you write leveraging .net framework. However, in some situations we need to be wakeful in dealing with objects which may lead to huge memory leaks eg:- Database connections. If you are opening a database connection it is your responsibility to efficiently release it after use. Most programmers even though know about this fact often forget to do so. This is where using statement comes handy, If you wrap an object using the 'using' statement, you can be most certainly be sure that memory it uses is freed after it gets out of the scope.
Example:-
Example:-
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- SqlCommand command = connection.CreateCommand();
- command.CommandText = "mysp_GetValue";
- command.CommandType = CommandType.StoredProcedure;
- connection.Open();
- object ret = command.ExecuteScalar();
- }
Notes:- You can only wrap object of classes which implemented IDisposable inside using.
Detailed information and examples can be found from :http://www.w3enterprises.com/articles/using.aspx
Google search query:advantage of using using C#
Comments