HomeCSharpC# Error CS0272 – The property or indexer ‘property/indexer’ cannot be used in this context because the set accessor is inaccessible

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

C# Compiler Error

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

Reason for the Error

You’ll get this error in your C# code when you try to set or assign value to a property that inaccessible set accessor.

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

using System;

namespace DeveloperPubNamespace
{
    public class Employee
    {
        private int _id;

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

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

You’ll receive the error code CS0272 because you are using trying to set a value “1” to the property Id of the Employee instance where the property “Id” has a private set accessor.

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

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

Solution

You can fix this error in your C# program by increasing the accessibility of the set 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();
            emp.Id = 1;
            Console.WriteLine("No Error");
        }
    }
}

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