Ошибка компилятора cs0200

Permalink

Cannot retrieve contributors at this time

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Compiler Error CS0200

Compiler Error CS0200

04/22/2020

CS0200

CS0200

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, 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:

// 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 auto-implemented properties and object initializers and still generates CS0200:

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

public class Example
{
    int I { get; }

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

Strings are immutable, you cannot change them like this.
Use StringBuilder to make another string with changed characters, for example:

if (Start[i] == Middle[j])
{
    StringBuilder sb = new (Middle);
    (sb[i], sb[j]) = (sb[j], sb[i]);
    Middle = sb.ToString();
}

or even better — declare Middle as StringBuilder from the beginning, this will reduce string -> StringBuilder -> string conversions.
Char array is also an option if you only swap characters and never remove / add any.

kostyalom5

1 / 1 / 0

Регистрация: 02.06.2020

Сообщений: 64

1

11.09.2020, 15:43. Показов 4895. Ответов 4

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        double x, y, eps, u, summa;
        int n;
        string s1, s2;
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void pictureBox1_Click(object sender, EventArgs e)
        {
 
        }
 
        private void label4_Click(object sender, EventArgs e)
        {
 
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            listBox1.Font.Size = 14;
            listBox1.Items.Clear();
            eps = 0.0001;
            for (x = 0.0; x <= 1.0; x += 0.15)
            {
                n = 0;
                u = 1;
                summa = u;
                while (Math.Abs(u) >= eps)
                {
                    u = u * x / (n = 1);
                    summa = summa + u;
                    n = n = 1;
                }
                s1 = x.ToString() + "    "; s1 = s1.Substring(0, 6);
                s2 = summa.ToString() + "      "; s2 = s2.Substring(0, 8);
                listBox1.Items.Add(s1 + "/t" + "  " + s2 + "  " + "/t" + Math.Exp(x));
            }
 
        }
    }
}

Ошибка ни как не пойму как исправить:

Ошибка CS0200 Невозможно присвоить значение свойству или индексатору «Font.Size» — доступ только для чтения.



0



Svetlana Saphon

76 / 54 / 22

Регистрация: 26.02.2017

Сообщений: 206

11.09.2020, 16:06

2

Цитата
Сообщение от kostyalom5
Посмотреть сообщение

как исправить

C#
1
listBox1.Font = new Font(FontFamily.GenericSansSerif, 14);



0



kostyalom5

1 / 1 / 0

Регистрация: 02.06.2020

Сообщений: 64

16.09.2020, 14:11

 [ТС]

3

C#
1
ListBox.Items.Clear();

тут тоже ошибка, но ошибка такая:

Ошибка CS0120 Для нестатического поля, метода или свойства «ListBox.Items» требуется ссылка на объект.



0



Эксперт .NET

9777 / 5949 / 1402

Регистрация: 25.05.2015

Сообщений: 18,110

Записей в блоге: 14

16.09.2020, 14:13

4

И как же вы эту ошибку получили, если изначально было правильно?

Цитата
Сообщение от kostyalom5
Посмотреть сообщение

listBox1.Items.Clear();

Цитата
Сообщение от kostyalom5
Посмотреть сообщение

ListBox.Items.Clear();



0



Пора на C++?

369 / 263 / 99

Регистрация: 10.04.2020

Сообщений: 1,275

16.09.2020, 15:28

5

Не по теме:

Цитата
Сообщение от Rius
Посмотреть сообщение

И как же вы эту ошибку получили, если изначально было правильно?

Эволюция не стоит на месте



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

16.09.2020, 15:28

5

Read-only auto-properties can be set in a constructor:

public int AutoProp { get; }

public MyClass()
{
    AutoProp = 1;
}

Non-auto properties with only a getter are treated the same as read-only auto-properties in many cases, but they cannot be set in a constructor because there’s no backing field:

public int MyProp { get { return 0; } }

public MyClass()
{
    MyProp = 1; // Compiler Error CS0200
}

However, the error message reads:

Property or indexer ‘property’ cannot be assigned to — it is read only

That’s not the whole story. It’s not just because it’s read only. It’s also because it’s not an auto-property and/or it’s not in a constructor. The error message should say something to that effect.

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

  • #1

I am trying to manipulate a string within C#, and I keep getting this error:

error CS0200: Property or indexer ‘string.this[int]’ cannot be assigned to — it is read only

Here is the code snippet that is causing this:
string x = «Hello»;
x[0] = ‘a’;

Shoudln’t this work as it does in C++, giving the new value of aello to x? If not, what is the proper way of doing this?

  • #2

In .NET, a System.String is truly immutable. In other words, you can’t alter it… at all. Any operation on an immutable string results in the creation of a new string. This is a fairly expensive operation. If you look at the Chars property (the indexer) of System.String you’ll notice there is a get operation, but not a set operation. In order to edit a String in the manner you’re describing, you’ll need to use a System.Text.StringBuilder. e.g.:

StringBuilder x = new StringBuilder();
x.Append(«Hello»);
x[0] = ‘a’;

If you’re familiar with .NET you’ll probably ask yourself, «Why is the indexer for String/StringBuilder Chars instead of the default Item?» Well, if you create an indexer it will, by default, emit the Items property of the same type your indexer returns. You can apply the IndexerNameAttribute to the indexer to override this. This is how they got it to be Chars…

  • #3

Thanks. This helps a lot. Now I can manipulate strings like I can in c++

Similar threads

  • Advertising
  • Cookies Policies
  • Privacy
  • Term & Conditions

  • This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.

Понравилась статья? Поделить с друзьями:
  • Ошибка компилятора cs0120
  • Ошибка компилятора cs0115
  • Ошибка компилятора cs0103
  • Ошибка компилятора cs0030
  • Ошибка компиляции для платы generic esp8266 module