There might be several different reasons for the generic errors below to appear.
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.
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.
- Make sure to specify default language in your web.config (<compilation defaultLanguage=”C#”>)
- Specify default language in the beginning of your ASPX files (<%@ Page Language=”C#” %>)
- Page declarative must be the first line in your ASPX files. There shouldn’t be any lines including comments before your Page declarative (<%@ Page … %>
- Exclude the file from the project. Compile. Include it back
- Restart Visual Studio and recompile your code
1 thought on “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”