Example of Generics Using C# in ASP.NET

Friday 27 March 2015
Generics provide a code template for creating type-safe code without referring to specific data types. Generics allow you to realize type safety at compile time. They allow you to create a data structure without committing to a specific data type. When the data structure is used, however, the compiler ensures that the types used with it are consistent for type safety. I want to discuss two benefits of generics, one is type safety and another is performance before explaining with an example.

Type Safety

Generics are mostly used for collections but the framework class library also has non-generic collection classes like ArrayListHashtableSortedListStackQueue. So, first of all, we see an example of a non-generic collection class. In other words, ArrayList where we add integer values to the array list and perform addition operation on the list values.
You need to create a class, ArrayListOperation, and define an Addition method as in the following code snippet.
using System.Collections;
namespace TypeSafety
{
    class ArrayListOperation
    {
        public static int Addition()
        {
            ArrayList list = new ArrayList();
            list.Add(5);
            list.Add(9);
 
            int result = 0;
            foreach (int value in list)
            {
                result += value;
            }
            return result;
        }
    }
}
When you run this code you get a return value from the method.
As you saw in the previous example there is an array list of integer values and get the result as expected but now add one more value to the ArrayList that the data type is float and perform the same Addition operation. Let's see the updated code in the following snippet.
using System.Collections;
namespace TypeSafety
{
    class ArrayListOperation
    {
        public static int Addition()
        {
            ArrayList list = new ArrayList();
            list.Add(5);
            list.Add(9);
            list.Add(5.10);
 
            int result = 0;
            foreach (int value in list)
            {
                result += value;
            }
            return result;
        }
    }
}
In the code above, all three values are easily added to the array list because the ArrayList class Add() method values are an object type, but when retrieving the values using each statement, each value will be assigned anint data type variable. However, this array list has a combination of both integer and float type values and float values won't cast to an int implicitly. That is why the code will give the exception "Specified cast is not valid." That means that an ArrayList is not type safe. This also means that an ArrayList can be assigned a value of any type.
Generics allow you to realize type safety at compile time. They allow you to create a data structure without committing to a specific data type. When the data structure is used, however, the compiler ensures that the types used with it are consistent for type safety. Generics provide type safety, but without any loss of performance or code bloat. The System.Collections.Generics namespace contains the generics collections. Now let's see an example with a generic collection List.
using System.Collections.Generic;
namespace TypeSafety
{
    class ListOperation
    {
        public static int Addition()
        {
            List<int> list = new List<int>();
            list.Add(5);
            list.Add(9);            
 
            int result = 0;
            foreach (int value in list)
            {
                result += value;
            }
            return result;
        }
    }
}</int></int>
In the code above we define a list int type. In other words, we can only add an integer value to the list and can't add a float value to it so when we retrieve values from the list using a foreach statement we only get an int value. When you run this code you will get a return value from the method. Now you can say that a generic collection is type safe.

Code Re-usability with Generics

Suppose, you required to sort the integer and floating type numbers, then let's see how to do in collections and generics.

How to do it using Collections

  1. //Overloaded sort methods
  2. private int[] Sort(int[] inputArray)
  3. {
  4. //Sort array
  5. //and return sorted array
  6. return inputArray;
  7. }
  8. private float[] Sort(float[] inputArray)
  9. {
  10. //Sort array
  11. //and return sorted array
  12. return inputArray;
  13. }

How to do it using Generics

  1. private T[] Sort(T[] inputArray)
  2. {
  3. //Sort array
  4. //and return sorted array
  5. return inputArray;
  6. }
Here, T is short for Type and can be replaced with the Type defined in the C# language at runtime. So once we have this method, we can call it with different data types as follows and can see the beauty of Generics. In this way Generics provide code re-usability.

No comments:

Post a Comment

Sharing

Get widget