C# Error CS0116 – A namespace cannot directly contain members such as fields or methods

C# Compiler Error

CS0116 – A namespace cannot directly contain members such as fields or methods.

Reason for the Error

This is one of the simplest of the errors that you will notice in C#. You will receive this error when you have declared a field or method directly under namespace instead of the class.

In C#, a namespace can contain only other namespaces, classes, Enums and structs and not fields, variables or methods directly under them.

Try compiling the below code snippet and you will immediately see the C# Compiler error CS0116.

namespace DeveloperPublishNamespace
{
    public int Field1;
    public class DeveloperPublish
    {
        public static void Main()
        {

        }
    }
}

Error CS0116 A namespace cannot directly contain members such as fields or methods ConsoleApp1 C:\Users\Senthil\source\repos\ConsoleApp1\ConsoleApp1\Program.cs 3 Active

C# Error CS0116 – A namespace cannot directly contain members such as fields or methods

Solution

You can fix this by moving the fields or methods from the namespace into a class.

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...