Friday, June 20, 2008

Cannot use local variable [variablename] before it is declared

I recently ran into a little issue that I would almost call a bug in Visual Studio 2008.

Technically my code ended up being the issue, however the error VS gave me was very misleading.

I had a method with two input parameters which were used throughout the method.
about 2/3 rd's of the way through I accidentally put this line
obj.var
essentially I referenced an attribute on a custom object without using the value for anything and without ending the line with a semicolon (C#). I received this error and almost every instance of my parameter variables were underlined with it:
"Cannot use local variable [variablename] before it is declared".

My problems with this error were:
1. it is completely false.
2. with every variable highlighted I forgot about my bad line and set about figuring out what the issue could be towards the top of my method to cause such a bad problem.
3. Normally VS will keep missing ; errors constrained to the errant line and the one following it, this time it said there was an error in lines far above where the actual error was.

10 comments:

Anonymous said...

thanks... a lot!!

Jeremy said...

No problem, glad it helped someone.

Anonymous said...

Helped me too... Thanks!

It turned out that 20 lines below the error that VS2010 incorrectly pointed out, I had a leftover "Then" that I missed when converting a function from VB.Net to C#.

Lame.

Anonymous said...

Another way to reproduce this every time is to precede the object name with 'delete' inside some scope (e.g. if statement):

string tmp;
if(true) {
tmp.Insert(0, "hello world");
delete tmp;
}

Removing either the invalid 'delete tmp;' line or the if statement will remove the error.

This is common when porting code from C/C++.

Behroz Sikander said...

I was going mad at the error that VS 2010 was giving and i looked the variable many times but everything was ok. Finally, i ended up googling your site and pewh i got the direction that error was somewhere else. Thankyou for posting such small thing (things like these sometimes become headache :().

Pierre Fournier said...

DOH! Indeed, VS2008 was giving me this irrelevant error because of a real error 5 lines below. When I commented out the line with the real error, this one magically went away.

Another customer helped here :) Thanks!

Anonymous said...

Thank you!!!

Mike said...

I received the same error message in Visual Studio 2010. :(
For solving the error, this blog post helps me:
http://blogs.msdn.com/b/samng/archive/2007/11/09/local-variable-scoping-in-c.aspx
It was a problem with the local scope ...

Thanks!

STC Technologies said...

thanks for the wonter full share..
It's very use full for every one

Anonymous said...

Thank you!