C# tutorials
4. Hello world with array and foreach loop

Note: While reading this page, bear in mind that I'm no computer expert and that the text below may be partly inaccurate. If you find errors or have proposals for improvements, please send me a message and help make this a better page for the benefit of future visitors. To the left, there are links to more C# tutorials.

To complete this tutorial, follow these instructions:

1. Open Visual C# 2010 Express.

2. Click on New Project in the File menu.

3. Choose Windows Forms Application if that option isn't already chosen, change the name if you like and click on OK.

4. Point at Toolbox in the left margin and click on the Auto Hide icon at the top of the window (to keep the window to stay open and easier to work with).

5. Drag a Button to Form 1.

6. Drag a Rich Textbox to Form 1. Resize the textbox if you like.

7. Double-click on the button. The file Form1.cs will open with the caret ready to write code that will run when button 1 is clicked.

8. Write or paste this code where the caret is:

string[] hello = { "Hello", "world!", "Goodbye", "world ..." };
richTextBox1.Text = null;
foreach (string value in hello)
  richTextBox1.Text += value + "\n";

9. Press F5 to start debugging the program.

10. Click on the button. This text should appear in the textbox:

world ...

Comments on the code snippet

Line 1: string[] is the beginning of an array with strings. { indicates the beginning of the array and }; the end of the array.

Line 2: Remove this line, and Hello world! Goodbye world ... will be written again and again every time you click on the button. Keep this line, and Hello world! Goodbye world ... will be written only once.

Line 3 means that something will be done to or with each value in the string array hello.

Line 5: += means that something will be added to the textbox each time the loop is run. If you remove the + sign, only world ... (the last value) will appear in the textbox.

Would you like to comment on this page or some other page? Send an email to mats.kristiansson.skovde@gmail.com or a letter to Mats Kristiansson, Timmervägen 3A, 541 64 Skövde, Sweden with the title of the page you want to comment on, your comment and your name or a pseudonym.