In this article, I’m explaining the concept of generics in c#.

 

Generics allow you to write a class or method that can work with any data type. This results in an important performance boost and higher quality code, because you get to reuse data processing algorithms without duplicating type-specific code. Generics are similar to C++ template.

Benefits of Generics

·    It helps you to maximize code reuse, type safety, and performance.

·   You can create generic collection classes. The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. You may use these generic collection classes instead of the collection classes in the System.Collections namespace.

·     You can create your own generic interfaces, classes, methods, events and delegates.

·     You may create generic classes constrained to enable access to methods on particular data types.

·    You may get information on the types used in a generic data type at run-time by means of reflection.

Example 1
using System;
 
namespace GenericExample
{
    public class MyGenericArrayExample<T>
    {
        T[] arrayOfAnyType;  
        public MyGenericArrayExample(int sizeOfArray)
        {
            arrayOfAnyType = new T[sizeOfArray + 1]; // create a type array by given size
        }
        public T getArrayItem(int indexOfArray)
        {
            return arrayOfAnyType[indexOfArray];     //  get array value at index
        }
        public void setArrayItem(int indexOfArray, T value)
        {
            arrayOfAnyType[indexOfArray] = value;   // set array value at index
        }
        public void showArrayAllItem() 
        {
            foreach (var arrayItem in arrayOfAnyType)      // show all item of array
            {
                Console.Write(arrayItem+" ");
            }
        }
       
    }
    class TestGenericArray
    {
        static void Main(string[] args)
        {
            //declaring an int array
            MyGenericArrayExample<int> intArray = new MyGenericArrayExample<int>(5);
            //setting values
                intArray.setArrayItem(0,10);
                intArray.setArrayItem(1,20);
                intArray.setArrayItem(2,30);
                intArray.setArrayItem(3, 40);
                intArray.setArrayItem(4, 50);
            //getting the values at position
                Console.WriteLine("Array get item at index 1 : "+intArray.getArrayItem(1));
            // show all array item
            Console.WriteLine("\nShow all integer array items:\n");
            intArray.showArrayAllItem();
            Console.WriteLine();
            //declaring a string array
            MyGenericArrayExample<string> stringArray = new MyGenericArrayExample<string>(3);
            //setting values
                stringArray.setArrayItem(0, "One");
                stringArray.setArrayItem(1, "Two");
                stringArray.setArrayItem(2, "Three");
            //show all the array values
             Console.WriteLine("\nShow all string array items:\n");
            stringArray.showArrayAllItem();
            Console.WriteLine();
            Console.ReadKey();
        }
    }
}

 

Output:

Generics in C#

In this example we use generic class for an generic array.

Example 2
using System;
 
namespace GenricsMehodExample
{
   
    class Program
    {
        static void Main(string[] args)
        {
            int a, b;
            a = 15;
            b = 25;
            string str1, str2;
            str1 = "Ram";
            str2 = "Shyam";
 
            //display values before swaping:
            Console.WriteLine("Before swaping integer values  a={0}, b={1}\n", a, b);
            Console.WriteLine("Before swaping string values  str1={0}, str2={1}\n", str1, str2);
            //swaping performmed
            Swap<int>(ref a, ref b);
            Swap<string>(ref str1, ref str2);
 
            //display values after swap:
            Console.WriteLine("After swaping integer values  a={0}, b={1}\n", a, b);
            Console.WriteLine("After swaping string values  str1={0}, str2={1}\n", str1, str2);
            Console.ReadKey();
        }
        static void Swap<T>(ref T first, ref T second)
        {
            T temp;
            temp = first;
            first = second;
            second = temp;
        }
    }
}
Output

Generics in C#

In this example we use the generic method for swapping any type of data.

 

There are some important classes in generics in c#:

·         Dictionary

·         List

·         LinkedList

·         Stack

·         Queue

·         SortedDictionary

·         SortedList

 

Dictionary

 A Dictionary<TKey, TValue> class contains a collection of key and value. It denotes

like a dictionary in C#. Its Add method takes two parameters, one for the key and

one for the value.

There are some important methods in dictionary:

·    Add: Adds the specified key and value to the dictionary.

·    Remove: Removes the value with the specified key from the Dictionary<TKey, TValue>.

·   ContainsKey: Determines whether the Dictionary<TKey, TValue> contains the specified key.

·    ContainsValue: Determines whether the Dictionary<TKey, TValue> contains a specific value.

·    Clear: Removes all keys and values from the Dictionary<TKey, TValue>.

Example
using System;
using System.Collections.Generic;
namespace GenricDictionaryClass
{
 
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<intstring> dictObj = new Dictionary<intstring>(); //create an object of dictionary
            dictObj.Add(1, "A");  // add dictionary element
            dictObj.Add(5, "E");
            dictObj.Add(7, "G"); 
            dictObj.Add(4, "D");
            dictObj.Add(2, "B");
 
            foreach (KeyValuePair<int,string> alphabet in dictObj)      // show all dictionary element
            {
                Console.WriteLine("Key = {0}, value = {1}",alphabet.Key,alphabet.Value);
            }
            Console.WriteLine("\nNumber of dictionary element :" + dictObj.Count);     //count dictionary item
            Console.WriteLine("Contains key=1 in dictionary :" + dictObj.ContainsKey(1));
            Console.WriteLine("Contains value=B in dictionary :" + dictObj.ContainsValue("B"));
            dictObj.Remove(2); //remove item at key
            Console.WriteLine("\nAfter remove one item Number of dictionary element :" + dictObj.Count);
            foreach (int i in dictObj.Keys)     // show all dictionary element
            {
                Console.WriteLine("Key = {0}, value = {1}", i, dictObj[i]);
            }
            dictObj.Clear(); // remove all dictionary element
            Console.WriteLine("\nAfter remove all element from dictionary Number of dictionary element :" + dictObj.Count);
            Console.ReadKey();
         
        }
    }
}
Output:

Generics in C#

 

List

The List class in .NET represents a strongly typed list of objects that can be accessed

by index. The List<T> class is contained with the System.Collections.Generic

namespace. The List provides the built-in methods and properties including add,

remove, search, and sort.

Example
using System;
using System.Collections.Generic;
 
namespace ListExample
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> title = new List<string>();  // create a list object
            Console.WriteLine("\nCapacity: {0}", title.Capacity);
            title.Add("Array List");        // add list items
            title.Add("List");
            title.Add("HashTable");
            title.Add("Stack");
            title.Add("Queue");
            Console.WriteLine();
            foreach (string author in title)
            {
                Console.WriteLine(author);          // print list data
            }
            Console.WriteLine("Number of Titles in List: {0}", title.Count);
            Console.WriteLine("\nContains(\"Title\"): {0}",
                title.Contains("Abstract class")); //contain method return true or false
            Console.WriteLine("\nInsert(2, \"Static class\")");
            title.Insert(2, "Non-static class");    // insert new item at position 2
            Console.WriteLine();
            foreach (string author in title)
            {
                Console.WriteLine(author);
            }
            Console.WriteLine("\ntitle[3]: {0}", title[3]);
            Console.WriteLine("\nRemove(\"Static class\")");
            title.Remove("Array List");             // remove item
            Console.WriteLine();
            foreach (string author in title)
            {
                Console.WriteLine(author);
            }
            Console.WriteLine();
            title.Sort();           // sort the list
            Console.WriteLine("Sorted List");
            foreach (string author in title)
            {
                Console.WriteLine(author);
            }
            title.TrimExcess();
            Console.WriteLine("\nTrimExcess()");
            Console.WriteLine("Capacity: {0}", title.Capacity); //list capacity
            Console.WriteLine("Count: {0}", title.Count);       // list element count
            title.Clear();      // list clear
            Console.WriteLine("\nClear()");
            Console.WriteLine("Capacity: {0}", title.Capacity);  // after clearing the list
            Console.WriteLine("Count: {0}", title.Count);       // after clearing the list item 0
            Console.ReadKey();
        }
    }
}

 

 

 Output

Generics in C#

In this example, we use the list functions.

LinkedList

A linked list is a simple chain of nodes where a node points to next node and so on till the next node doesn't points to anything. LinkedList allows fast inserts and removes. It implements a linked list. Each object is separately allocated.

Example
using System;
using System.Collections.Generic;
 
 
namespace GenricLinkedListExample
{
    class Program
    {
        static void Main(string[] args)
        {
            LinkedList<string> linkedObj = new LinkedList<string>(); // create an object of LinkedList
            linkedObj.AddLast("One"); // add linked list items
            linkedObj.AddLast("Two");
            linkedObj.AddLast("Three");
            linkedObj.AddFirst("Zero");
            foreach (string str in linkedObj)  // show all records of linked list
            {
                Console.WriteLine(str);
            }
            Console.WriteLine("Linked list item: " + linkedObj.Count); //
            LinkedListNode<string> node=linkedObj.Find("One");  
            linkedObj.AddBefore(node,"Four");
            Console.WriteLine("\nAdd Before");
            foreach (string str in linkedObj)  // show all records of linked list
            {
                Console.WriteLine(str);
            }
            LinkedListNode<string> node1 = linkedObj.Find("Two");
            linkedObj.AddAfter(node1, "Five");
            Console.WriteLine("\nAdd After");
            foreach (string str in linkedObj) // show all records of linked list
            {
                Console.WriteLine(str);
            }
            linkedObj.RemoveFirst();
            linkedObj.RemoveLast();
            linkedObj.Remove("Three");
           Console.WriteLine("\nShow after remove");
            foreach (string str in linkedObj)  // show all records of linked list
            {
                Console.WriteLine(str);
            }
            Console.WriteLine("Linked list item: " + linkedObj.Count);
            Console.ReadKey();
        }
    }
}
Output:

Generics in C#

Stack

Stack is the LIFO (Last-In-first-out) collection. Stack contains the push-pop

method.In stack, we can insert (push) and retrieve (pop) from the stack list. Stack

class is under the System.Collections.Generic namespace.

Example
using System;
using System.Collections.Generic;
namespace GenericStackExample
{
  
        class Program
        {
            static void Main(string[] args)
            {
                Stack<string> stackObj = new Stack<string>(); // create an object of Stack class
                // Stack stackObj=new Stack(); // or you create this type stack class object
                stackObj.Push("Sunday");     // add or push the item into Stack
                stackObj.Push("Monday");
                stackObj.Push("Tuesday");
                stackObj.Push("Thursday");
                stackObj.Push("Friday");
                stackObj.Push("Saturday");
                foreach (string str in stackObj)
                {
                    Console.WriteLine(str);    // fetch or pop the item from Stack
                }
                Console.WriteLine("Stack item count:" + stackObj.Count);
                Console.WriteLine("Stack last item:" + stackObj.Pop()); //  last element of stack removed
                Console.WriteLine("Stack item count:" + stackObj.Count); // count stack item
                Console.WriteLine("Stack item count:" + stackObj.Contains("Saturday")); // check stack contains this item
                stackObj.Clear();       // remove all stack items
                Console.WriteLine("Stack item count:" + stackObj.Count); // count stack item
                Console.ReadKey();
            }
        }
 
 
}
Output

Generics in C#

Queue

The Queue works like FIFO system, a first-in, first-out collection of Objects. Objects

stored in a Queue are inserted at one end and removed from the other. In queue,

we can add Enqueue (add) and dequeue (remove) from the queue.

Example
using System;
using System.Collections.Generic;
 
 
namespace GenricQueueExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Queue<string> queueObj = new Queue<string>();
            queueObj.Enqueue("Sunday");
            queueObj.Enqueue("Monday");
            queueObj.Enqueue("Tuesday");
            queueObj.Enqueue("Wednesday");
            queueObj.Enqueue("Thursday");
            queueObj.Enqueue("Saturday");
            foreach (string str in queueObj)
            {
                Console.WriteLine(str);     // print the queue data
            }
            queueObj.Dequeue();         // remove first element from queue
            queueObj.Dequeue();         // remove second element from queue
            Console.WriteLine("\nAfter dequeue");
            foreach (string str in queueObj)
            {
                Console.WriteLine(str);
            }
            Console.WriteLine("\nQueue element count :" + queueObj.Count);   // count queue element
            Console.WriteLine("Queue contains Wednesday :" + queueObj.Contains("Wednesday")); // contains queue
            queueObj.Clear(); // remove all items from queue
            Console.WriteLine("Queue element count :" + queueObj.Count); // count queue element
            Console.ReadKey(); // hold the console screen
 
        }
    }
}
Output:

Generics in C#

 

SortedDictionary

A SortedDictionary<Tkey,Tvalue> represents a collection of key/value pairs that are

sorted on the key. The hierarchy of this class is

System.Collections.Generic.SortedDictionary<TKey,TValue>, where Tkey is the type

of the keys in the dictionary and Tvalue is the type of the values in the dictionary.

 

SortedList

The SortedList class represents a collection of key-and-value pairs that are sorted by

the keys and are accessible by key and by index. SortedList stores elements in an

ordered way. Main method of sorted list are Add(), Remove(), IndexOfKey(),

IndexOfValue(), GetKeyList(), GetKeyValue() etc. and to object key and values.

Example
using System;
using System.Collections.Generic;
 
namespace GenricSortedListExample
{
    class Program
    {
        static void Main(string[] args)
        {
            //make object of Sorted List 
            SortedList<int,string> countryList = new SortedList<int,string>();
            //Add country with each
            countryList.Add(1, "India");
            countryList.Add(2, "England");
            countryList.Add(3, "France");
            countryList.Add(4, "Japan");
            //show all records
            foreach (int i in countryList.Keys)
            {
                Console.WriteLine(i+"   "+countryList[i]);
            }
            Console.WriteLine("Number of items :" + countryList.Count); // count the element
            countryList.Remove(4); // remove the element at index
            Console.WriteLine("After remove number of items :" + countryList.Count);
            countryList.Add(4, "America");
            Console.WriteLine("Index of Key :"+countryList.IndexOfKey(4)); // find index of key
            Console.WriteLine("Index of Value :" + countryList.IndexOfValue("India"));  // find index of value
            countryList.Clear(); // remove all element
            Console.WriteLine("Number of items :" + countryList.Count);
           
            Console.ReadKey();
        }
    }
}
Output

Generics in C#

  Modified On Nov-30-2017 12:39:13 AM

Leave Comment