Generics and generic types in C#

Posted by in C# category on for Intermediate level | Points: 250 | Views : 3417 red flag
Rating: 5 out of 5  
 1 vote(s)

C# is an Object-oriented programming language. C# comes with simplicity, expressiveness and great performance to meet the programmer productivity.
Read Enums debugging and Nested types in C# before this article.


In the previous chapters, we have discussed about enums, debugger and nested types in C#. Let.s study a new topic called C# generics in this chapter.


The main objective of this chapter is to study C# generics and System.Collections.Generic namespace in C# programming.


Generics is introduced in C# 2.0 which is the mechanism of writing codes which are reusable. Another C# mechanism to achieve this is by using inheritances.
Difference between these two is that, inheritance expresses re-usability with a base type and generics uses a 'template' which comes with 'placeholder' types.
  • By using generics, we can reduce casting and boxing and type safety is also increased.
  • Maximizes the code re-usability and improves the performance.
  • Generics are commonly used in creating collection classes.
  • .NET Framework class library contains several generic collection classes. They reside in System.Collections.Generic namespace.
  • We can also create our own generics of classes, interfaces, methods, delegates and events.
Generic types
Generic types declare the type parameters. Let's have an example of using generic types in C#,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Example
    class Program
        public class MyClass<T>      // Generic type
            int pos;
            T[] demo = new T[10];
            public void Insert(T obj)
                demo[pos++] = obj;
            public T Update()
                return demo[--pos];

        static void Main()
            MyClass<int> my = new MyClass<int>();

            int i = my.Update();
            Console.WriteLine(i);    // prints 8

            int j = my.Update();
            Console.WriteLine(j);    // prints 6

            int k = my.Update();
            Console.WriteLine(k);    // prints 2
In the above code, we have a generic type MyClass<T>. And we are creating instances for that type in the Main() method.
MyClass<int> fills in the type parameter T with type argument int, implicitly creating a type on the fly (occurs at runtime).
In many cases, instead of creating own type, we use List<T> which is the class provided by the .NET Framework library. It represents a strongly typed list of objects which are accessed by index.
List<T> class provides methods to sort, search and manipulate lists.

The above code prints the following lines in your console,

Using generics is an awesome feature of C#.


System.Collections.Generic is the C# namespace introduced from C# 2.0 which comes with several generic based collection classes. It is recommended to use these classes instead of older ones (non-generic classes) such as ArrayList.

This namespace contains classes and interfaces that defines generic collections, which helps user to create strongly typed collections with better performance and type safety.

There are so many classes in this namespace. Some of them are,
  1. Dictionary<TKey, TValue>: Represents the collection of keys and values (key-value pairs).
  2. Dictionary<TKey, TValue>.KeyCollection: Represents the collection of keys that are present in Dictionary<TKey, TValue>.
  3. Dictionary<TKey, TValue>.ValueCollection: Represents the collection of values that are present in Dictionary<TKey, TValue>.
  4. Comparer<T>: Used in the implementations of IComparer<T> interface (generic) to provide a base class for that.
  5. HashSet<T>: Represents a set of values.
  6. EqualityComparer<T>: Used in the implementations of IEqualityComparer<T> interface (generic) to provide base class for that.
  7. List<T>: Provides methods to sort, search and manipulate lists. It represents a strongly typed list of objects which are accessed by index.
  8. Queue<T>: Represents the collection of objects in FIFO (first-in, first-out) manner.
  9. Stack<T>: Represents variable size collection of instances of same type in LIFO (last-in, first-out) manner.
There are some other classes such as LinkedList<T>, LinkedListNode<T>, SortedList<TKey, TValue>, SortedSet<T>, SynchronizedCollection<T> etc.

System.Collections.Generic namespace contain some interfaces. They are,
  1. IComparer<T>: It defines a method to compare two objects for the types.
  2. ICollection<T>: This is the important interface which defines the methods to manipulate the generic collections.
  3. IEnumerable<T>: It exposes the enumerator, which supports iteration and performs simple iterations over a generic collection.
  4. IEnumerator<T>: Supports iteration and allows simple iteration over a generic specified type collection.
  5. ISet<T>: Gives a base interface for the abstraction of sets.
  6. IList<T>: It represents strongly typed objects which are accessed by index.
  7. IDictionary<TKey, TValue>: It represents the collection of key-value pairs.
There are some other generic interfaces such as IEqualityComparer<T>, IReadOnlyCollection<T>, IReadOnlyList<T> etc.

There are some generic structures in this namespace. They are,
  1. List<T>.Enumerator: It enumerates the elements of the type List<T>.
  2. Dictionary<TKey, TValue>.Enumerator: It enumerates the elements of type Dictionary<TKey, TValue>.
  3. Queue<T>.Enumerator: It enumerates the elements of the type Queue<T>.
  4. HashSet<T>.Enumerator: It enumerates the elements of the type HashSet<T>.
  5. Stack<T>.Enumerator: It enumerates the elements of the type Stack<T>.
  6. LinkedList<T>.Enumerator: It enumerates the elements of the type LinkedList<T>.
  7. SortedSet<T>.Enumerator: It enumerates the elements of the type SortedSet<T>.
  8. KeyValuePair<TKey, TValue>: It defines the key-value pairs that can be set or retrieved.
There are some other generic structures such as SortedDictionary<TKey, TValue>.Enumerator etc.


In this article, we have studied about C# generics and System.Collections.Generic namespace in C#. Hope you understand.

Thanks for reading,

Page copy protected against web site content infringement by Copyscape

About the Author

Full Name: Krishna Vamshi Goud
Member Level: Gold
Member Status: Member,MVP
Member Since: 2/12/2014 2:34:09 AM
Country: India
Thanks & Regards, Krishna

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)