Pavel Nefyodov
Pavel Nefyodov

Reputation: 896

Why is the compiler Error CS0116 above everything?

I get Compiler Error CS0116 in the code:

<%@ Page EnableEventValidation="false" ValidateRequest="false" Language="C#" AutoEventWireup="true"

CodeFile="../Default.aspx.cs" Inherits="x.Program" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>

<%@ Register Assembly="Validators" Namespace="Sample.Web.UI.Compatibility" TagPrefix="cc1" %>

<%@ Import Namespace="System.IO" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Title</title>
<link href="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body class="mainbody"></body>
</html>

script code in Default.aspx.cs(Please note that "this random text somehow ignored" is ignored and no syntax error is generated):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

//this random text somehow ignored (now commented)

namespace x
{
// To fix the error, you must
// enclose a method in a class:

 class Program // changed from Class Program
 {
 void Method2(string str)
  {
  Console.WriteLine(str)
  }
 }
}

Why is the compiler Error CS0116 appearing? Why are the other things ignored (such as syntax error)? Update: Please note, if I delete "this random text somehow ignored" line error still persist.

FINAL UPDATE: Solution is 1. Obviously, extra line should be deleted. 2. Tools->Options->Text Editor->Basic->VB-Specific->Pretty listing(reformatting) of code was on and caused automatic change of case ("class" to "Class"). I didn't notice it straight away. Thank you very much. It works as charm now. @Rob Levine and @Guffa I can accept only one answer, but you both did a great job!

Upvotes: 0

Views: 3573

Answers (2)

Guffa
Guffa

Reputation: 700342

Change Class to class.

C# is case sensetive.

As the compiler doesn't recognise Class,
the method is still not in a class, and you still get the same error.

Upvotes: 3

Rob Levine
Rob Levine

Reputation: 41298

Error CS0116 is appearing precisely because of your line

this random text somehow ignored

This error message appears to tell you that members such as fields, methods, properties, etc, cannot appear directly inside the namespace - they need to be enclosed in a class or struct. [As Marc points out in the comment - even though this line appears above the namespace declaration, it is still considered to be directly inside the global namespace]

In other words - because it sees this compile issue, it doesn't bother attempting to make any further sense of what you may have in the class file, and doesn't give you any syntax error type messages - it is really saying "this file is totally wrong and I'm not even going to try and make sense of it."

Upvotes: 2

Related Questions