Can you have some error in foreach execution in this method?

3

Can I run the following code in error?

protected void ImprimeValores(Ilist<int> values) {
    if (values.Count > 0 && values != null)
        {
            foreach(int v in values) 
                Console.WriteLine(string.Concat("value:", v));
        }
}
    
asked by anonymous 22.05.2016 / 20:14

1 answer

4

I can not talk about the correct logic because I do not know what to do, but there is a basic error in the code itself. It is possible to have a null reference error, since the condition characteristic is short-circuit , this can easily be solved by reversing the condition:

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

To tell you the truth, I find it unnecessary to check that values is greater than zero, unless you later 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 this for you). It's not wrong, there are people you like.

I did not even mention the syntax error, this compiler already shows.

See running on dotNetFiddle and on CodingGround .

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

    
22.05.2016 / 20:29