Passing array as parameter in C#

In this chapter you will learn:
  • How to passing array as parameter?
  • How to declare a method to accept array as argument?
  • How to pass array as parameter using C# programming?

An array can also be passed to a method as argument or parameter. A method process the array and returns output. Passing array as parameter in C# is pretty easy as passing other value as a parameter. Just create a function that accepts an array as argument and then processes them. The following demonstration will help you to understand how to pass an array as an argument in C# programming.

 

Programming Example of passing array as parameter in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace array_parameter
{
    class Program
    {
        static void printarray(int[] newarray)
        {
            int i, sum = 0;
            Console.Write("\n\nYou entered:\t");
            for (i = 0; i < 4; i++)
            {
                Console.Write("{0}\t", newarray[i]);
                sum = sum + newarray[i];
            }
            Console.Write("\n\nAnd sum of all value is:\t{0}", sum);
            Console.ReadLine();
        }
        static void Main(string[] args)
        {
            int[] arr = new int[4];
            int i;
            for (i = 0; i < 4; i++)
            {
                Console.Write("Enter number:\t");
                arr[i] = Convert.ToInt32(Console.ReadLine());
            }
            // passing array as argument
            Program.printarray(arr);
        }
    }
}

Output

Enter number:      5
Enter number:      3
Enter number:      2
Enter number:      1
You entered:     5    3    2    1
Add sum of all value is:       11 __

In the preceding example, we create an array and accept some integer value from the user at runtime. Then we passed array as argument to printarray(int[] newarray)  for printing and other calculation. It is same as other value passed as parameter to the function.

Summary

In this chapter you learned how to pass array as parameter to the function. In next chapter you will learn about some predefined array function in C#.

More Examples

Write A Program To Print One Dimensional Array In Reverse Order
Write A Program To Sort One Dimensional Array In Descending Order Using Non Static Method.
Write A Program To Sort One Dimensional Array In Desending Order Static Class Array Method.
Write A Program To Sort One Dimensional Array In Ascending Order Using Non Static Method.
Write A Program To Sort One Dimensional Array In Ascending Order Using Static Method.
Write A Program To Add The Diagonal Of Two-Dimensional Array.
 

Share your thought