• Startseite
  • Tutorials
  • Kontakt
  • Mein Account
Panjutorials
  • Startseite
  • Tutorials
  • Kontakt
  • Mein Account

Arrays as arguments

It can happen that you want to use arrays as an argument, this is easily possible. How, you will learn here :).

So far we have already made a lot of arguments and arrays.

Example of arrays as an argument in CSharp

public class Panjutorials {	

	public static void Main(string[] args)
        {
            int[] joy = { 2, 3, 4, 5, 6 };
            sunshine(joy);

            foreach (int y in joy)
                Console.WriteLine(y);
            Console.ReadLine();
        }
        public static void sunshine(int[] x)
        {
            for (int i = 0; i < x.Length; i++)
                x[i] += 2;
        }

}

Now I have created a new function outside the main () function. What static means can be learned in the chapter Static in CSharp.

The function  “sunshine” takes as an argument an int [] x, i.e.. An array of type Integer. The function is to run a foreach loop, which increases the content of each position of the array by 2. Sunshine simply increases everything by 2 😉

In the main function I then create an array “joy” and call the function sunshine. As a parameter I give her our array “joy”. Then I use a foreach loop to output the values ​​of the array.

Little side info

I do not have {} on the line of the foreach loop. You can do this if the content of the For loop is only one line. So if you want to run more than one line of code within the for loop, you need the braces.

For more details on arrays as an argument, I recommend the documentation.