C# Error CS0276 – ‘property/indexer’: accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor

C# Compiler Error

CS0276 – ‘property/indexer’: accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor

Reason for the Error

You’ll get this error in your C# code when you declare a property with just one accessor and specify a access modifier for it.

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

using System;

namespace DeveloperPublishNamespace
{
    public class Employee
    {
        public int Id
        {
            protected set { }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

You’ll receive the error code CS0276 because you have specified only the set accessor for the Id property in the Employee class and you have also specified the protected accessor for the setter but no corresponding get accessor exists for the property.

Error CS0276 ‘Employee.Id’: accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor ConsoleApp4 C:\Users\Senthil\source\repos\ConsoleApp4\ConsoleApp4\Program.cs 7 Active

C# Error CS0276 – 'property/indexer': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor

Solution

You can fix this error in your C# program by either removing the access modifier for the accessor or include the missing accessor.

using System;

namespace DeveloperPublishNamespace
{
    public class Employee
    {
        public int Id
        {
            set { }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

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