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

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