top

Search

C# Tutorial

Arrays contain a collection of data elements of the same type. These data elements are stored in contiguous memory locations. Some of the arrays in C# are 1-D arrays, 2-D arrays, Jagged arrays, Param arrays etc. Details about these are given as follows:1-D ArraysOne dimensional arrays consist of a single row with as many elements as required. These arrays can be declared using the following syntax:data_type[ ] name_of_array;In the above syntax, data_type is the data type of array elements and name_of_array is the name given to the array.The syntax to initialize the array is given as follows:data_type[ ] name_of_array = new data_type[array_size];In the above syntax, data_type is the data type of array elements, name_of_array is the name given to the array, new is a keyword that creates an instance of the array and array_size is the size of the array.There are many methods to assign values to the array. Some of these are given as follows:int[ ] arr = { 1, 2, 3, 4, 5};  int[ ] arr = new int[] { 1, 2, 3, 4, 5}; int[ ] arr = new int[5] { 1, 2, 3, 4, 5};A program that demonstrates one dimensional arrays is given as follows:Source Code: Program that demonstrates one dimensional arrays in C#using System; namespace ArrayDemo {   class Example   {      static void Main(string[ ] args)      {         int [ ] arr = new int[5] {1, 2, 3, 4, 5};         int i;         Console.WriteLine("Elements in the array are:");         for ( i = 0; i < 5; i++ )         {            Console.WriteLine(arr[i]);         }      }   } }The output of the above program is as follows:Elements in the array are: 1 2 3 4 52-D ArraysTwo dimensional arrays contain multiple rows and columns and each element of the array is identified as arr[i,j] where i and j are the subscripts for row and column index respectively and the name of the array is arr.The 2-D arrays can be declared using the following syntax:data_type[ , ] name_of_array = new data_type[row_size, column_size]; In the above syntax, data_type is the data type of array elements, name_of_array is the name given to the array, new is a keyword that creates an instance of the array,row_size is the number of rows and column_size is the number of columns.One of the methods to assign values in a 2-D array is given as follows:int[ , ] arr = new int [2,2] { {1,4} , {8,3} };A program that demonstrates two dimensional arrays is given as follows:Source Code: Program that demonstrates two dimensional arrays in C#using System; namespace ArrayDemo {   class Example   {      static void Main(string[] args)      {         int[,] arr = new int[2, 3] { {4,1,7}, {3, 8, 2} };         int i, j;         Console.WriteLine("The elements in the 2-D array are:");         for (i = 0; i < 2; i++)         {            for (j = 0; j < 3; j++)            {               Console.Write(arr[i,j]);               Console.Write(" ");            }            Console.WriteLine();         }      }   } }The output of the above program is as follows:The elements in the 2-D array are: 4 1 7 3 8 2Jagged ArraysJagged arrays are arrays of arrays. The arrays in a jagged array can be of different sizes.The declaration of elements in a jagged array are given as follows:int[ ][ ] myArr = new int [4][ ];In the above initialization, myArr is the name of the jagged array. There are 4 elements in the jagged array and each of these elements are 1-D integer arrays.Element initialization in jagged arrays is given as follows:myArr[0] = new int[ ] { 7, 1, 5, 9 }; myArr[1] = new int[ ] { 2, 4, 8 }; myArr[2] = new int[ ] { 1, 5, 8, 2, 9}; myArr[3] = new int[ ] { 4, 3 };Here, each of the array elements are 1-D arrays with sizes 4, 3, 5, 2 respectively.A program that demonstrates jagged arrays is given as follows:Source Code: Program that demonstrates jagged arrays in C#using System; namespace ArrayDemo {   class Example   {      static void Main(string[] args)      {        int[][] myArr = new int[4][];        myArr[0] = new int[ ] { 7, 1, 5, 9 };        myArr[1] = new int[ ] { 2, 4, 8 };        myArr[2] = new int[ ] { 1, 5, 8, 2, 9};        myArr[3] = new int[ ] { 4, 3 };        for (int i = 0; i < myArr.Length; i++)        {            System.Console.Write("Element {0}: ", i);            for (int j = 0; j < myArr[i].Length; j++)            {                System.Console.Write( myArr[i][j] );                System.Console.Write(" ");            }            System.Console.WriteLine();                    }      }   } }The output of the above program is as follows:Element 0: 7 1 5 9 Element 1: 2 4 8 Element 2: 1 5 8 2 9 Element 3: 4 3Param ArraysParam arrays are used if the number of arguments are not fixed in a function. So the user can pass as many arguments as required.A program that demonstrates param arrays is given as follows:Source Code: Program that demonstrates param arrays in C#using System; namespace ArrayDemo {   class Example   {       static int SumOfElements(params int[] p_arr)        {            int sum=0;            foreach (int i in p_arr)            {               sum += i;            }            return sum;        }      static void Main(string[] args)      {            int sum=0;            sum = SumOfElements(4, 8, 7, 3, 1);            Console.WriteLine("Sum of 5 Parameters: {0}", sum);            sum = SumOfElements(5, 7);            Console.WriteLine("Sum of 2 Parameters: {0}", sum);            sum = SumOfElements(10, 7, 9);            Console.WriteLine("Sum of 3 Parameters: {0}", sum);      }   } }The output of the above program is as follows:Sum of 5 Parameters: 23 Sum of 2 Parameters: 12 Sum of 3 Parameters: 26Passing Arrays to FunctionsArrays can be passed as parameters to functions. An example of this is as follows:int[ ] arr = {1, 2, 3, 4, 5}; func(arr);In the above example, the array arr is passed to the function func().A program that demonstrates passing arrays to functions is given as follows:Source Code: Program that demonstrates passing arrays to functions in C#using System; namespace ArrayDemo {   class Example   {      static void func(int[] arr, int n)      {         int i, sum=0;         Console.WriteLine("Array Elements are:");         for (i = 0; i < n; ++i)         {            Console.Write(arr[i]);            Console.Write(" ");         }         Console.WriteLine();         for (i = 0; i < n; ++i)         {            sum += arr[i];         }         Console.WriteLine("Sum of array elements is: {0}",sum);      }      static void Main(string[] args)      {         int[] arr= new int[] {12, 56, 3, 81, 9, 13, 76, 99, 5, 10};         func(arr, 10 ) ;      }   } }The output of the above program is as follows:Array Elements are: 12 56 3 81 9 13 76 99 5 10 Sum of array elements is: 364Array OperationsSome of the array operations are given as follows:Find common elements in three sorted arrays in C#The program that demonstrates finding the common elements in three arrays that are sorted is given as followed:Source Code: Program that finds common elements in three sorted arrays in C#using System; class Demo {    static void commonElements(int []arr1, int []arr2, int []arr3)    {        int i = 0, j = 0, k = 0;        while (i < arr1.Length && j < arr2.Length && k < arr3.Length)        {            if (arr1[i] == arr2[j] && arr2[j] == arr3[k])            {                Console.Write(arr1[i] + " ");                i++;                j++;                k++;            }            else if (arr1[i] < arr2[j])                i++;            else if (arr2[j] < arr3[k])                j++;            else                k++;        }    }    public static void Main()    {        int []arr1 = {1, 11, 45, 89, 90};        int []arr2 = {1, 23, 45, 56, 89, 90};        int []arr3 = {1, 8, 11, 45, 67, 89, 90, 95};        Console.Write("The common elements in the arrays are: ");        commonElements(arr1, arr2, arr3);    } }The output of the above program is as follows:The common elements in the arrays are: 1 45 89 90Dynamic creation of arrays in C#The program that demonstrates the dynamic creation of arrays is given as follows:Source Code: Program that demonstrates the dynamic creation of arrays in C#using System; using System.Collections; namespace CollectionApplication {   class Example   {      static void Main(string[] args)      {         ArrayList myAL = new ArrayList();         myAL.Add(6);         myAL.Add(1);         myAL.Add(9);         myAL.Add(2);         myAL.Add(4);         Console.WriteLine("The number of elements are: {0}", myAL.Count);         Console.Write("The ArrayList is: ");         foreach (int i in myAL)         {            Console.Write(i + " ");         }         Console.WriteLine();      }   } }The output of the above program is as follows:The number of elements are: 5 The ArrayList is: 6 1 9 2 4Concatenation of two arrays in C#To concatenate two arrays, use the Join() method in C#.Source Code: Program that demonstrates the concatenation of two arrays  in C#using System; class Example {    static void Main()    {        string[] str = new string[] { "Concatenation", "in C#" };        string result = string.Join(" ", str);        Console.WriteLine(result);    } }The output of the above program is as follows: Concatenation in C#Intersection of two arrays in C#To perform intersection of two arrays, use the Intersect() method in C#.Source Code: Program that demonstrates the intersection of two arrays in C#using System; using System.Linq; class Example {    static void Main()    {        int[] arr1 = { 56, 12, 89, 67, 1, 45, 9};        int[] arr2 = { 4, 98, 56, 45, 9, 89 };        var arr_intersect = arr1.Intersect(arr2);        Console.WriteLine("The elements in the intersection of the two arrays are:");        foreach (int i in arr_intersect)        {            Console.Write(i + " ");        }    } }The output of the above program is as follows:The elements in the intersection of the two arrays are: 56 89 45 9Mixed Arrays in C#Mixed arrays in C# are a combination of multidimensional arrays and jagged arrays. They are currently obsolete as they were removed by the .NET 4.0 update. A program that demonstrates mixed arrays is given as follows:Source Code: Program that demonstrates mixed arrays in C#using System; using System.Collections.Generic; class Example {    static void Main()    {        List<string> list = new List<string>()        {            "Harry",            "Amy",            "Micheal",            "Lucy",            "Susan",            "Peter"        };        Console.WriteLine("The element count in List is: {0}", list.Count);    } }The output of the above program is as follows:The element count in List is: 6Comparison of two arrays in C#Two arrays in C# can be compared using SequenceEqual(). The program that demonstrates this is given as follows:Source Code: Program that demonstrates comparison of two arrays  in C#using System; using System.Linq; namespace ArrayDemo {   class Example   {      static void Main(string[] args)      {        int[] arr1 = new int[] { 9, 7, 5, 6};        int[] arr2 = new int[] { 9, 7, 5, 6};        Console.WriteLine("The two arrays are equal? {0}", arr1.SequenceEqual(arr2));      }   } }The output of the above program is as follows:The two arrays are equal? True Split even and odd numbers in array into 2 different arrays in C#A program that splits the even and odd numbers in an array into 2 different arrays is given as follows:Source Code: Program that splits the even and odd numbers in an array in C#using System; namespace ArrayDemo { public class Example {  public static void Main(string[] args)  {   int[] arr = new int[] { 45, 12, 9, 36, 77, 54, 7 };   int[] arr1 = new int[5];   int[] arr2 = new int[5];   int i, j = 0, k = 0;   for (i = 0; i < 7; i++)   {    if (arr[i] % 2 == 0)    {       arr1[j] = arr[i];       j++;    }    else    {       arr2[k] = arr[i];       k++;    }   }   Console.Write("Even numbers are: ");   for (i = 0; i < j; i++)   {    Console.Write(arr1[i] + " ");   }   Console.Write("\nOdd numbers are: ");   for (i = 0; i < k; i++)   {    Console.Write(arr2[i] + " ");   }  } } }The output of the above program is as follows:Even numbers are: 12 36 54 Odd numbers are: 45 9 77 7Merge two sorted arrays in C#A program that merges two sorted arrays into a single array is given as follows:Source Code: Program that merges two sorted arrays into a single array in C#using System; using System.Collections.Generic; class Example { static void Main() {  int i = 0;  int j = 0;  int[] arr1 = new int[4] { 1, 23, 35, 49 };  int[] arr2 = new int[4] { 51, 66, 89, 95 };  int[] mergeArr = new int[8];  for (i = 0, j = 0; i < 4; i++)  {    mergeArr[j++] = arr1[i];  }  for (i = 0; i < 4; i++)  {    mergeArr[j++] = arr2[i];  }  Console.Write("The elements of merged array are: ");  for (i = 0; i < 8; i++)  {     Console.Write(mergeArr[i] + " ");  } } }The output of the above program is as follows:The elements of merged array are: 1 23 35 49 51 66 89 95Merge two sorted arrays using List in C#A program that merges two sorted arrays into a single array using lists is given as follows:Source Code: Program that merges two sorted arrays into a single array using lists in C#using System; using System.Collections.Generic; public class Example { public static void Main() {     int[] arr1 = { 1, 2, 3 };     int[] arr2 = { 4, 5, 6 };     var list = new List<int>();     for (int i = 0; i < arr1.Length; i++)       {          list.Add(arr1[i]);          list.Add(arr2[i]);       }     int[] arr3 = list.ToArray(); Console.WriteLine("The merged array is:"); foreach(int i in arr3) {  Console.WriteLine(i); } } }The output of the above program is as follows:The merged array is: 1 4 2 5 3 6Merge two arrays using AddRange() method in C#A program that merges two arrays using AddRange() method is given as follows:Source Code: Program that merges two arrays using AddRange() method in C#using System; using System.Collections.Generic; class Demo {    static void Main()    {        int[] arr1 = { 1, 10, 17, 26, 30 };        int[] arr2 = { 35, 55, 67, 80, 99 };        Console.Write("The first array is: ");        foreach(int i in arr1)        {            Console.Write(i + " ");        }        Console.WriteLine();        Console.Write("The second array is: ");        foreach(int i in arr2)        {            Console.Write(i + " ");        }        Console.WriteLine();        var myList = new List<int>();        myList.AddRange(arr1);        myList.AddRange(arr2);        int[] arr3 = myList.ToArray();        Console.Write("The merged array is: ");        foreach (int i in arr3)        {            Console.Write(i + " ");        }    } }The output of the above program is as follows:The first array is: 1 10 17 26 30 The second array is: 35 55 67 80 99 The merged array is: 1 10 17 26 30 35 55 67 80 99Get the last element from an array in C#A program that obtains the last element of an array is given as follows. We have used the Last() method here to get the last element.Source Code: Program that obtains the last element of an array in C#using System; using System.Collections.Generic; using System.Linq; class Demo {    static void Main()    {        int[] arr = { 1, 6, 24, 25, 37, 40, 49, 50 };        int lastElement = arr.AsQueryable().Last();        Console.WriteLine("The last element of the array is: " + lastElement);    } }The output of the above program is as follows:The last element of the array is: 50Print the contents of an array horizontally in C#A program that prints the contents of an array horizontally is given as follows:Source Code: Program that prints the contents of an array horizontally in C#using System; using System.Linq; using System.IO; class Example {    static void Main()    {        int[] arr = new int[] { 5, 1, 9, 7, 3 };        Console.Write("The array elements are: ");        Console.WriteLine(string.Join(" ", arr));    } }The output of the above program is as follows:The array elements are: 5 1 9 7 3Display the first element from an array in C#A program that displays the first element from an array is given as follows. We have used the First() method to get the first element.Source Code: Program that displays the first element from an array in C#using System; using System.Linq; using System.Collections.Generic; class Example {    static void Main()    {        int[] arr = {1, 3, 4, 7, 9};        int first = arr.AsQueryable().First();        Console.WriteLine("The first element in the array is: {0}", first);    } }The output of the above program is as follows: The first element in the array is: 1Order array elements in C#A program that orders the elements in the array is given as follows:Source Code: Program that orders the elements in the array in C#using System; using System.Linq; using System.Collections.Generic; public class Demo { public static void Main() {    string[] str = { "Harry", "Jack", "Amy", "Matthew", "Joseph" };        IEnumerable<string> strResult =            str.AsQueryable()            .OrderBy(alp => alp.Length).ThenBy(alp => alp);        foreach (string s in strResult)            Console.WriteLine(s);    } }The output of the above program is as follows:Amy Jack Harry Joseph MatthewOrder array elements in descending order in C#A program that orders the elements in the array in descending order is given as follows:Source Code: Program that orders the elements in the array in descending order in C#using System; using System.Linq; using System.Collections.Generic; public class Demo { public static void Main() {    string[] str = { "Harry", "Jack", "Amy", "Matthew", "Joseph" };        IEnumerable<string> strResult =            str.AsQueryable()            .OrderByDescending(ch => ch.Length).ThenBy(ch => ch);        foreach (string s in strResult)            Console.WriteLine(s);    } }The output of the above program is as follows:Matthew Joseph Harry Jack AmyReverse an array in C#A program that reverses an array is given as follows. Use Array.Reverse() method to perform reverse.Source Code: Program that reverses an array in C#using System; class Example {    static void Main()    {        int[] arr = { 12, 3, 67, 54, 99};        Console.Write("The original array is: ");        foreach (int i in arr)        {           Console.Write(i + " ");        }        Array.Reverse(arr);        Console.WriteLine();        Console.Write("The reversed array is: ");        foreach (int i in arr)        {           Console.Write(i + " ");        }    } }The output of the above program is as follows: The original array is: 12 3 67 54 99 The reversed array is: 99 54 67 3 12Array ClassThe Array class is defined in the System namespace. Using Array class, you can easily work with arrays. It is the base class for all the arrays in C#.Properties in Array ClassThe different properties and their description is given as follows:Source: MSDNPropertiesDescriptionIsFixedSizeThis property gets a value indicating whether the Array has a fixed size.IsReadOnlyThis property gets a value indicating whether the Array is read-only.IsSynchronizedThis property gets a value indicating whether access to the Array is synchronized (thread safe).LengthThis property gets the total number of elements in all the dimensions of the Array.LongLengthThis property gets a 64-bit integer that represents the total number of elements in all the dimensions of the Array.RankThis property gets the rank (number of dimensions) of the Array. For example, a one-dimensional array returns 1, a two-dimensional array returns 2, and so on.SyncRootThis property gets an object that can be used to synchronize access to the Array.Methods in Array ClassThe different methods and their description is given as follows:Source: MSDNMethodsDescriptionIsFixedSizeThis property gets a value indicating whether the Array has a fixed size.IsReadOnlyThis property gets a value indicating whether the Array is read-only.IsSynchronizedThis property gets a value indicating whether access to the Array is synchronized (thread safe).LengthThis property gets the total number of elements in all the dimensions of the Array.LongLengthThis property gets a 64-bit integer that represents the total number of elements in all the dimensions of the Array.RankThis property gets the rank (number of dimensions) of the Array. For example, a one-dimensional array returns 1, a two-dimensional array returns 2, and so on.SyncRootThis property gets an object that can be used to synchronize access to the Array.Methods in Array ClassThe different methods and their description is given as follows:Source: MSDNMethodsDescriptionAsReadOnly<T>(T[])This method returns a read-only wrapper for the specified array.BinarySearch(Array, Int32, Int32, Object)This method searches a range of elements in a one-dimensional sorted array for a value, using the IComparable interface implemented by each element of the array and by the specified value.Clear(Array, Int32, Int32)This method sets a range of elements in an array to the default value of each element type.Clone()This method creates a shallow copy of the Array.ConstrainedCopy(Array, Int32, Array, Int32, Int32)This method copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. Guarantees that all changes are undone if the copy does not succeed completely.Copy(Array, Array, Int32)This method copies a range of elements from an Array starting at the first element and pastes them into another Array starting at the first element. The length is specified as a 32-bit integer.CreateInstance(Type, Int32)This method creates a one-dimensional Array of the specified Type and length, with zero-based indexing.Empty<T>()This method returns an empty array.Equals(Object)This method determines whether the specified object is equal to the current object.Exists<T>(T[], Predicate<T>)This method determines whether the specified array contains elements that match the conditions defined by the specified predicate.GetEnumerator()This method returns an IEnumerator for the Array.GetHashCode()This method serves as the default hash function.GetLength(Int32)This method gets a 32-bit integer that represents the number of elements in the specified dimension of the Array.GetType()This method gets the Type of the current instance.GetUpperBound(Int32)This method gets the index of the last element of the specified dimension in the array.GetValue(Int32)This method gets the value at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer.IndexOf(Array, Object)This method searches for the specified object and returns the index of its first occurrence in a one-dimensional array.Initialize()This method initializes every element of the value-type Array by calling the default constructor of the value type.Reverse(Array)This method reverses the sequence of the elements in the entire one-dimensional Array.SetValue(Object, Int32)This method sets a value to the element at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer.Sort(Array)This method sorts the elements in an entire one-dimensional Array using the IComparableimplementation of each element of the Array.ToString()This method returns a string that represents the current object.ArrayClass OperationsSome of the ArrayClass operations are given as follows:Get Upperbound and Lowerbound of a three-dimensional array in C#A program that gets the upperbound and lowerbound of a three-dimensional array is given as follows:Source Code: Program that gets the upperbound and lowerbound of a three dimensional array in C#using System; class Example {    static void Main()    {        int[,,] array = new int[3,4,5];        Console.WriteLine("Upper Bound : {0}",array.GetUpperBound(0).ToString());        Console.WriteLine("Lower Bound : {0}",array.GetLowerBound(0).ToString());        Console.WriteLine("Upper Bound : {0}",array.GetUpperBound(1).ToString());        Console.WriteLine("Lower Bound : {0}",array.GetLowerBound(1).ToString());        Console.WriteLine("Upper Bound : {0}",array.GetUpperBound(2).ToString());        Console.WriteLine("Lower Bound : {0}",array.GetLowerBound(2).ToString());    } }The output of the above program is as follows: Upper Bound : 2 Lower Bound : 0 Upper Bound : 3 Lower Bound : 0 Upper Bound : 4 Lower Bound : 0Sort one dimensional array in descending order using Array Class methodA program that sorts one dimensional array in descending order using Array Class method is given as follows:Source Code: Program that sorts one dimensional array in descending order in C#using System; namespace Demo {    public class MyApplication    {        public static void Main(string[] args)        {            int[] arr = {34, 76, 1, 99, 68};            Console.Write("The original unsorted array is: ");            foreach (int i in arr)            {              Console.Write(i + " ");            }            Array.Sort(arr);            Array.Reverse(arr);            Console.WriteLine();            Console.Write("The sorted array is: ");            for(int i=0; i<arr.Length; i++)            {                Console.Write(arr[i] + " ");            }        }    } }The output of the above program is as follows:The original unsorted array is: 34 76 1 99 68 The sorted array is: 99 76 68 34 1Sorting an arrayA program that sorts an array in C# is given as follows. The Array.Sort() method is used to sort an array.Source Code: Program that sorts an array in C#using System; class Demo {    static void Main()    {        int[] arr = { 23, 8, 2, 99, 67 };        Array.Sort(arr);        Console.WriteLine("The sorted array is: ");        foreach (int i in arr)        {            Console.Write(i + " ");        }    } }The output of the above program is as follows:The sorted array is: 2 8 23 67 99Usage of the ?: conditional operator in C#A program that uses the ?: conditional operator in C# is given as follows:Source Code: Program that uses the ?: conditional operator in C#using System; namespace Example {   class Example   {      static void Main(string[] args)      {         int a, b = 5;         a = ( b == 5 ? 10 : 0 ) ;         Console.WriteLine("a = " + a);         Console.WriteLine("b = " + b);         Console.ReadKey();      }   } }The output of the above program is as follows:a = 10 b = 5Usage of the Clear() method of array class in C#A program that demonstrates the clear() method of array class is given as follows:Source Code: Program that demonstrates the clear() method of array class in C#using System; class Example {    static void Main()    {        int[] arr = new int[] {12, 67, 34, 99, 7};        Console.WriteLine("The original array is given as follows:");        foreach (int i in arr)        {            Console.Write(i + " ");        }        Array.Clear(arr, 0, arr.Length);        Console.WriteLine();        Console.WriteLine("The array after clear() method is given as follows:");        foreach (int i in arr)        {            Console.Write(i + " ");        }    } }The output of the above program is given as follows:The original array is given as follows: 12 67 34 99 7 The array after clear() method is given as follows: 0 0 0 0 0Usage of the Clone() method of array class in C#A program that demonstrates the clone() method of array class is given as follows:Source Code: Program that demonstrates the clone() method of array class in C#using System; class Example {    static void Main()    {        string[] array = { "Clone() method", "in C#"};        Console.WriteLine(string.Join(" ", array));        string[] arrayClone = array.Clone() as string[];        Console.WriteLine(string.Join(" ", arrayClone));    } }The output of the above program is as follows:Clone() method in C# Clone() method in C#Usage of the Copy(, ,) method of array class in C#A program that demonstrates the copy(, ,) method of array class is given as follows:Source Code: Program that demonstrates the copy(, ,) method of array class in C#using System; class Example {    static void Main()    {        int[] arr1 = new int[5] { 45, 12, 9, 77, 34};        int[] arr2 = new int[5];        Array.Copy(arr1, arr2, 5);        Console.WriteLine("arr1: ");        foreach (int i in arr1)        {            Console.Write(i + " ");        }        Console.WriteLine();        Console.WriteLine("arr2: ");        foreach (int i in arr2)        {            Console.Write(i + " ");        }    } }The output of the above program is as follows:arr1: 45 12 9 77 34 arr2: 45 12 9 77 34Usage of the CopyTo(,) method of array class in C#A program that demonstrates the CopyTo(,) method of array class is given as follows:Source Code: Program that demonstrates the CopyTo(,) method of array class in C#using System; class Example {    static void Main()    {        int[] arr1 = new int[5]{12, 55, 9, 1, 78};        int[] arr2 = new int[5];        Console.WriteLine("arr1: ");        foreach (int i in arr1)        {            Console.Write(i + " ");        }        arr1.CopyTo(arr2,0 );        Console.WriteLine();        Console.WriteLine("arr2: ");        foreach (int i in arr2)        {            Console.Write(i + " ");        }    } }The output of the above program is as follows:arr1: 12 55 9 1 78 arr2: 12 55 9 1 78Usage of the GetLength() method of array class in C#A program that demonstrates the GetLength() method of array class is given as follows:Source Code: Program that demonstrates the GetLength() method of array class in C#using System; class Example {    static void Main()    {        int[,] a = new int[5, 2];        int length1 = a.GetLength(0);        int length2 = a.GetLength(1);        Console.WriteLine(length1);        Console.WriteLine(length2);    } }The output of the above program is as follows:5 2Usage of the GetLongLength() method of array class in C#A program that demonstrates the GetLongLength() method of array class is given as follows:Source Code: Program that demonstrates the GetLongLength() method of array class in C#using System; class Example {    static void Main()    {        int[,] arr1 = new int[6, 2];        int len1 = arr1.GetLength(0);        Console.WriteLine(len1);        long[,] arr2= new long[76, 89];        long len2 = arr2.GetLongLength(0);        Console.WriteLine(len2);    } }The output of the above program is as follows:6 76Usage of the GetLowerBound() method of array class in C#A program that demonstrates the GetLowerBound() method of array class is given as follows:Source Code: Program that demonstrates the GetLowerBound() method of array class in C#using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace lowerBound {    class Example    {        static void Main(string[] args)        {            Array a = Array.CreateInstance(typeof(String), 5);            a.SetValue("James", 0);            a.SetValue("Lily", 1);            a.SetValue("Harry", 2);            a.SetValue("Bill", 3);            a.SetValue("Charlie", 4);            Console.WriteLine("The lower bound is: {0}", a.GetLowerBound(0).ToString());        }    } }The output of the above program is as follows:The lower bound is: 0Usage of the GetType() method of array class in C#A program that demonstrates the GetType() method of array class is given as follows:Source Code: Program that demonstrates the GetType() method of array class in C#using System; public class Example {   public static void Main()   {      object[] values = { (int) 67, (long) 84658};      foreach (var val in values)      {         Type t = val.GetType();         if (t.Equals(typeof(int)))               Console.WriteLine("{0} is an integer data type.", val);         else            Console.WriteLine("{0} is not an integer data type.", val);      }   } }The output of the above program is as follows:67 is an integer data type. 84658 is not an integer data type.Usage of the GetUpperBound() method of array class in C#A program that demonstrates the GetUpperBound() method of array class is given as follows:Source Code: Program that demonstrates the GetUpperBound() method of array class in C#using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Demo {    class Example    {        static void Main(string[] args)        {            Array a = Array.CreateInstance(typeof(String), 5);            a.SetValue("James", 0);            a.SetValue("Lily", 1);            a.SetValue("Harry", 2);            a.SetValue("Bill", 3);            a.SetValue("Charlie", 4);            Console.WriteLine("The upper bound is: {0}",a.GetUpperBound(0).ToString());        }    } }The output of the above program is as follows:The upper bound is: 4Usage of the GetValue() method of array class in C#A program that demonstrates the GetValue() method of array class is given as follows:Source Code: Program that demonstrates the GetValue() method of array class in C#using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Demo {    class Example    {        static void Main(string[] args)        {            Array a = Array.CreateInstance(typeof(String), 3, 6);            a.SetValue("Apple", 0, 0);              a.SetValue("Mango", 0, 1);              a.SetValue("Cherry", 0, 2);              a.SetValue("Grapes", 0, 3);              a.SetValue("Melon", 1, 4);              a.SetValue("Guava", 1, 5);              a.SetValue("Plum", 1, 2);              a.SetValue("Berry", 1, 3);            int x = a.GetLength(0);              int y = a.GetLength(1);            for (int i = 0; i < x; i++)                for (int j = 0; j < y; j++)                Console.WriteLine( a.GetValue(i, j));          }    } }The output of the above program is as follows:Apple Mango Cherry Grapes Plum Berry Melon GuavaUsage of the IndexOf(,) method of array class in C#A program that demonstrates the IndexOf(,) method of array class is given as follows:Source Code: Program that demonstrates the IndexOf(,) method of array class in C#using System; class Example {    static void Main()    {        int[] a = new int[5] {45, 78, 12, 99, 4};        int index = Array.IndexOf(a, 12);        Console.WriteLine("The index of 12 is {0}", index);    } }The output of the above program is as follows:The index of 12 is 2
logo

C# Tutorial

Arrays in C#

Arrays contain a collection of data elements of the same type. These data elements are stored in contiguous memory locations. Some of the arrays in C# are 1-D arrays, 2-D arrays, Jagged arrays, Param arrays etc. Details about these are given as follows:

1-D Arrays

One dimensional arrays consist of a single row with as many elements as required. These arrays can be declared using the following syntax:

data_type[ ] name_of_array;

In the above syntax, data_type is the data type of array elements and name_of_array is the name given to the array.

The syntax to initialize the array is given as follows:

data_type[ ] name_of_array = new data_type[array_size];

In the above syntax, data_type is the data type of array elements, name_of_array is the name given to the array, new is a keyword that creates an instance of the array and array_size is the size of the array.

There are many methods to assign values to the array. Some of these are given as follows:

int[ ] arr = { 1, 2, 3, 4, 5}; 
int[ ] arr = new int[] { 1, 2, 3, 4, 5};
int[ ] arr = new int[5] { 1, 2, 3, 4, 5};

A program that demonstrates one dimensional arrays is given as follows:

Source Code: Program that demonstrates one dimensional arrays in C#

using System;
namespace ArrayDemo
{
  class Example
  {
     static void Main(string[ ] args)
     {
        int [ ] arr = new int[5] {1, 2, 3, 4, 5};
        int i;
        Console.WriteLine("Elements in the array are:");
        for ( i = 0; i < 5; i++ )
        {
           Console.WriteLine(arr[i]);
        }
     }
  }
}

The output of the above program is as follows:

Elements in the array are:
1
2
3
4
5

2-D Arrays

Two dimensional arrays contain multiple rows and columns and each element of the array is identified as arr[i,j] where i and j are the subscripts for row and column index respectively and the name of the array is arr.

The 2-D arrays can be declared using the following syntax:

data_type[ , ] name_of_array = new data_type[row_size, column_size]; 

In the above syntax, data_type is the data type of array elements, name_of_array is the name given to the array, new is a keyword that creates an instance of the array,row_size is the number of rows and column_size is the number of columns.

One of the methods to assign values in a 2-D array is given as follows:

int[ , ] arr = new int [2,2] { {1,4} , {8,3} };

A program that demonstrates two dimensional arrays is given as follows:

Source Code: Program that demonstrates two dimensional arrays in C#

using System;
namespace ArrayDemo
{
  class Example
  {
     static void Main(string[] args)
     {
        int[,] arr = new int[2, 3] { {4,1,7}, {3, 8, 2} };
        int i, j;
        Console.WriteLine("The elements in the 2-D array are:");
        for (i = 0; i < 2; i++)
        {
           for (j = 0; j < 3; j++)
           {
              Console.Write(arr[i,j]);
              Console.Write(" ");
           }
           Console.WriteLine();
        }
     }
  }
}

The output of the above program is as follows:

The elements in the 2-D array are:
4 1 7
3 8 2

Jagged Arrays

Jagged arrays are arrays of arrays. The arrays in a jagged array can be of different sizes.

The declaration of elements in a jagged array are given as follows:

int[ ][ ] myArr = new int [4][ ];

In the above initialization, myArr is the name of the jagged array. There are 4 elements in the jagged array and each of these elements are 1-D integer arrays.

Element initialization in jagged arrays is given as follows:

myArr[0] = new int[ ] { 7, 1, 5, 9 };
myArr[1] = new int[ ] { 2, 4, 8 };
myArr[2] = new int[ ] { 1, 5, 8, 2, 9};
myArr[3] = new int[ ] { 4, 3 };

Here, each of the array elements are 1-D arrays with sizes 4, 3, 5, 2 respectively.

A program that demonstrates jagged arrays is given as follows:

Source Code: Program that demonstrates jagged arrays in C#

using System;
namespace ArrayDemo
{
  class Example
  {
     static void Main(string[] args)
     {
       int[][] myArr = new int[4][];
       myArr[0] = new int[ ] { 7, 1, 5, 9 };
       myArr[1] = new int[ ] { 2, 4, 8 };
       myArr[2] = new int[ ] { 1, 5, 8, 2, 9};
       myArr[3] = new int[ ] { 4, 3 };
       for (int i = 0; i < myArr.Length; i++)
       {
           System.Console.Write("Element {0}: ", i);
           for (int j = 0; j < myArr[i].Length; j++)
           {
               System.Console.Write( myArr[i][j] );
               System.Console.Write(" ");
           }
           System.Console.WriteLine();            
       }
     }
  }
}

The output of the above program is as follows:

Element 0: 7 1 5 9
Element 1: 2 4 8
Element 2: 1 5 8 2 9
Element 3: 4 3

Param Arrays

Param arrays are used if the number of arguments are not fixed in a function. So the user can pass as many arguments as required.

A program that demonstrates param arrays is given as follows:

Source Code: Program that demonstrates param arrays in C#

using System;
namespace ArrayDemo
{
  class Example
  {
      static int SumOfElements(params int[] p_arr)
       {
           int sum=0;
           foreach (int i in p_arr)
           {
              sum += i;
           }
           return sum;
       }
     static void Main(string[] args)
     {
           int sum=0;
           sum = SumOfElements(4, 8, 7, 3, 1);
           Console.WriteLine("Sum of 5 Parameters: {0}", sum);
           sum = SumOfElements(5, 7);
           Console.WriteLine("Sum of 2 Parameters: {0}", sum);
           sum = SumOfElements(10, 7, 9);
           Console.WriteLine("Sum of 3 Parameters: {0}", sum);
     }
  }
}

The output of the above program is as follows:

Sum of 5 Parameters: 23
Sum of 2 Parameters: 12
Sum of 3 Parameters: 26

Passing Arrays to Functions

Arrays can be passed as parameters to functions. An example of this is as follows:

int[ ] arr = {1, 2, 3, 4, 5};
func(arr);

In the above example, the array arr is passed to the function func().

A program that demonstrates passing arrays to functions is given as follows:

Source Code: Program that demonstrates passing arrays to functions in C#

using System;
namespace ArrayDemo
{
  class Example
  {
     static void func(int[] arr, int n)
     {
        int i, sum=0;
        Console.WriteLine("Array Elements are:");
        for (i = 0; i < n; ++i)
        {
           Console.Write(arr[i]);
           Console.Write(" ");
        }
        Console.WriteLine();
        for (i = 0; i < n; ++i)
        {
           sum += arr[i];
        }
        Console.WriteLine("Sum of array elements is: {0}",sum);
     }
     static void Main(string[] args)
     {
        int[] arr= new int[] {12, 56, 3, 81, 9, 13, 76, 99, 5, 10};
        func(arr, 10 ) ;
     }
  }
}

The output of the above program is as follows:

Array Elements are:
12 56 3 81 9 13 76 99 5 10
Sum of array elements is: 364

Array Operations

Some of the array operations are given as follows:

Find common elements in three sorted arrays in C#

The program that demonstrates finding the common elements in three arrays that are sorted is given as followed:

Source Code: Program that finds common elements in three sorted arrays in C#

using System;
class Demo
{
   static void commonElements(int []arr1, int []arr2, int []arr3)
   {
       int i = 0, j = 0, k = 0;
       while (i < arr1.Length && j < arr2.Length && k < arr3.Length)
       {
           if (arr1[i] == arr2[j] && arr2[j] == arr3[k])
           {
               Console.Write(arr1[i] + " ");
               i++;
               j++;
               k++;
           }
           else if (arr1[i] < arr2[j])
               i++;
           else if (arr2[j] < arr3[k])
               j++;
           else
               k++;
       }
   }
   public static void Main()
   {
       int []arr1 = {1, 11, 45, 89, 90};
       int []arr2 = {1, 23, 45, 56, 89, 90};
       int []arr3 = {1, 8, 11, 45, 67, 89, 90, 95};
       Console.Write("The common elements in the arrays are: ");
       commonElements(arr1, arr2, arr3);
   }
}

The output of the above program is as follows:

The common elements in the arrays are: 1 45 89 90

Dynamic creation of arrays in C#

The program that demonstrates the dynamic creation of arrays is given as follows:

Source Code: Program that demonstrates the dynamic creation of arrays in C#

using System;
using System.Collections;
namespace CollectionApplication
{
  class Example
  {
     static void Main(string[] args)
     {
        ArrayList myAL = new ArrayList();
        myAL.Add(6);
        myAL.Add(1);
        myAL.Add(9);
        myAL.Add(2);
        myAL.Add(4);
        Console.WriteLine("The number of elements are: {0}", myAL.Count);
        Console.Write("The ArrayList is: ");
        foreach (int i in myAL)
        {
           Console.Write(i + " ");
        }
        Console.WriteLine();
     }
  }
}

The output of the above program is as follows:

The number of elements are: 5
The ArrayList is: 6 1 9 2 4

Concatenation of two arrays in C#

To concatenate two arrays, use the Join() method in C#.

Source Code: Program that demonstrates the concatenation of two arrays  in C#

using System;
class Example
{
   static void Main()
   {
       string[] str = new string[] { "Concatenation", "in C#" };
       string result = string.Join(" ", str);
       Console.WriteLine(result);
   }
}

The output of the above program is as follows: 

Concatenation in C#

Intersection of two arrays in C#

To perform intersection of two arrays, use the Intersect() method in C#.

Source Code: Program that demonstrates the intersection of two arrays in C#

using System;
using System.Linq;
class Example
{
   static void Main()
   {
       int[] arr1 = { 56, 12, 89, 67, 1, 45, 9};
       int[] arr2 = { 4, 98, 56, 45, 9, 89 };
       var arr_intersect = arr1.Intersect(arr2);
       Console.WriteLine("The elements in the intersection of the two arrays are:");
       foreach (int i in arr_intersect)
       {
           Console.Write(i + " ");
       }
   }
}

The output of the above program is as follows:

The elements in the intersection of the two arrays are:
56 89 45 9

Mixed Arrays in C#

Mixed arrays in C# are a combination of multidimensional arrays and jagged arrays. They are currently obsolete as they were removed by the .NET 4.0 update. A program that demonstrates mixed arrays is given as follows:

Source Code: Program that demonstrates mixed arrays in C#

using System;
using System.Collections.Generic;
class Example
{
   static void Main()
   {
       List<string> list = new List<string>()
       {
           "Harry",
           "Amy",
           "Micheal",
           "Lucy",
           "Susan",
           "Peter"
       };
       Console.WriteLine("The element count in List is: {0}", list.Count);
   }
}

The output of the above program is as follows:

The element count in List is: 6

Comparison of two arrays in C#

Two arrays in C# can be compared using SequenceEqual(). The program that demonstrates this is given as follows:

Source Code: Program that demonstrates comparison of two arrays  in C#

using System;
using System.Linq;
namespace ArrayDemo
{
  class Example
  {
     static void Main(string[] args)
     {
       int[] arr1 = new int[] { 9, 7, 5, 6};
       int[] arr2 = new int[] { 9, 7, 5, 6};
       Console.WriteLine("The two arrays are equal? {0}", arr1.SequenceEqual(arr2));
     }
  }
}

The output of the above program is as follows:

The two arrays are equal? True 

Split even and odd numbers in array into 2 different arrays in C#

A program that splits the even and odd numbers in an array into 2 different arrays is given as follows:

Source Code: Program that splits the even and odd numbers in an array in C#

using System;
namespace ArrayDemo
{
public class Example
{
 public static void Main(string[] args)
 {
  int[] arr = new int[] { 45, 12, 9, 36, 77, 54, 7 };
  int[] arr1 = new int[5];
  int[] arr2 = new int[5];
  int i, j = 0, k = 0;
  for (i = 0; i < 7; i++)
  {
   if (arr[i] % 2 == 0)
   {
      arr1[j] = arr[i];
      j++;
   }
   else
   {
      arr2[k] = arr[i];
      k++;
   }
  }
  Console.Write("Even numbers are: ");
  for (i = 0; i < j; i++)
  {
   Console.Write(arr1[i] + " ");
  }
  Console.Write("\nOdd numbers are: ");
  for (i = 0; i < k; i++)
  {
   Console.Write(arr2[i] + " ");
  }
 }
}
}

The output of the above program is as follows:

Even numbers are: 12 36 54
Odd numbers are: 45 9 77 7

Merge two sorted arrays in C#

A program that merges two sorted arrays into a single array is given as follows:

Source Code: Program that merges two sorted arrays into a single array in C#

using System;
using System.Collections.Generic;
class Example
{
static void Main()
{
 int i = 0;
 int j = 0;
 int[] arr1 = new int[4] { 1, 23, 35, 49 };
 int[] arr2 = new int[4] { 51, 66, 89, 95 };
 int[] mergeArr = new int[8];
 for (i = 0, j = 0; i < 4; i++)
 {
   mergeArr[j++] = arr1[i];
 }
 for (i = 0; i < 4; i++)
 {
   mergeArr[j++] = arr2[i];
 }
 Console.Write("The elements of merged array are: ");
 for (i = 0; i < 8; i++)
 {
    Console.Write(mergeArr[i] + " ");
 }
}
}

The output of the above program is as follows:

The elements of merged array are: 1 23 35 49 51 66 89 95

Merge two sorted arrays using List in C#

A program that merges two sorted arrays into a single array using lists is given as follows:

Source Code: Program that merges two sorted arrays into a single array using lists in C#

using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
    int[] arr1 = { 1, 2, 3 };
    int[] arr2 = { 4, 5, 6 };
    var list = new List<int>();
    for (int i = 0; i < arr1.Length; i++)
      {
         list.Add(arr1[i]);
         list.Add(arr2[i]);
      }
    int[] arr3 = list.ToArray();
Console.WriteLine("The merged array is:");
foreach(int i in arr3)
{
 Console.WriteLine(i);
}
}
}

The output of the above program is as follows:

The merged array is:
1
4
2
5
3
6

Merge two arrays using AddRange() method in C#

A program that merges two arrays using AddRange() method is given as follows:

Source Code: Program that merges two arrays using AddRange() method in C#

using System;
using System.Collections.Generic;
class Demo
{
   static void Main()
   {
       int[] arr1 = { 1, 10, 17, 26, 30 };
       int[] arr2 = { 35, 55, 67, 80, 99 };
       Console.Write("The first array is: ");
       foreach(int i in arr1)
       {
           Console.Write(i + " ");
       }
       Console.WriteLine();
       Console.Write("The second array is: ");
       foreach(int i in arr2)
       {
           Console.Write(i + " ");
       }
       Console.WriteLine();
       var myList = new List<int>();
       myList.AddRange(arr1);
       myList.AddRange(arr2);
       int[] arr3 = myList.ToArray();
       Console.Write("The merged array is: ");
       foreach (int i in arr3)
       {
           Console.Write(i + " ");
       }
   }
}

The output of the above program is as follows:

The first array is: 1 10 17 26 30
The second array is: 35 55 67 80 99
The merged array is: 1 10 17 26 30 35 55 67 80 99

Get the last element from an array in C#

A program that obtains the last element of an array is given as follows. We have used the Last() method here to get the last element.

Source Code: Program that obtains the last element of an array in C#

using System;
using System.Collections.Generic;
using System.Linq;
class Demo
{
   static void Main()
   {
       int[] arr = { 1, 6, 24, 25, 37, 40, 49, 50 };
       int lastElement = arr.AsQueryable().Last();
       Console.WriteLine("The last element of the array is: " + lastElement);
   }
}

The output of the above program is as follows:

The last element of the array is: 50

Print the contents of an array horizontally in C#

A program that prints the contents of an array horizontally is given as follows:

Source Code: Program that prints the contents of an array horizontally in C#

using System;
using System.Linq;
using System.IO;
class Example
{
   static void Main()
   {
       int[] arr = new int[] { 5, 1, 9, 7, 3 };
       Console.Write("The array elements are: ");
       Console.WriteLine(string.Join(" ", arr));
   }
}

The output of the above program is as follows:

The array elements are: 5 1 9 7 3

Display the first element from an array in C#

A program that displays the first element from an array is given as follows. We have used the First() method to get the first element.

Source Code: Program that displays the first element from an array in C#

using System;
using System.Linq;
using System.Collections.Generic;
class Example
{
   static void Main()
   {
       int[] arr = {1, 3, 4, 7, 9};
       int first = arr.AsQueryable().First();
       Console.WriteLine("The first element in the array is: {0}", first);
   }
}

The output of the above program is as follows: 

The first element in the array is: 1

Order array elements in C#

A program that orders the elements in the array is given as follows:

Source Code: Program that orders the elements in the array in C#

using System;
using System.Linq;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
   string[] str = { "Harry", "Jack", "Amy", "Matthew", "Joseph" };
       IEnumerable<string> strResult =
           str.AsQueryable()
           .OrderBy(alp => alp.Length).ThenBy(alp => alp);
       foreach (string s in strResult)
           Console.WriteLine(s);
   }
}

The output of the above program is as follows:

Amy
Jack
Harry
Joseph
Matthew

Order array elements in descending order in C#

A program that orders the elements in the array in descending order is given as follows:

Source Code: Program that orders the elements in the array in descending order in C#

using System;
using System.Linq;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
   string[] str = { "Harry", "Jack", "Amy", "Matthew", "Joseph" };
       IEnumerable<string> strResult =
           str.AsQueryable()
           .OrderByDescending(ch => ch.Length).ThenBy(ch => ch);
       foreach (string s in strResult)
           Console.WriteLine(s);
   }
}

The output of the above program is as follows:

Matthew
Joseph
Harry
Jack
Amy

Reverse an array in C#

A program that reverses an array is given as follows. Use Array.Reverse() method to perform reverse.

Source Code: Program that reverses an array in C#

using System;
class Example
{
   static void Main()
   {
       int[] arr = { 12, 3, 67, 54, 99};
       Console.Write("The original array is: ");
       foreach (int i in arr)
       {
          Console.Write(i + " ");
       }
       Array.Reverse(arr);
       Console.WriteLine();
       Console.Write("The reversed array is: ");
       foreach (int i in arr)
       {
          Console.Write(i + " ");
       }
   }
}

The output of the above program is as follows: 

The original array is: 12 3 67 54 99
The reversed array is: 99 54 67 3 12

Array Class

The Array class is defined in the System namespace. Using Array class, you can easily work with arrays. It is the base class for all the arrays in C#.

Properties in Array Class

The different properties and their description is given as follows:

Source: MSDN

PropertiesDescription
IsFixedSizeThis property gets a value indicating whether the Array has a fixed size.
IsReadOnlyThis property gets a value indicating whether the Array is read-only.
IsSynchronizedThis property gets a value indicating whether access to the Array is synchronized (thread safe).
LengthThis property gets the total number of elements in all the dimensions of the Array.
LongLengthThis property gets a 64-bit integer that represents the total number of elements in all the dimensions of the Array.
RankThis property gets the rank (number of dimensions) of the Array. For example, a one-dimensional array returns 1, a two-dimensional array returns 2, and so on.
SyncRootThis property gets an object that can be used to synchronize access to the Array.

Methods in Array Class

The different methods and their description is given as follows:

Source: MSDN

MethodsDescription
IsFixedSizeThis property gets a value indicating whether the Array has a fixed size.
IsReadOnlyThis property gets a value indicating whether the Array is read-only.
IsSynchronizedThis property gets a value indicating whether access to the Array is synchronized (thread safe).
LengthThis property gets the total number of elements in all the dimensions of the Array.
LongLengthThis property gets a 64-bit integer that represents the total number of elements in all the dimensions of the Array.
RankThis property gets the rank (number of dimensions) of the Array. For example, a one-dimensional array returns 1, a two-dimensional array returns 2, and so on.
SyncRootThis property gets an object that can be used to synchronize access to the Array.

Methods in Array Class

The different methods and their description is given as follows:

Source: MSDN

MethodsDescription
AsReadOnly<T>(T[])This method returns a read-only wrapper for the specified array.
BinarySearch(Array, Int32, Int32, Object)This method searches a range of elements in a one-dimensional sorted array for a value, using the IComparable interface implemented by each element of the array and by the specified value.
Clear(Array, Int32, Int32)This method sets a range of elements in an array to the default value of each element type.
Clone()This method creates a shallow copy of the Array.
ConstrainedCopy(Array, Int32, Array, Int32, Int32)This method copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. Guarantees that all changes are undone if the copy does not succeed completely.
Copy(Array, Array, Int32)This method copies a range of elements from an Array starting at the first element and pastes them into another Array starting at the first element. The length is specified as a 32-bit integer.
CreateInstance(Type, Int32)This method creates a one-dimensional Array of the specified Type and length, with zero-based indexing.
Empty<T>()This method returns an empty array.
Equals(Object)This method determines whether the specified object is equal to the current object.
Exists<T>(T[], Predicate<T>)This method determines whether the specified array contains elements that match the conditions defined by the specified predicate.
GetEnumerator()This method returns an IEnumerator for the Array.
GetHashCode()This method serves as the default hash function.
GetLength(Int32)This method gets a 32-bit integer that represents the number of elements in the specified dimension of the Array.
GetType()This method gets the Type of the current instance.
GetUpperBound(Int32)This method gets the index of the last element of the specified dimension in the array.
GetValue(Int32)This method gets the value at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer.
IndexOf(Array, Object)This method searches for the specified object and returns the index of its first occurrence in a one-dimensional array.
Initialize()This method initializes every element of the value-type Array by calling the default constructor of the value type.
Reverse(Array)This method reverses the sequence of the elements in the entire one-dimensional Array.
SetValue(Object, Int32)This method sets a value to the element at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer.
Sort(Array)This method sorts the elements in an entire one-dimensional Array using the IComparableimplementation of each element of the Array.
ToString()This method returns a string that represents the current object.

ArrayClass Operations

Some of the ArrayClass operations are given as follows:

Get Upperbound and Lowerbound of a three-dimensional array in C#

A program that gets the upperbound and lowerbound of a three-dimensional array is given as follows:

Source Code: Program that gets the upperbound and lowerbound of a three dimensional array in C#

using System;
class Example
{
   static void Main()
   {
       int[,,] array = new int[3,4,5];
       Console.WriteLine("Upper Bound : {0}",array.GetUpperBound(0).ToString());
       Console.WriteLine("Lower Bound : {0}",array.GetLowerBound(0).ToString());
       Console.WriteLine("Upper Bound : {0}",array.GetUpperBound(1).ToString());
       Console.WriteLine("Lower Bound : {0}",array.GetLowerBound(1).ToString());
       Console.WriteLine("Upper Bound : {0}",array.GetUpperBound(2).ToString());
       Console.WriteLine("Lower Bound : {0}",array.GetLowerBound(2).ToString());
   }
}

The output of the above program is as follows: 

Upper Bound : 2
Lower Bound : 0
Upper Bound : 3
Lower Bound : 0
Upper Bound : 4
Lower Bound : 0

Sort one dimensional array in descending order using Array Class method

A program that sorts one dimensional array in descending order using Array Class method is given as follows:

Source Code: Program that sorts one dimensional array in descending order in C#

using System;
namespace Demo
{
   public class MyApplication
   {
       public static void Main(string[] args)
       {
           int[] arr = {34, 76, 1, 99, 68};
           Console.Write("The original unsorted array is: ");
           foreach (int i in arr)
           {
             Console.Write(i + " ");
           }
           Array.Sort(arr);
           Array.Reverse(arr);
           Console.WriteLine();
           Console.Write("The sorted array is: ");
           for(int i=0; i<arr.Length; i++)
           {
               Console.Write(arr[i] + " ");
           }
       }
   }
}

The output of the above program is as follows:

The original unsorted array is: 34 76 1 99 68
The sorted array is: 99 76 68 34 1

Sorting an array

A program that sorts an array in C# is given as follows. The Array.Sort() method is used to sort an array.

Source Code: Program that sorts an array in C#

using System;
class Demo
{
   static void Main()
   {
       int[] arr = { 23, 8, 2, 99, 67 };
       Array.Sort(arr);
       Console.WriteLine("The sorted array is: ");
       foreach (int i in arr)
       {
           Console.Write(i + " ");
       }
   }
}

The output of the above program is as follows:

The sorted array is:
2 8 23 67 99

Usage of the ?: conditional operator in C#

A program that uses the ?: conditional operator in C# is given as follows:

Source Code: Program that uses the ?: conditional operator in C#

using System;
namespace Example
{
  class Example
  {
     static void Main(string[] args)
     {
        int a, b = 5;
        a = ( b == 5 ? 10 : 0 ) ;
        Console.WriteLine("a = " + a);
        Console.WriteLine("b = " + b);
        Console.ReadKey();
     }
  }
}

The output of the above program is as follows:

a = 10
b = 5

Usage of the Clear() method of array class in C#

A program that demonstrates the clear() method of array class is given as follows:

Source Code: Program that demonstrates the clear() method of array class in C#

using System;
class Example
{
   static void Main()
   {
       int[] arr = new int[] {12, 67, 34, 99, 7};
       Console.WriteLine("The original array is given as follows:");
       foreach (int i in arr)
       {
           Console.Write(i + " ");
       }
       Array.Clear(arr, 0, arr.Length);
       Console.WriteLine();
       Console.WriteLine("The array after clear() method is given as follows:");
       foreach (int i in arr)
       {
           Console.Write(i + " ");
       }
   }
}

The output of the above program is given as follows:

The original array is given as follows:
12 67 34 99 7
The array after clear() method is given as follows:
0 0 0 0 0

Usage of the Clone() method of array class in C#

A program that demonstrates the clone() method of array class is given as follows:

Source Code: Program that demonstrates the clone() method of array class in C#

using System;
class Example
{
   static void Main()
   {
       string[] array = { "Clone() method", "in C#"};
       Console.WriteLine(string.Join(" ", array));
       string[] arrayClone = array.Clone() as string[];
       Console.WriteLine(string.Join(" ", arrayClone));
   }
}

The output of the above program is as follows:

Clone() method in C#
Clone() method in C#

Usage of the Copy(, ,) method of array class in C#

A program that demonstrates the copy(, ,) method of array class is given as follows:

Source Code: Program that demonstrates the copy(, ,) method of array class in C#

using System;
class Example
{
   static void Main()
   {
       int[] arr1 = new int[5] { 45, 12, 9, 77, 34};
       int[] arr2 = new int[5];
       Array.Copy(arr1, arr2, 5);
       Console.WriteLine("arr1: ");
       foreach (int i in arr1)
       {
           Console.Write(i + " ");
       }
       Console.WriteLine();
       Console.WriteLine("arr2: ");
       foreach (int i in arr2)
       {
           Console.Write(i + " ");
       }
   }
}

The output of the above program is as follows:

arr1:
45 12 9 77 34
arr2:
45 12 9 77 34

Usage of the CopyTo(,) method of array class in C#

A program that demonstrates the CopyTo(,) method of array class is given as follows:

Source Code: Program that demonstrates the CopyTo(,) method of array class in C#

using System;
class Example
{
   static void Main()
   {
       int[] arr1 = new int[5]{12, 55, 9, 1, 78};
       int[] arr2 = new int[5];
       Console.WriteLine("arr1: ");
       foreach (int i in arr1)
       {
           Console.Write(i + " ");
       }
       arr1.CopyTo(arr2,0 );
       Console.WriteLine();
       Console.WriteLine("arr2: ");
       foreach (int i in arr2)
       {
           Console.Write(i + " ");
       }
   }
}

The output of the above program is as follows:

arr1:
12 55 9 1 78
arr2:
12 55 9 1 78

Usage of the GetLength() method of array class in C#

A program that demonstrates the GetLength() method of array class is given as follows:

Source Code: Program that demonstrates the GetLength() method of array class in C#

using System;
class Example
{
   static void Main()
   {
       int[,] a = new int[5, 2];
       int length1 = a.GetLength(0);
       int length2 = a.GetLength(1);
       Console.WriteLine(length1);
       Console.WriteLine(length2);
   }
}

The output of the above program is as follows:

5
2

Usage of the GetLongLength() method of array class in C#

A program that demonstrates the GetLongLength() method of array class is given as follows:

Source Code: Program that demonstrates the GetLongLength() method of array class in C#

using System;
class Example
{
   static void Main()
   {
       int[,] arr1 = new int[6, 2];
       int len1 = arr1.GetLength(0);
       Console.WriteLine(len1);
       long[,] arr2= new long[76, 89];
       long len2 = arr2.GetLongLength(0);
       Console.WriteLine(len2);
   }
}

The output of the above program is as follows:

6
76

Usage of the GetLowerBound() method of array class in C#

A program that demonstrates the GetLowerBound() method of array class is given as follows:

Source Code: Program that demonstrates the GetLowerBound() method of array class in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace lowerBound
{
   class Example
   {
       static void Main(string[] args)
       {
           Array a = Array.CreateInstance(typeof(String), 5);
           a.SetValue("James", 0);
           a.SetValue("Lily", 1);
           a.SetValue("Harry", 2);
           a.SetValue("Bill", 3);
           a.SetValue("Charlie", 4);
           Console.WriteLine("The lower bound is: {0}", a.GetLowerBound(0).ToString());
       }
   }
}

The output of the above program is as follows:

The lower bound is: 0

Usage of the GetType() method of array class in C#

A program that demonstrates the GetType() method of array class is given as follows:

Source Code: Program that demonstrates the GetType() method of array class in C#

using System;
public class Example
{
  public static void Main()
  {
     object[] values = { (int) 67, (long) 84658};
     foreach (var val in values)
     {
        Type t = val.GetType();
        if (t.Equals(typeof(int)))   
           Console.WriteLine("{0} is an integer data type.", val);
        else
           Console.WriteLine("{0} is not an integer data type.", val);
     }
  }
}

The output of the above program is as follows:

67 is an integer data type.
84658 is not an integer data type.

Usage of the GetUpperBound() method of array class in C#

A program that demonstrates the GetUpperBound() method of array class is given as follows:

Source Code: Program that demonstrates the GetUpperBound() method of array class in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo
{
   class Example
   {
       static void Main(string[] args)
       {
           Array a = Array.CreateInstance(typeof(String), 5);
           a.SetValue("James", 0);
           a.SetValue("Lily", 1);
           a.SetValue("Harry", 2);
           a.SetValue("Bill", 3);
           a.SetValue("Charlie", 4);
           Console.WriteLine("The upper bound is: {0}",a.GetUpperBound(0).ToString());
       }
   }
}

The output of the above program is as follows:

The upper bound is: 4

Usage of the GetValue() method of array class in C#

A program that demonstrates the GetValue() method of array class is given as follows:

Source Code: Program that demonstrates the GetValue() method of array class in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo
{
   class Example
   {
       static void Main(string[] args)
       {
           Array a = Array.CreateInstance(typeof(String), 3, 6);
           a.SetValue("Apple", 0, 0);  
           a.SetValue("Mango", 0, 1);  
           a.SetValue("Cherry", 0, 2);  
           a.SetValue("Grapes", 0, 3);  
           a.SetValue("Melon", 1, 4);  
           a.SetValue("Guava", 1, 5);  
           a.SetValue("Plum", 1, 2);  
           a.SetValue("Berry", 1, 3);
           int x = a.GetLength(0);  
           int y = a.GetLength(1);
           for (int i = 0; i < x; i++)  
             for (int j = 0; j < y; j++)
               Console.WriteLine( a.GetValue(i, j));  
       }
   }
}

The output of the above program is as follows:

Apple
Mango
Cherry
Grapes

Plum
Berry
Melon
Guava

Usage of the IndexOf(,) method of array class in C#

A program that demonstrates the IndexOf(,) method of array class is given as follows:

Source Code: Program that demonstrates the IndexOf(,) method of array class in C#

using System;
class Example
{
   static void Main()
   {
       int[] a = new int[5] {45, 78, 12, 99, 4};
       int index = Array.IndexOf(a, 12);
       Console.WriteLine("The index of 12 is {0}", index);
   }
}

The output of the above program is as follows:

The index of 12 is 2

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

austin faith

Avery good write-up. Please let me know what are the types of C# libraries used for AI development.

kariya arti

very satisfied!!

jean-Francois Michaud

Good tutorial. Small question: Say, there is : enum numbers { one, two, three} and a string field_enum ="one" how would I from the variable field_enum have a response with value numbers.one so that it can be treated as an enum and not as a string. making a list from the enum, and loop into the list. is not elegant... and may not work is forced value on field is forced ( one = 100).

Kshitiz

Hi Team Knowledge Hut, Thank you for such an informative post like this. I am completely new to this digital marketing field and do not have much idea about this, but your post has become a supportive pillar for me. After reading the blog I would expect to read more about the topic. I wish to get connected with you always to have updates on these sorts of ideas. Regards, Kshitiz

Ed

The reason abstraction can be used with this example is because, the triangle, circle. Square etc can be defined as a shape, for example.....shape c = new circle(5,0)...the abstract object c now points at the circle class. Thus hiding implementation

Suggested Tutorials

Swift Tutorial

Introduction to Swift Tutorial
Swift Tutorial

Introduction to Swift Tutorial

Read More

R Programming Tutorial

R Programming

Python Tutorial

Python Tutorial