C# Fundamentals - Generics


C# Fundamentals - Generics

Generic classes and methods provide us mainly three things :
1) Reusability
2) Type safety (certain value will not show undefined behavior)
3) Efficiency
It is similar to templates in C++ but it does not provide the same flexibility as that of templates.
Generics allow you to write a class or method that can work with any data type. When the compiler encounters a constructor for the class or a function call for the method, it generates code to match with the specified data type.
Let's look at a generic class called 'Node'.
public class Node<T>
{
   private Node<T> next;
   private T data;
   public Node(T t)
   {
       data = t;
   }
   public T GetData(){ return data; }
   public Node<T> GetNext(){ return next; }
   public void SetNext(Node<T> node){ next = node; }
}
We will now see what all of that means.
public class Node<T> 
Where T is a placeholder for any data type (int,float,string,user-defined...etc).
It's a good idea to always have the type parameter start with a 'T', it's good practise.
Good examples : TtypeA, Tvar, Ta... or just TšŸ˜Š.
Bad examples : type1, A, B...etc.
{
  private T data;
  public Node<T>(T t)
  {
     data = t;
  } 
}
Here we have a private data member called data of type 'T'.
And we have a parameterized constructor which takes in a variable of type t, then assign that to member 'data'.
public T GetData(){ return data; }
public Node<T> GetNext(){ return next; }
public void SetNext(Node<T> node){ next = node; }
Now we have a set of functions that do what you think they'll do.
GetData() - returns the member 'data'.
GetNext() - returns the member 'node', which is another Node of the same type.
SetNext() - sets the member 'node' with whatever Node variable of  the same type that was passed in as argument.
It is also useful for an interface to define constraints for the generic types it uses
public interface ICoolInterface<T> where T : IAnInterface<T>
this can also be used with classes deriving from interfaces.
public class Node<T> where T : IAnInterface<T>
Here is the entrie source code for an example program dealing with generics. For more information you can check out microsoft's intro to generics HERE.
For More C# Tutorials, go HERE