Wednesday, 18 September 2013

C# Variable scope in switch statement

C# Variable scope in switch statement

I have a function that begins with this:
void RecordLoadPosition()
{
OdbcCommand command;
if (_hasPlantGenie)
{
command = new OdbcCommand();
string query;
switch (ItemType)
{
case ItemTypeEnum.COIL:
// We're only going to add records to the coils_pg
table when the coil gets moved. After
// a record is added, we'll update it.
command = new OdbcCommand("select * from coils_pg where
coil_id = " + _itemName, _db);
When I compile this, I do not get an error on the first line in the if
block, but I get errors complaining that I cannot use "command" before it
is declared inside the case block. I don't understand why the declaration
at the top of the function is not available inside the case block.
But OK. If it's not visible in the case block, I can just declare it. I
changed the first statement in the case block to "OdbcCommand command...".
Now I get an error complaining that I can't declare a variable that is
already declared in a parent block! I can't win either way!
What is happening here?
Of course, I can just use different OdbcCommand objects, and that's what
I'll do for now, but I'd like to understand this.

No comments:

Post a Comment