Might there be some error in the execution of foreach in this method?

Asked

Viewed 89 times

3

The execution of the code below may occur some error?

protected void ImprimeValores(Ilist<int> values) {
    if (values.Count > 0 && values != null)
        {
            foreach(int v in values) 
                Console.WriteLine(string.Concat("value:", v));
        }
}
  • Did the answer solve your problem? Do you think you can accept it? If you don’t know how you do it, check out [tour]. This would help a lot to indicate that the solution was useful to you and to give an indication that there was a satisfactory solution. You can also vote on any question or answer you find useful on the entire site.

1 answer

4

I can’t talk about the right logic because I don’t know what to do, but there’s a basic error of the code itself. It is possible to have a null reference error, since the condition feature is short-Circuit, this can be easily solved with condition reversal:

protected void ImprimeValores(Ilist<int> values) => if (values != null && values.Count > 0) foreach(int v in values) WriteLine(string.Concat("value:", v));

As a matter of fact, I don’t think it’s necessary to check whether values is greater than zero, unless you want to do something different in this code, it’s redundancy. I also find it completely unnecessary to use the concatenation method (the compiler will do it for you). It’s not wrong, some people like it.

I didn’t even mention the syntax error, this compiler already shows.

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

It is also possible to change this if by a contract and avoid verification at runtime in many cases, but this is already another matter.

  • thank you... I did the test here and really got the null reference error... regarding the other parts, also corrected.

  • The foreach will only be executed if values.Count > 0 , no need to check in if.

  • @Joãosobral read the whole answer.

  • What syntax error you refer to?

  • 1

    @ramaral ilist.

Browser other questions tagged

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