Monday 17 July 2017

Generics

Summary

  • Generics feature added in C# 2.0
  • A generic type uses a Type parameter instead of hard-coding all the types.

Why Generics?

  1. Elimination of casts.
  2. Enabling programmers to implement generic algorithms.
  3. Stronger type checks at compile time (Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.)

Generic method implementation.

   1:  using System;
   2:  using System.Collections.Generic;
   3:   
   4:  namespace GenericDisplayArray
   5:  {
   6:      class Program
   7:      {
   8:          static void Main(string[] args)
   9:          {
  10:              int[] intArray = { 1, 2, 3 };
  11:              double[] doubleArray = { 1.1, 2.2, 3.3 };
  12:              char[] charArray = { 'A', 'B', 'C' };
  13:             
  14:              Console.WriteLine("Display Integer array using Generic Method:");
  15:              DisplayArray<int>(intArray); // How to call generic method.
  16:   
  17:              Console.WriteLine("\nDisplay Double array using Generic Method: ");
  18:              DisplayArray(doubleArray); // How to call generic method.
  19:   
  20:              Console.WriteLine("\nDisplay Char array using Generic Method: ");
  21:              DisplayArray<char>(charArray); // How to call generic method.
  22:              Console.ReadKey();
  23:          }
  24:   
  25:          /// <summary>
  26:          /// Display any type of array.
  27:          /// </summary>
  28:          /// <typeparam name="T">Pass the datatype</typeparam>
  29:          /// <param name="inputArray">Pass the all type of array</param>
  30:          private static void DisplayArray<T>(T[] inputArray)
  31:          {
  32:              foreach (T element in inputArray)
  33:              {
  34:                  Console.Write("{0} ", element);
  35:              }
  36:          }
  37:      }
  38:  }

No comments:

Post a Comment