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.

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.

commented: ok, tnx +2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.