I’ve seen questions like this a few times:

 

Why doesn’t my code compile?

All I do is getting a row out from the database and use that value, like so:

 

        static void Main(string[] args)

        {

            string cs = @"Data Source=<server>;Integrated Security=SSPI;Initial Catalog=Northwind";

            using (SqlConnection con = new SqlConnection(cs))

            {

                SqlCommand cmd = con.CreateCommand();

                con.Open();

                cmd.CommandText = "SELECT * FROM Shippers WHERE ShipperId = 2";

                SqlDataReader rdr = cmd.ExecuteReader();

 

                if(rdr.Read())

                    int id = (int)rdr.GetValue(0);

                    string name = (string)rdr.GetValue(1);

                    string phone = (string)rdr.GetValue(2);

               

                con.Close();

            }

        }

 

When compiling, I get the following error:

 

“Embedded statement cannot be a declaration or labeled statement”

 

Well, head over to the “Visual C# Reference: Errors and Warnings - C# Compiler Errors and Warnings”

http://msdn.microsoft.com/en-us/library/ms228296.aspx

 

and check for CS1023.

 

"Compiler Error CS1023"

http://msdn.microsoft.com/en-us/library/xaw06638.aspx

 

This states that: "An embedded statement, such as the statements following an if statement, can contain neither declarations nor labeled statements."

 

so, going back to the code above, we can clearly see that since we have omitted the curly brackets, { }, after the if statement we are violating this restriction.

 

Simply change the if statement to:

 

                if (rdr.Read())

                {

                    int id = (int)rdr.GetValue(0);

                    string name = (string)rdr.GetValue(1);

                    string phone = (string)rdr.GetValue(2);

                }

 

and Bob’s your uncle.

 

This is obviously not limited to database access, it will fail in all scenarios where there is a declaration after an if statement where the curly brackets are missing.