Using the local variable before it is declared #9677
-
Hello, Could somebody please explain why the line below is valid? int value = (value = 1) > 0 ? 2 : -2; If I replace var value = (value = 1) > 0 ? 2 : -2;
// error CS0841: Cannot use local variable 'value' before it is declared (SharpLab) I'm confused because in both cases it seems I'm using a local variable "before it is declared". |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
In hte latter case, we don't know the type of 'value', and to determine its type, we have to look at the RHS. But the RHS uses 'value', whose type we are trying to figure out. So we can't figure out the type of the RHS. So we can't figure out the type of 'value'. In the former case, there is no issue. we knwo the type. It is explicit. It is 'int'. As such, we don't have to go figure out the type. We can just bind and compile the RHS. The RHS is perfectly legal. The variable is never read before it is written, for example. |
Beta Was this translation helpful? Give feedback.
In hte latter case, we don't know the type of 'value', and to determine its type, we have to look at the RHS. But the RHS uses 'value', whose type we are trying to figure out. So we can't figure out the type of the RHS. So we can't figure out the type of 'value'.
In the former case, there is no issue. we knwo the type. It is explicit. It is 'int'.
As such, we don't have to go figure out the type. We can just bind and compile the RHS. The RHS is perfectly legal. The variable is never read before it is written, for example.