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

Asked

Viewed 143 times

0

I’m having second thoughts about CS0206 Error Maybe a property or an 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
  • that can’t out produtos[i].Preco you need to pass a variable that cannot be a property ... quick solution if (decimal.TryParse(ReadLine(), out var p)) { produtos[i].Preco = p; } If you passed the Tryparse test you pass the value for the property ... It lacks context, so I didn’t answer, doesn’t it make sense to put a Return 1 there ?? where will return 1 ... unknown problems in your code, so I asked for closure for the lack of a context to clarify all the code that was not posted.

1 answer

3


The mistake is exactly what is written, you can’t 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 seems to be a variable, but it is a method that is called to possibly access a variable indirectly. The modifier out, as well as ref, end up having a indirect and so they are passed as a pointer and the expected semantics is that this is a pointer to a given directly. If you have a new indirect compiler doesn’t know what to do.

If you want to understand more about how this modifier works has answer on What are the out and ref parameters. And to learn more about property has more on How the properties in C work#? (plus and plus). I strongly recommend reading these and others links that give insight into the mechanisms to understand what you’re 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;

I put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.