Compiler Error CS0116

 

Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

A namespace does not directly contain members such as fields or methods

Inside a namespace, the compiler only accepts classes, structures, unions, enumerations, interfaces, and delegates. This error is often generated by developers from a C/C++ background who forget that in C#, methods and variables must be declared and defined within a struct or class. For more information, see General Structure of a C# Program.

The following sample generates CS0116:

// CS0116.cs  
namespace x  
{  
    using System;  
  
    // method must be in class/struct  
    void Method(string str) // CS0116  
    {  
        Console.WriteLine(str);  
    }  
    // To fix the error, you must  
    // enclose a method in a class:  
    class Program  
    {  
        void Method2(string str)  
        {  
            Console.WriteLine(str);  
        }  
    }  
}  

General Structure of a C# Program
Classes and Structs
Namespaces

Show: