How to fix “Declaration expected”, “Syntax error”, and “Statement cannot appear outside of a method” errors that appear in a non-sense way in Visual Studio

There might be several different reasons for the generic errors below to appear.

Declaration expected
Syntax error
Statement cannot appear outside of a method

In my case, Visual Studio IntelliSense seemed to be showing these errors in every single line in my code-behind (cs) pages. Including the Page declaration in the ASPX page.

Solution

Follow the steps below until you solve the issue. If a step solves the problem, you don’t have to continue with the next step.

  1. Make sure to specify default language in your web.config (<compilation defaultLanguage=”C#”>)
  2. Specify default language in the beginning of your ASPX files (<%@ Page Language=”C#” %>)
  3. Page declarative must be the first line in your ASPX files. There shouldn’t be any lines including comments before your Page declarative (<%@ Page … %>
  4. Exclude the file from the project. Compile. Include it back
  5. Restart Visual Studio and recompile your code

Source: http://stackoverflow.com/questions/5978839/visual-studio-website-lots-of-random-errors-but-still-building

Leave a Reply