Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

So I'm trying to pass a local string to another form in a c# project. This is my code:

Form 1:

... Main frm = new Main(); frm.Passvalue = usrTxt.Text; frm.ShowDialog(); 

Form 2

... public string Username; public string Passvalue {     get { return Username; } } 

I'm getting the error:

Property or indexer "Main.Passvalue" cannot be assigned to "--" it is read only

I never declared anything as ReadOnly, does anyone know what the problem here is?

like image 529
hasno l Avatar asked Jun 27 '16 12:06

hasno l


People also ask

How do you implement a read only property?

Create Readonly Property Read only means that we can access the value of a property but we can't assign a value to it. When a property does not have a set accessor then it is a read only property. For example in the person class we have a Gender property that has only a get accessor and doesn't have a set accessor.

How do you know if a property is readOnly?

Use the readOnly property to check if an element is read-only, e.g. if (element. readOnly) {} . The readOnly property returns true when the element is read-only, otherwise false is returned.

How do you make something read only in C#?

To create a read-only field, use the readonly keyword in the definition. In the case of a field member, you get only one chance to initializeinitializeIn computer programming, initialization (or initialisation) is the assignment of an initial value for a data object or variable. The manner in which initialization is performed depends on the programming language, as well as the type, storage class, etc., of an object to be initialized.https://en.wikipedia.org › wiki › Initialization_(programming)Initialization (programming) - Wikipedia the field with a value, and that is when you call the class constructor.


1 Answers

It has no setter, which makes it a readonly property, change it to:

public string Passvalue {     get { return Username; }     set { Username = value; } } 

Incidentally, this seems a little redundant, as you're publicly exposing Username anyway. It's generally considered good practice to make class fields private.

like image 153
James Jenkinson Avatar answered Sep 22 '22 13:09

James Jenkinson