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
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.


  1. AnonymousJuly 01, 2009

    thanks... a lot!!

  2. No problem, glad it helped someone.

  3. AnonymousJuly 07, 2010

    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#.


  4. AnonymousJuly 12, 2010

    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++.

  5. 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 :().

  6. Pierre FournierJanuary 25, 2012

    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!

  7. Thank you!!!

  8. I received the same error message in Visual Studio 2010. :(
    For solving the error, this blog post helps me:
    It was a problem with the local scope ...


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

  10. Thank you!


Please leave your thoughts, I love hearing what you got out of the post. Spam comments will be removed.