What is " : " (two points) in C#?

Asked

Viewed 460 times

8

I still don’t understand what the two points represent and why this code isn’t running.

int soma = 0;
        int[] lista = { 3, 7, -6, 10, -1, 0, -1, 4};

        for (int i : lista)
        {
            if (i > 0) { 
            soma = soma + i;
            }
        }
        Console.WriteLine("Soma: " + soma);
  • 2

    Hey, there you are, Misaell. It would be important to [Dit] the question with more details (which error, since it says it does not work, and complement with a brief explanation of what I expected the code to do - references are welcome) to check if it has to do with the mentioned syntax (this part has already been explained by @Maniero) or if they are two separate problems.

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site.

1 answer

8

In this context it is syntax error. Under no circumstances can the two points be used there in C#.

In Java this syntax of for would be valid and would be equivalent to this in C#:

foreach (int i in lista)

Since there are no two points in another part of the code I imagine that is confusing languages. So until you try to compile this will give a syntax error, so it is not running. So it runs:

using static System.Console;

public class Program {
    public static void Main() {
        var soma = 0;
        foreach (var i in { 3, 7, -6, 10, -1, 0, -1, 4}) if (i > 0) soma++;
        WriteLine("Soma: " + soma);
    }
}

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

Browser other questions tagged

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