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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With