diff --git a/docs/csharp/misc/cs0200.md b/docs/csharp/misc/cs0200.md index f8e9e1c6b23e3..691639caa7e22 100644 --- a/docs/csharp/misc/cs0200.md +++ b/docs/csharp/misc/cs0200.md @@ -1,45 +1,81 @@ --- title: "Compiler Error CS0200" -ms.date: 07/20/2015 -f1_keywords: +ms.date: 04/22/2020 +f1_keywords: - "CS0200" -helpviewer_keywords: +helpviewer_keywords: - "CS0200" ms.assetid: 1990704a-edfa-4dbd-8477-d9c7aae58c96 --- # 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](../programming-guide/classes-and-structs/using-properties.md), but the property does not have a set accessor. Resolve the error by adding a set accessor. For more information, see [How to declare and use read write properties](../programming-guide/classes-and-structs/how-to-declare-and-use-read-write-properties.md). - -## Example - The following sample generates CS0200: - -```csharp -// CS0200.cs -public class MainClass -{ - // private int _mi; - int I +Property or indexer 'property' cannot be assigned to -- it is read only + +An attempt was made to assign a value to a [property](../programming-guide/classes-and-structs/using-properties.md), 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](../programming-guide/classes-and-structs/how-to-declare-and-use-read-write-properties.md). + +## Examples +The following sample generates CS0200: + +```csharp +// 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() { - get - { - return 1; - } - - // uncomment the set accessor and declaration for _mi - /* - set - { - _mi = value; - } - */ - } - - public static void Main () - { - MainClass II = new MainClass(); - II.I = 9; // CS0200 - } + Example example = new Example(); + example.I = 9; // CS0200 + } } ``` + +The following sample uses [auto-implemented properties](../programming-guide/classes-and-structs/auto-implemented-properties.md), [object initializers](../programming-guide/classes-and-structs/object-and-collection-initializers.md), and still generates CS0200: + +```csharp +// 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 + }; + } +} +``` + +Assignment to a property or indexer 'property' that is read only, can be achieved through adding a set accessor or by assigning to the property in the object's constructor. + +```csharp +public class Example +{ + int I { get; } + + public Example() + { + I = -7; + } +} +```