HomeCSharpC# Error CS0176 – Static member ‘member’ cannot be accessed with an instance reference; qualify it with a type name instead

C# Error CS0176 – Static member ‘member’ cannot be accessed with an instance reference; qualify it with a type name instead

C# Compiler Error

CS0176 – Static member ‘member’ cannot be accessed with an instance reference; qualify it with a type name instead

Reason for the Error

You will receive this error when you try to access a static variable of a class with an instance as a qualifier.

For example, try compiling the below code snippet

namespace DeveloperPubNamespace
{
    public class Employee
    {
        public static int EmployeeCount = 0;
    }

    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee();
            emp.EmployeeCount=1;
        }
    }
}

The above code snippet will result with the error code CS0176

Error CS0176 Member ‘Employee.EmployeeCount’ cannot be accessed with an instance reference; qualify it with a type name instead ConsoleApp3 C:\Users\Senthil\source\repos\ConsoleApp3\ConsoleApp3\Program.cs 13 Active

Solution

To fix this error, ensure that you access the static variable directly using the class name instead of the instance name as the qualifier. The above code snippet can be fixed by replacing the Main() function with the below code snippet.

static void Main(string[] args)
{
	Employee.EmployeeCount=1;
}

Leave A Reply

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

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...