Monday, September 7, 2020

Generics

  • Generic classes and methods combine reusability, type safety, and efficiency in a way that their non-generic counterparts cannot.
  • Generics introduce the concept of type parameters to .NET, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.
  • For example, by using a generic type parameter T, you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations, as shown here:
  •     public class GenericList<T>
        {
            public void Print(T key)
            {
                Console.WriteLine(key);
            }
    
        }
    	
       class TestGenericList
       {
        static void Main()
        {
           // Type of T is int
            var genericnumbers = new GenericList<int> ();
            genericnumbers.Print(5);
    
    	// Type of T is strings
            var genericStrings = new GenericList<strings>();
            genericStrings.Print("Janaki");
        }
    }
    	
    
  • The System.Collections.Generic namespace contains several generic-based collection classes.We can also create custom generic types and methods to provide your own generalized solutions and design patterns that are type-safe and efficient.
Constraints on Type Parameters

  • Constraints specify the capabilities and expectations of a type parameter.
  • Without any constraints, the type argument could be any type. The compiler can only assume the members of System.Object, which is the ultimate base class for any .NET type.
  • If client code uses a type that doesn't satisfy a constraint, the compiler issues an error. 
  • Constraints are specified by using the where contextual keyword. Below are some examples. 
    • where T : struct -  The type argument must be a non-nullable value type. 
    • where T : class -  T must be a non-nullable reference type.
    • where T: <any base class> :  T must be a non-nullable reference type derived from the specified base class.  
    •     public class CalculatePrice<T> where TProduct : Product
          {
              public decimal getPrice(TProduct product)
              {
                  return product.price;
              }
          }
          public class Product
          {
              public decimal price { get; set; }
          }
      	
      
    • where T : <interface name> - The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic.  
    • where T : new() - T is an object type that has a default constructor. 
    •     public class CalculatePrice<T> where TProduct : new()
          {
              public void DoSomeThing()
              {
                  var Onj = new T();
              }
           }
      

  • Type parameters that have no constraints can not use !=, > ,== operators because there's no guarantee that the concrete type argument will support these operators.
  •     public class Utilities<T> where T :IComparable
        {
            public int Max(int a, int b)
            {
                return a > b ? a : b;
            }
    
            public T Max (T a, T b)
            {
                //Can not compare by using operators a>b
                return a.CompareTo(b)>0 ? a : b;
            }
    
        }
    	
    
References :  docs.microsoft.com and udemy.com

No comments:

Post a Comment