Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# syntax question - for loop and end of line

Tags:

c#

I am currently learning c# and reading a few books. I can do quite a few things, however only from modifying examples - it really frustrates that I do not actually understand how/why some of the more basic items work.

I have just done a console application that takes arguments and displays them all one by one.

The code is:

using System;

class test
{ static int Main(string[] argsin)
{ 

for (
        int i = 0; 
        i < argsin.Length; 
        i++
    )
Console.WriteLine("Argument: {0}", argsin[i]);
Console.ReadLine();
return -1;
}
}

Now, this works perfectly, but coming from a basic (no pun!) understand of Visual Basic, how/why does it know to print the correct argument and then go on to the next without quitting the application after the first Console.WriteLine... I feel I have missed the fundamentals of how this works!

Next, why is it that inside the for loop, each line ends with a semicolon apart from i++?

I keep forgetting to add it from time to time, and then when trying to work out why it wasn't compiling, I added one where I wasn't meant to!

like image 843
Wil Avatar asked Nov 30 '22 09:11

Wil


1 Answers

Your code is formatted a bit strangely, if you reformat it as this I think it's easier to understand:

using System;

class test
{ 
    static int Main(string[] argsin)
    { 
        for (int i = 0; i < argsin.Length; i++)
        {
            Console.WriteLine("Argument: {0}", argsin[i]);  
        }
        Console.ReadLine();
        return -1;
    }
}

So as you can see int i = 0; i < argsin.Length; i++ are not 3 different lines, they are all just arguments to the for loop.

And adding the { and } makes it easier to see what lines of code are inside the for loop.

like image 127
Hans Olsson Avatar answered Dec 19 '22 04:12

Hans Olsson