Arrays and Method-1
Arrays and Method-1
Example Explained
•MyMethod() is the name of the method
•static means that the method belongs to the Program class and
•not an object of the Program class.
•void means that this method does not have a return value.
Calling a method
// Sort an int
int[] myNumbers = {5, 1, 8, 9};
Array.Sort(myNumbers);
foreach (int i in myNumbers)
{ Console.WriteLine(i); }
Others utility of Array
using System;
using System.Linq;
namespace MyApplication
{ class Program
{ static void Main(string[] args)
{ int[] myNumbers = {5, 1, 8, 9};
Console.WriteLine(myNumbers.Max());
// returns the largest value
Console.WriteLine(myNumbers.Min());
// returns the smallest value Console.WriteLine(myNumbers.Sum());
// returns the sum of elements }
}
}
Other Ways to Create an Arrays
// Create an array of four elements, and add values later
string[] cars = new string[4];
// Create an array of four elements and add values right
away
string[] cars = new string[4] {"Volvo", "BMW", "Ford",
"Mazda"};
// Create an array of four elements without specifying the
size
string[] cars = new string[] {"Volvo", "BMW", "Ford",
"Mazda"};
// Create an array of four elements, omitting the new
keyword,
and without specifying the size
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
There are 3 types of arrays in C#
1. Single Dimensional Array:
– To create single dimensional array, you need to use square brackets [] after the
type.
2. Multidimensional Array
– The multidimensional array is also known as rectangular arrays in C#. It can be
two dimensional or three dimensional. The data is stored in tabular form (row *
column) which is also known as matrix.
– To create multidimensional array, we need to use comma inside the square
brackets. For example:
– int[,] arr=new int[3,3];//declaration of 2D array
– int[,,] arr=new int[3,3,3];//declaration of 3D array
3. Jagged Array
– In C#, jagged array is also known as "array of arrays" because its elements are
arrays. The element size of jagged array can be different.
– Let's see an example to declare jagged array that has two elements.
– int[][] arr = new int[2][];
Multi dimensional Arrays
Full Class Array program
The Array class is the base class of all the arrays in C sharp programming.
Array class is defined within the system namespace.
Array class provides number of predefined functions and properties to work with.
Its function makes array much easier and simpler to work.