Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. .NET (Core and Framework)
  4. Understanding using statement

Understanding using statement

Scheduled Pinned Locked Moved .NET (Core and Framework)
databasequestion
7 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • V Offline
    V Offline
    Vipul Mehta
    wrote on last edited by
    #1

    Hi, I just wanted some clarification for using statement. With reference to my below code, lets say for some reason there is any exception on the following line of code - command.Parameters.Add("@ID", SqlDbType.Int) So in case of exception, the lines of code after the above line of code will not get executed and the control will move on to the last line of the method. Considering this scenario, I wanted to know will the connection and command objects (which are already initialised) get disposed?

    using (DbConnection connection =
    this.Database.ConnectionManager.GetConnection())
    {
    using (DbCommand command = connection.CreateCommand())
    {
    command.CommandType = CommandType.StoredProcedure;
    command.CommandText = "spGetList";

            command.Parameters.Add("@ID", SqlDbType.Int)
            command.Parameters("@ID").Value = this.ID
            
            using(DbDataReader dataReader = 
                    this.Database.Execute<DbDataReader>(command,
                    DatabaseExecutionType.DataReader))
            {
                this.Fill(dataReader);
            }
        }
    }
    

    Regards, Vipul Mehta

    L J D S M 6 Replies Last reply
    0
    • V Vipul Mehta

      Hi, I just wanted some clarification for using statement. With reference to my below code, lets say for some reason there is any exception on the following line of code - command.Parameters.Add("@ID", SqlDbType.Int) So in case of exception, the lines of code after the above line of code will not get executed and the control will move on to the last line of the method. Considering this scenario, I wanted to know will the connection and command objects (which are already initialised) get disposed?

      using (DbConnection connection =
      this.Database.ConnectionManager.GetConnection())
      {
      using (DbCommand command = connection.CreateCommand())
      {
      command.CommandType = CommandType.StoredProcedure;
      command.CommandText = "spGetList";

              command.Parameters.Add("@ID", SqlDbType.Int)
              command.Parameters("@ID").Value = this.ID
              
              using(DbDataReader dataReader = 
                      this.Database.Execute<DbDataReader>(command,
                      DatabaseExecutionType.DataReader))
              {
                  this.Fill(dataReader);
              }
          }
      }
      

      Regards, Vipul Mehta

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      The Using statement usually cleans up[^], that is, if your object is disposable. Alas, the documentation [^]for SqlConnection states;

      MSDN wrote:

      If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose. Close and Dispose are functionally equivalent. If the connection pooling value Pooling is set to true or yes, the underlying connection is returned back to the connection pool. On the other hand, if Pooling is set to false or no, the underlying connection to the server is actually closed.

      I are Troll :)

      1 Reply Last reply
      0
      • V Vipul Mehta

        Hi, I just wanted some clarification for using statement. With reference to my below code, lets say for some reason there is any exception on the following line of code - command.Parameters.Add("@ID", SqlDbType.Int) So in case of exception, the lines of code after the above line of code will not get executed and the control will move on to the last line of the method. Considering this scenario, I wanted to know will the connection and command objects (which are already initialised) get disposed?

        using (DbConnection connection =
        this.Database.ConnectionManager.GetConnection())
        {
        using (DbCommand command = connection.CreateCommand())
        {
        command.CommandType = CommandType.StoredProcedure;
        command.CommandText = "spGetList";

                command.Parameters.Add("@ID", SqlDbType.Int)
                command.Parameters("@ID").Value = this.ID
                
                using(DbDataReader dataReader = 
                        this.Database.Execute<DbDataReader>(command,
                        DatabaseExecutionType.DataReader))
                {
                    this.Fill(dataReader);
                }
            }
        }
        

        Regards, Vipul Mehta

        J Offline
        J Offline
        Jaime Olivares
        wrote on last edited by
        #3

        using will ensure you to dispose an IDisposable-derived object even if you return from inside the "using" block.

        Best regards, Jaime.

        1 Reply Last reply
        0
        • V Vipul Mehta

          Hi, I just wanted some clarification for using statement. With reference to my below code, lets say for some reason there is any exception on the following line of code - command.Parameters.Add("@ID", SqlDbType.Int) So in case of exception, the lines of code after the above line of code will not get executed and the control will move on to the last line of the method. Considering this scenario, I wanted to know will the connection and command objects (which are already initialised) get disposed?

          using (DbConnection connection =
          this.Database.ConnectionManager.GetConnection())
          {
          using (DbCommand command = connection.CreateCommand())
          {
          command.CommandType = CommandType.StoredProcedure;
          command.CommandText = "spGetList";

                  command.Parameters.Add("@ID", SqlDbType.Int)
                  command.Parameters("@ID").Value = this.ID
                  
                  using(DbDataReader dataReader = 
                          this.Database.Execute<DbDataReader>(command,
                          DatabaseExecutionType.DataReader))
                  {
                      this.Fill(dataReader);
                  }
              }
          }
          

          Regards, Vipul Mehta

          D Offline
          D Offline
          DaveyM69
          wrote on last edited by
          #4

          connection, command and dataReader will all have their Dispose or IDisposable.Dispose methods called.

          Dave
          Generic BackgroundWorker - My latest article!
          BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
          Why are you using VB6? Do you hate yourself? (Christian Graus)

          1 Reply Last reply
          0
          • V Vipul Mehta

            Hi, I just wanted some clarification for using statement. With reference to my below code, lets say for some reason there is any exception on the following line of code - command.Parameters.Add("@ID", SqlDbType.Int) So in case of exception, the lines of code after the above line of code will not get executed and the control will move on to the last line of the method. Considering this scenario, I wanted to know will the connection and command objects (which are already initialised) get disposed?

            using (DbConnection connection =
            this.Database.ConnectionManager.GetConnection())
            {
            using (DbCommand command = connection.CreateCommand())
            {
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "spGetList";

                    command.Parameters.Add("@ID", SqlDbType.Int)
                    command.Parameters("@ID").Value = this.ID
                    
                    using(DbDataReader dataReader = 
                            this.Database.Execute<DbDataReader>(command,
                            DatabaseExecutionType.DataReader))
                    {
                        this.Fill(dataReader);
                    }
                }
            }
            

            Regards, Vipul Mehta

            S Offline
            S Offline
            supercat9
            wrote on last edited by
            #5

            In general, 'Using' is an almost magic bullet to ensure that allocated resources will get freed when used as indicated above. It's not always perfect, however. The biggest gotcha I have found is that a constructor itself creates iDisposable objects which are supposed to get disposed at a later time and an exception is thrown in the constructor, the constructor itself must dispose of those objects, since the partially-constructed object will be going out of scope. For example, using VB syntax:

            Sub New(whatever_arguments...)
            Try
            .. construct the object
            Catch
            Me.Dispose()
            Throw
            End Try
            End Sub

            Note that the catch block doesn't swallow an exception nor even throw a new one; it simply re-throws the old exception so as to preserve the stack trace.

            1 Reply Last reply
            0
            • V Vipul Mehta

              Hi, I just wanted some clarification for using statement. With reference to my below code, lets say for some reason there is any exception on the following line of code - command.Parameters.Add("@ID", SqlDbType.Int) So in case of exception, the lines of code after the above line of code will not get executed and the control will move on to the last line of the method. Considering this scenario, I wanted to know will the connection and command objects (which are already initialised) get disposed?

              using (DbConnection connection =
              this.Database.ConnectionManager.GetConnection())
              {
              using (DbCommand command = connection.CreateCommand())
              {
              command.CommandType = CommandType.StoredProcedure;
              command.CommandText = "spGetList";

                      command.Parameters.Add("@ID", SqlDbType.Int)
                      command.Parameters("@ID").Value = this.ID
                      
                      using(DbDataReader dataReader = 
                              this.Database.Execute<DbDataReader>(command,
                              DatabaseExecutionType.DataReader))
                      {
                          this.Fill(dataReader);
                      }
                  }
              }
              

              Regards, Vipul Mehta

              M Offline
              M Offline
              muktaa
              wrote on last edited by
              #6

              We can use .net class (Manage code) in using clause it will automatically goes out of scope. You don't need to close or dispose out side, Because they called dispose function.all the class which is implemented the idisposable intercace will work on using clause

              1 Reply Last reply
              0
              • V Vipul Mehta

                Hi, I just wanted some clarification for using statement. With reference to my below code, lets say for some reason there is any exception on the following line of code - command.Parameters.Add("@ID", SqlDbType.Int) So in case of exception, the lines of code after the above line of code will not get executed and the control will move on to the last line of the method. Considering this scenario, I wanted to know will the connection and command objects (which are already initialised) get disposed?

                using (DbConnection connection =
                this.Database.ConnectionManager.GetConnection())
                {
                using (DbCommand command = connection.CreateCommand())
                {
                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = "spGetList";

                        command.Parameters.Add("@ID", SqlDbType.Int)
                        command.Parameters("@ID").Value = this.ID
                        
                        using(DbDataReader dataReader = 
                                this.Database.Execute<DbDataReader>(command,
                                DatabaseExecutionType.DataReader))
                        {
                            this.Fill(dataReader);
                        }
                    }
                }
                

                Regards, Vipul Mehta

                L Offline
                L Offline
                Lost User
                wrote on last edited by
                #7

                using keyword is nothing but a syntactic sugar over try-finally construct. For example, the following code

                using (SqlConnection conn = new SqlConnection(...)) {
                ....
                ....
                ....
                }

                actually gets compiled to

                SqlConnection conn = new SqlConnection(...);
                try {
                ....
                ....
                ....
                }
                finally {
                if (conn is IDisposable) {
                conn.Dispose();
                }
                }

                Therefore, irrespective of whether an exception is thrown or a return statement is encountered, the finally blok is always executed and ensures that objects that implement IDisposable are always cleaned up (unless the runtime host chooses not to do so - just to complicate things).

                1 Reply Last reply
                0
                Reply
                • Reply as topic
                Log in to reply
                • Oldest to Newest
                • Newest to Oldest
                • Most Votes


                • Login

                • Don't have an account? Register

                • Login or register to search.
                • First post
                  Last post
                0
                • Categories
                • Recent
                • Tags
                • Popular
                • World
                • Users
                • Groups