Wednesday, May 26, 2021

C# Generics

What is Generics?
Generics is C# language construct that let you write code that works with any type while keeping full type safety. Instead of writing separate classes or methods for int, string, and every other type you need, you write one version with the help of one or more type parameters (such as T, or TKey and TValue) and specify the actual types when you use it. The compiler checks types at compile time, so you don't need runtime casts or risk InvalidCastException.

👉Generics become useful when the logic stays same but type changes. (Read here)

Generics are classes, structures, interfaces, methods, delegates and events that have type parameters for one or more of the types that they store or use. 
In the following class, T is Type parameter. 
class Person<T> // T is called Type parameter. It can get any type e.g. int, string etc.
{
    public T Name { get; set; }
    public T City { get; set; }
    public string GetInfo()
    {
        return $"Name: {Name}, City: {City}";
    }
}
Points to Note
  • The symbol T used just after the generic class identifier is called Type parameter.
  • Any other symbol e.g. K, R, S, RType etc. can be used for Type parameter.
  • More than one Type parameter can be in a generic.
  • Type parameter can get any type argument e.g. int, string, List<int> etc.
  • Type Argument can be built-in or custom type.
  • After passing Type Argument(s), generic becomes closed generic type. Before that, it is known as Open generic type.
  • In given example, Person<T> is open generic class.
  • An instance of closed generic class can be created.
Now, to convert open generic class Person<T> into closed generic class, we can pass type argument string, so we get Person<string> which is a closed generic class. Now, we can create objects from this closed generic class:
class Program
{
    static void Main(string[] args)
    {
        Person<string> person1 = new Person<string>();
        person1.Name = "John";
        person1.City = "New York";
        Console.WriteLine(person1.GetInfo());
    }
}
Generics improves code usability, type safety and performance. System.Collections.Generic namespace contains a number of built-in generic collections.

Important Terms, Related to Generic

  1. Type Parameter
  2. Generic Type
    • Open generic type
    • Closed generic type
  3. Generic Type Definition
  4. Constructed Generic Type
  5. Generic Type Argument
  6. Generic Constraints
  7. Generic Method

1. Type Parameter
  • Generic type parameters, or type parameters, are the placeholders in a generic type definition or method definition.
  • We can use any letter or word to denote type parameter such as T, TResult etc. 
  • Generics use type parameter to represent a placeholder for type.
  • The type of type parameter is determined when generic type is initialized.
  • Example. In Person<T> class, T is type parameter. 
  • Person<T> is initialized when T is replaced by type argument e.g. string. So, Person<string> can be initialized: Person<string> person1 = new Person<string>();
2. Generic Type: The general term generic type includes both constructed types and generic type definitions. Generic type can be generic class, generic interface, generic method, generic delegate and generic event. Generic type can be classified as:
  1. Open generic type
  2. Closed generic type
3. Generic Type Definition: A generic type definition is a class, structure, or interface declaration that functions as a template, with placeholders for the types that it can contain or use.
Example:
class Person<T> // T is called Type parameter
{
    public T Name { get; set; }
    public T City { get; set; }
    public string GetInfo()
    {
        return $"Name: {Name}, City: {City}";
    }
}
Because a generic type definition is only a template, you cannot create instances of a class, structure, or interface that is a generic type definition.  The generic type definition must have type parameter(s) written inside angular bracket e.g. <T> after the name of generic class, generic property, generic interface or generic method.

4. Constructed Generic Type
  • A constructed generic type, or constructed type, is the result of specifying types for the generic type parameters of a generic type definition. 
  • For example, List<string> is a constructed generic type but List<T> is not.

5. Generic Type Argument: A generic type argument is any type e.g. string, double etc. that is substituted for a generic type parameter.

6. Generic Constraints: It inform the compiler about the capabilities a type argument must have. Without any constraints, the type argument could be any type. we use where keyword for defining constraint.
Example. The where keyword defines the constraint on T i.e. T must be value type e.g. int, double, float. If you use string then compiler will throw error.
class Box<T> where T : struct // T must be value type 
{
    public T height { get; set; }
    public T width { get; set; }
    public string GetDimension()
    {
        return $"Height: {height}, Height: {width}";
    }
}
7. Generic Method Definition
  • A generic method definition is a method with type parameter(s).
  • Type parameters can appear as the return type or/and as the types of the formal parameters.
  • A generic method can be non generic class/struct also.
Example
T MyGenericMethod(T arg)
{
    T temp = arg;
    //...
    return temp;
}
Example. Generic methods can be in generic or nongeneric types.
class NonGenericClass
{
    public void Print<T>(T value)
    {
        Console.WriteLine(value);
    }
}
class GenericClass<T>
{
    T M(T arg)
    {
        T temp = arg;
        //...
        return temp;
    }
}

No comments:

Post a Comment

Hot Topics