Categories
Blog

Scoping rules in c#

What a dull subject. Exactly so because it’s supposed to be a done deal, I don’t hear many people arguing about scope rules anymore. That is why I was so suprised when the compiler complained about some perfectly valid code I had written.  At first I thought it was only a peculiarity of the way closures are implemented in c#, but as I dug deeper, the scoping rules of c# seems to be… well just annoyingly stupid. Lets start with a simple case:

OleDbCommand command = SQLServer.CreateCommand();

if (true)

{

OleDbCommand command = SQLServer.CreateCommand();

}

I don’t think many people would argue that is just bad programming practice, but look what happens if we just change it a little:

if (true)

{

OleDbCommand command = SQLServer.CreateCommand();

}

OleDbCommand command = SQLServer.CreateCommand();

This fails with the exact same error. Apparently the command of the if statement prevents the other command from being declared, but since you can use command anymore this is just plainly wrong.  Furthermore closures behave the same way:

VoidFunction t = delegate

{

OleDbCommand command = SQLServer.CreateCommand();

}

OleDbCommand command = SQLServer.CreateCommand();

Please note that the closure has just been declared. For more discussion of the examples see this thread on stackoverflow.  I followed up with a question of why the language guys at microsoft would have made such a bonehead mistake and there wasn’t any good reason in my mind.  I’m still puzzled why the compiler wouldn’t just issue a warning, but maybe warnings is one of those things they hated about C++ and decided it was just easier to swing the big No-hammer and be done with it.

One reply on “Scoping rules in c#”

[…] Last friday, Lau discovered an interesting edge case of python. Something that at first appeared to be a bug, but later revealed a deeper truth about the scoping of Python. I guess coming from a C++ background spoils one in some regards. Scoping in C++ is simple and uniform, I have never in many years of programming C++ got bitten by the scope of the language, something that I also can’t say about C#. […]

Comments are closed.