Edit

Share via


Compiler error CS0200

Property or indexer 'property' cannot be assigned to -- it is read only

An attempt was made to assign a value to a property, but the property does not have a set accessor or the assignment was outside of the constructor. Resolve the error by adding a set accessor. For more information, see How to declare and use read-write properties.

Examples

The following sample generates CS0200:

C#
// CS0200.cs
public class Example
{
    private int _mi;
    int I
    {
        get
        {
            return _mi;
        }
        // uncomment the set accessor and declaration for _mi
        /*
        set
        {
            _mi = value;
        }
        */
    }

    public static void Main()
    {  
        Example example = new Example();
        example.I = 9;   // CS0200
    }
}  

The following sample uses automatically implemented properties and object initializers and still generates CS0200:

C#
// CS0200.cs
public class Example
{
    int I
    {
        get;
        // uncomment the set accessor and declaration
        //set;
    }

    public static void Main()
    {  
        var example = new Example
        {
            I = 9   // CS0200
        };
    }
}

To assign to a property or indexer 'property' that's read-only, add a set accessor or assign the value in the object's constructor.

C#
public class Example
{
    int I { get; }

    public Example()
    {
        I = -7;
    }
}