Using a generic method to display arrays of different types. - CSharp Custom Type

CSharp examples for Custom Type:Generics

Description

Using a generic method to display arrays of different types.

Demo Code

using System;/*  w  w  w  .  ja v a2s  .  co m*/
class MainClass
{
   public static void Main(string[] args)
   {
      int[] intArray = {1, 2, 3, 4, 5, 6};
      double[] doubleArray = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7};
      char[] charArray = {'H', 'E', 'L', 'L', 'O'};
      Console.Write("\nArray intArray contains: ");
      DisplayArray(intArray); // pass an int array argument
      Console.Write("\nArray doubleArray contains: ");
      DisplayArray(doubleArray); // pass a double array argument
      Console.Write("\nArray charArray contains: ");
      DisplayArray(charArray); // pass a char array argument
   }
   private static void DisplayArray<T>(T[] inputArray)
   {
      foreach (var element in inputArray)
      {
         Console.Write($"{element} ");
      }
   }
}

Result


Related Tutorials