2

I've just encounter this problem. As far as I know, isn't "str1" supposed to be a local variable and I'm able to create a new variable with the same name outside of the using code block?

Of course I can create a variable with a different name and move on but this really bother me. Can someone explain this?

public int Execute(string sql, params SqlParameter[] parameters)
        {
            try
            {
                this.AddSql(sql, parameters);
                using (var cmd = new SqlCommand(sql, this.connection))
                {
                    var str1 = "";
                }
                //var str1 =""; // error because variable str1 is used above
                //str1 =""; // this also causes an error because "Can not resolve symbol 'str1'"
            }
            catch (Exception e)
            {
                //...
            }
            return 0;
        }
Dinh Tran
  • 535
  • 4
  • 13
  • So just to clarify, you cannot create a local variable with the name "str1" outside of the using structure? – nmg49 Aug 25 '16 at 05:29

1 Answers1

1

As explained in the link added by Yeldar, think about the "second" var str1. in line:

//var str1 =""; // error because variable str1 is used above

if declared, the scope of this variable would be the entire try{} block, which includes, the using statement.

It is not allowed as that would mean, we would end up having two "str1"s in the using block.

Sirish Kumar
  • 76
  • 1
  • 5