Error: a property or indexer that cannot be passed as an out or ref parameter

I am in doubt about the error CS0206 maybe a property or indexer cannot be passed as an out or ref parameter on line 39 and 41 of my code, how do you solve this?

35| produtos[i] = new Produtos();
...
38| Write($"Digite o preço do {i}º produto : ");
39| if (!decimal.TryParse(ReadLine(), out produtos[i].Preco)) return 1; x
40| Write($"Digite a quantidade do {i}º produto: ");
41| (!int.TryParse(ReadLine(), out produtos[i].Quantidade)) return 1; x
Author: Maniero, 2019-10-19

1 answers

The error is exactly what is written, you can not do what you did. The solution is to create a normal variable and then assign its value to the property you want.

A variable passed by out can only be a true variable. A property is not a variable, it appears to be one but is a method that is called to possibly access a variable indirectly. The modifier out, as well as ref, end up having a indirection and so are passed as a pointer and the expected semantics is that this is a pointer to a given directly. If you have a new hint the compiler doesn't know what to do.

If you want to understand more about how this modifier works you have answer about in What are the parameters out and ref. And to learn more about property have more in How do Properties work in C#? (plus and plus). I strongly recommend reading these and other links that they give insight into the mechanisms to understand what you are doing and not just follow cake recipes.

Then it would be something like this:

if (!decimal.TryParse(ReadLine(), out var valor)) return 1;
produtos[i].Preco = valor;
 2
Author: Maniero, 2019-10-21 12:02:02