1.code

   static void Main(string[] args)
            {
                SqlConnection sc = new SqlConnection("Data Source=pc3490ierf43;Initial Catalog=Persons;Integrated Security=True");

                    sc.Open();
                   SqlCommand command=new SqlCommand("Select Name from Persontable",sc);
                     SqlDataReader reader= command.ExecuteReader();

                        while (reader.Read())
                        {
                            Console.WriteLine("{0}", reader.GetString(0));

                        }




                Console.ReadLine();
            }

---------------------------------------------------------------------------------------------------------------------
** 2.code**

static void Main(string[] args)
        {
            using (SqlConnection sc = new SqlConnection("Data Source=pc3490ierf43;Initial Catalog=Persons;Integrated Security=True"))
            {

                sc.Open();
                using (SqlCommand command = new SqlCommand("Select Name from Persontable", sc))
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Console.WriteLine("{0}", reader.GetString(0));

                    }

                }

            }
            Console.ReadLine();
        }

----------------------------------------------------------------------------------------------------------------------------
First of all, I get the same output for both code blocks.
My question is how does the first example work since i haven't used the .Dispose() method and what dou you suggest should i stick with the using's or should i manage my connections manually?. I ve read that the using 's have the dispose integrated inside of them. I m just unsure sometimes when to use using when not. For instance in this code i would just use it for making a connection and the other constructros such as SqlCommand and SqlDataReader i wouldn't.

Edited 3 Years Ago by castajiz_2

My question is how does the first example work since i haven't used the .Dispose() method

How would that stop the code from working? You've merely failed to release resources, which depending on the resource involved may or may not cause issues down the line.

I m just unsure sometimes when to use using when not.

If a class implements IDisposable, you should either use a using statement, or call the Dispose method when you're done with the object. I include both options even though using should be preferred because there are situations where a using is awkward, and rolling everything up into a try..finally is cleaner.

Comments
ok, tnx
This question has already been answered. Start a new discussion instead.