C# Error CS0271 – The property or indexer ‘property/indexer’ cannot be used in this context because the get accessor is inaccessible

C# Compiler Error

CS0271 – The property or indexer ‘property/indexer’ cannot be used in this context because the get accessor is inaccessible

Reason for the Error

You’ll get this error in your C# code when you try to access an property/indexer that doesnot have a get accessor or inaccessible get accessor.

For example, lets try to compile the below code snippet.

using System;

namespace DeveloperPubNamespace
{
    public class Employee
    {
        private int _id;

        public int Id
        {
            set { _id = value; }
            private get { return _id; }
        }

    }
    class Program
    {
        public static void Main()
        {
            Employee emp = new Employee();
            var result = emp.Id;
            Console.WriteLine("No Error");
        }
    }
}

You’ll receive the error code CS0271 because you are trying to access the property Id from the Employee instance where the property “Id” doesnot have the accessible (public/internal) get accessor.

Error CS0271 The property or indexer ‘Employee.Id’ cannot be used in this context because the get accessor is inaccessible DeveloperPublish C:\Users\Senthil\source\repos\ConsoleApp3\ConsoleApp3\Program.cs 21 Active

C# Error CS0271 – The property or indexer 'property/indexer' cannot be used in this context because the get accessor is inaccessible

Solution

You can fix this error in your C# program by increasing the accessibility of the get accessor (Eg : changing the access modifier to public).

using System;

namespace DeveloperPubNamespace
{
    public class Employee
    {
        private int _id;

        public int Id
        {
            set { _id = value; }
            get { return _id; }
        }

    }
    class Program
    {
        public static void Main()
        {
            Employee emp = new Employee();
            var result = emp.Id;
            Console.WriteLine("No Error");
        }
    }
}

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