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

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

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...