
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
How do we pass an array in a method in C#?
Pass array in a method as a method argument.
Let’s say the following is our array declaration and initialization.
MyArray app = new MyArray(); /* an int array with 5 elements */ int [] balance = new int[]{1000, 2, 3, 17, 50};
Now call the method getAverage() and pass the array as method argument.
double getAverage(int[] arr, int size) { // code }
The following is the example showing how to pass an array in a method in C#.
Example
using System; namespace ArrayApplication { class MyArray { double getAverage(int[] arr, int size) { int i; double avg; int sum = 0; for (i = 0; i < size; ++i) { sum += arr[i]; } avg = (double)sum / size; return avg; } static void Main(string[] args) { MyArray app = new MyArray(); /* an int array with 5 elements */ int [] balance = new int[]{1000, 2, 3, 17, 50}; double avg; /* pass pointer to the array as an argument */ avg = app.getAverage(balance, 5 ) ; /* output the returned value */ Console.WriteLine( "Average value is: {0} ", avg ); Console.ReadKey(); } } }
Output
Average value is: 214.4
- Related Articles
- How do we pass parameters by reference in a C# method?
- How do we pass parameters by value in a C# method?
- How do we pass parameters by value in a Java method?
- How to pass parameters using param array in a C# method?
- Why do we pass a Pointer by Reference in C++?
- How can we pass lambda expression in a method in Java?
- How to pass an array by reference in C++
- Pass an array by value in C
- How do we call a C# method recursively?
- How to pass parameters to a method in C#?
- How do we check if an object is an array in Javascript?
- How to pass entire array as an argument to a function in C language?
- How do we initialize an array within object parameters in java?
- How to pass an array as a URL parameter in Laravel?
- How do you empty an array in C#?

Advertisements