SlideShare una empresa de Scribd logo
1 de 39
Rohit Vipin Mathews
Topics
Why Generics are required?
Generic types and functions ,
Type parameters and Constraints
Difference between templates in C++ and Generics in C#
Generic Delegates and event handling
Generic Interfaces
Introduction
Generics are the most powerful feature of C# 2.0. Generics allow you to
define type-safe data structures, without committing to actual data types.
This results in a significant performance boost and higher quality code,
because you get to reuse data processing algorithms without duplicating
type-specific code.
In concept, generics are similar to C++ templates, but are drastically
different in implementation and capabilities.
Why Generics are required?
Consider an everyday data structure such as a stack, providing the classic
Push() and Pop() methods.
 When developing a general-purpose stack, you would like to use it to store
instances of various types.
Under C# 1.1, you have to use an Object-based stack, meaning that the
internal data type used in the stack is an amorphous Object, and the stack
methods interact with Objects.
An Object-based stack
public class Stack
{
         int m_Size;
         int m_StackPointer = 0;
         object[] m_Items;
         public Stack():this(100)
         {}
         public Stack(int size)
         {
                     m_Size = size;
                     m_Items = new object[m_Size];
         }
public void Push(object item)
{
             if(m_StackPointer >= m_Size)
                         throw new StackOverflowException();
             m_Items[m_StackPointer] = item;
             m_StackPointer++;
}


public object Pop()
{
             m_StackPointer--;
             if(m_StackPointer >= 0)
                         return m_Items[m_StackPointer];
             else
             {
                         m_StackPointer = 0;
                         throw new InvalidOperationException("empty stack");
             }
}
}
Problems with Object-based solutions
Performance – When using value types, you have to box them in order to
push and store them, and unbox the value types when popping them off the
stack. Boxing and unboxing incurs a significant performance penalty it also
increases the pressure on the managed heap, resulting in more garbage
collections
Type safety – the compiler lets you cast anything to and from Object, you
lose compile-time type safety. Eg: the following code compiles fine, but
raises an invalid cast exception at run time:
         Stack stack = new Stack();
         stack.Push(1);
         string number = (string)stack.Pop();
Generics
Generics allow you to define type-safe classes without compromising type safety,
performance, or productivity.
         public class Stack<T>
         {...}


         Stack<int> stack = new Stack<int>();
Generic stack
public class Stack<T>
{
         int m_Size;
         int m_StackPointer = 0;
         T[] m_Items;
         public Stack():this(100){ }
         public Stack(int size)
         {
                   m_Size = size;
                   m_Items = new T[m_Size];
         }
public void Push(T item)
{
           if(m_StackPointer >= m_Size)
                      throw new StackOverflowException();
           m_Items[m_StackPointer] = item;
           m_StackPointer++;
}
public T Pop()
{
           m_StackPointer--;
           if(m_StackPointer >= 0)
                      return m_Items[m_StackPointer];
           else
           {
           m_StackPointer = 0;
           throw new InvalidOperationException("Cannot pop an empty stack");
}
}
}
default() operator
public T Pop()
{
         m_StackPointer--;
         if(m_StackPointer >= 0)
                  return m_Items[m_StackPointer];
         else
         {
                  m_StackPointer = 0;
                  return default(T);
         }
}
Multiple Generic Types
class Node<K,T>

{

             public K Key;

             public T Item;

             public Node<K,T> NextNode;

             public Node()

             {

                              Key = default(K);

                              Item = default(T);

                              NextNode = null;

             }

             public Node(K key,T item,Node<K,T> nextNode)

             {

                              Key = key;

                              Item = item;

                              NextNode = nextNode;

             }

}
public class LinkedList<K,T>
{
          Node<K,T> m_Head;
          public LinkedList()
          {
                    m_Head = new Node<K,T>();
          }
          public void AddHead(K key,T item)
          {
                  Node<K,T> newNode = new
          Node<K,T>(key,item,m_Head.NextNode);
                    m_Head.NextNode = newNode;
          }
}


LinkedList<int,string> list = new LinkedList<int,string>();
list.AddHead(123,"AAA");
Generic type aliasing
using List = LinkedList<int,string>;


class ListClient
{
          static void Main(string[] args)
          {
                   List list = new List();
                   list.AddHead(123,"AAA");
          }
}
Generic Constraints
The compiler compiles the generic code into IL independent of any type
arguments that the clients will use. As a result, the generic code could try to
use methods, properties, or members of the generic type parameters that
are incompatible with the specific type arguments the client uses. This is
unacceptable because it amounts to lack of type safety.
There are three types of constraints.
A derivation constraint indicates to the compiler that the generic type parameter
derives from a base type such an interface or a particular base class.
A default constructor constraint indicates to the compiler that the generic type
parameter exposes a default public constructor (a public constructor with no
parameters).
A reference/value type constraint constrains the generic type parameter to be a
reference or a value type.
Derivation Constraints
The “where” keyword on the generic type parameter followed by a
derivation colon to indicate to the compiler that the generic type parameter
implements a particular interface.
public class LinkedList<K,T> where K : IComparable
{
            T Find(K key)
            {
            Node<K,T> current = m_Head;
            while(current.NextNode != null)
            {
                         if(current.Key.CompareTo(key) == 0)
                                     break;
                         else
                                     current = current.NextNode;
            }
            return current.Item;
}
...
}
Multiple interfaces on the same generic type parameter, separated by a comma. For
example:
         public class LinkedList<K,T>
         where K : IComparable<K>,Iconvertible
         {...}


Constraints for every generic type parameter your class uses, for example:
         public class LinkedList<K,T>
         where K : IComparable<K>
         where T : ICloneable
base class constraint
          public class MyBaseClass
          {...}
          public class LinkedList<K,T> where K : MyBaseClass
          {...}


constrain both a base class and one or more interfaces
          public class LinkedList<K,T>
          where K : MyBaseClass, IComparable<K>
          {...}
Constructor Constraint
Suppose you want to instantiate a new generic object inside a generic class.
The problem is the C# compiler does not know whether the type argument
the client will use has a matching constructor, and it will refuse to compile
the instantiation line.
Its overcome using the “new()” constraint.
class Node<K,T> where T : new()
{
         public K Key;
         public T Item;
         public Node<K,T> NextNode;
         public Node()
         {
                   Key = default(K);
                   Item = new T();
                   NextNode = null;
         }
}
Reference/Value Type Constraint
Value Type Constraint
         public class MyClass<T> where T : struct
         {...}
Reference Type Constraint
         public class MyClass<T> where T : class
         {...}
Generic Methods
A method can define generic type parameters, specific to its execution scope.
Generic Class:
            public class MyClass<T>
            {
                         public void MyMethod<X>(X x)
                         {...}
            }


Non Generic Class:
            public class MyClass
            {
                         public void MyMethod<T>(T t)
                         {...}
            }
Generic Delegates
A delegate defined in a class can take advantage of the generic type parameter of that class. For
example:
            public class MyClass<T>
            {
                        public delegate void GenericDelegate(T t);
            public void SomeMethod(T t)
                        {...}
            }


MyClass<int> obj = new MyClass<int>(); MyClass<int>.GenericDelegate del;
del = obj.SomeMethod;
Generic Event Handiling
namespace Generic_Delegates_and_Events

{

    public delegate void GenericEventHandler<S,A>(S sender,A args); //generic delegate



    public class MyPublisher

    {

        public event GenericEventHandler<MyPublisher,EventArgs> MyEvent;

        public void FireEvent()

        {

            MyEvent(this,EventArgs.Empty);

        }

    }



public class MySubscriber<A> //Optional: can be a specific type

    {
public class MySubscriber2<A> //Optional: can be a specific type

    {

        public void SomeMethod2(MyPublisher sender, A args)

        {

            Console.WriteLine("MySubscriber2::SomeMethod2()");

        }

    }



    class Program

    {

        static void Main(string[] args)

        {

            MyPublisher publisher = new MyPublisher();

            MySubscriber<EventArgs> subscriber = new MySubscriber<EventArgs>();

            publisher.MyEvent += subscriber.SomeMethod;

            MySubscriber2<EventArgs> subscriber2 = new MySubscriber2<EventArgs>();

            publisher.MyEvent += subscriber2.SomeMethod2;

            publisher.FireEvent();

        }

    }

}
Differences Between C++ Templates
and C# Generics
C# generics do not provide the same amount of flexibility as C++ templates.
C# does not allow non-type template parameters, such as template C<int i> {}.
C# does not support explicit specialization; that is, a custom implementation of a template for a specific
type.
C# does not support partial specialization: a custom implementation for a subset of the type arguments.
C# does not allow the type parameter to be used as the base class for the generic type.
C# does not allow type parameters to have default types.
In C#, a generic type parameter cannot itself be a generic, although constructed types can be used as
generics. C++ does allow template parameters.
C# Generics is more type safe than C++ templates.
C++ templates use a compile-time model. C# generics are not just a feature of the
compiler, but also a feature of the runtime.
Code Bloating is reduced in C# compared to C++.
Generics have full run time support. Which is not available to templates.
Generic Interfaces
The System.Collections.Generic namespace contains interfaces and classes that
define generic collections, which allow users to create strongly typed collections
that provide better type safety and performance than non-generic strongly typed
collections.
ICollection<T>
• Add(), Clear(), Contains(), CopyTo(), Remove(),Count, IsReadOnly
• The interface ICollection<T> is implemented by collection classes. Methods of this interface can be used to add and remove elements from
  the collection. The generic interface ICollection<T> inherits from the non-generic interface IEnumerable. With this it is possible to pass
  objects implementing ICollection<T> to methods that require IEnumerable objects as parameters.

IList<T>
• Insert(), RemoveAt(), IndexOf(),Item
• The interface IList<T> allows you to access a collection using an indexer. It is also possible to insert or remove elements at any position of the
  collection. Similar to ICollection<T>, the interface IList<T> inherits from IEnumerable.

IEnumerable<T>
• GetEnumerator()
• The interface IEnumerable<T> is required if a foreach statement is used with the collection. This interface defines the method
  GetEnumerator() that returns an enumerator implementing IEnumerator<T>.The generic interface IEnumerable<T> inherits from the non-
  generic interface IEnumerable.
IEnumerator<T>
• Current
• The foreach statement uses an enumerator implementing IEnumerator<T> for accessing all
  elements in a collection. The interface IEnumerator<T> inherits from the non-generic interfaces
  IEnumerator and IDisposable. The interface IEnumerator defines the methods MoveNext() and
  Reset(), IEnumerator<T> defines the type-safe version of the property Current.

IDictionary<TKey, TValue>
• Add(), ContainsKey(), Remove(), TryGetValue(),Item, Keys, Values
• The interface IDictionary<K, V> is implemented by collections whose elements have a key and a
  value.

IComparer<T>
• Compare()
• The interface IComparer<T> is used to sort elements inside a collection with the Compare()
  method.

IEqualityComparer<T>
• Equals(), GetHashCode()
• IEqualityComparer<T> is the second interface to compare objects. With this interface the objects
  can be compared for equality. The method GetHashCode() should return a unique value for every
  object. The method Equals() returns true if the objects are equal, false otherwise.
The ICollection<T> interface is the base interface for classes in the
System.Collections.Generic namespace.


The ICollection<T> interface extends IEnumerable<T>.


IDictionary<TKey, TValue> and IList<T> are more specialized interfaces that
extend ICollection<T>.


A IDictionary<TKey, TValue> implementation is a collection of key/value pairs, like
the Dictionary<TKey, TValue> class.


A IList<T> implementation is a collection of values, and its members can be
accessed by index, like the List<T> class.
IEnumerable is an interface that defines one method GetEnumerator which
returns an IEnumerator interface, this in turn allows readonly access to a
collection. A collection that implements IEnumerable can be used with a foreach
statement.
public interface ICustomInterface<T>
 {
     void ShowMethod();
     void SomeMethod(T t);


 }
 class CustomClass<U> : ICustomInterface<U>
 {
     U u;
     public CustomClass(U temp)
     {
         u = temp;
     }


     public void ShowMethod()
     {
         Console.WriteLine("Value: " + u);
     }
public void SomeMethod(U t)
     {
         Console.WriteLine(t + " " + u);
     }
 }
 class Program
 {
     static void Main(string[] args)
     {


         CustomClass<int> MyClass = new CustomClass<int>(10);
         MyClass.ShowMethod();
         CustomClass<int> MyClass2 = new CustomClass<int>(10);
         MyClass2.SomeMethod(20);
     }
 }
C# Generics

Más contenido relacionado

La actualidad más candente

Functions in python
Functions in pythonFunctions in python
Functions in pythoncolorsof
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methodsShubham Dwivedi
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Conceptsthinkphp
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator OverloadingNilesh Dalvi
 
Recursion in C++
Recursion in C++Recursion in C++
Recursion in C++Maliha Mehr
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdmHarshal Misalkar
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHPVibrant Technologies & Computers
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts Bharat Kalia
 
linked list (c#)
 linked list (c#) linked list (c#)
linked list (c#)swajahatr
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Michelle Anne Meralpis
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arraysHassan Dar
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAsivasundari6
 

La actualidad más candente (20)

Functions in python
Functions in pythonFunctions in python
Functions in python
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
Inheritance in Java
Inheritance in JavaInheritance in Java
Inheritance in Java
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
Control statements
Control statementsControl statements
Control statements
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Recursion in C++
Recursion in C++Recursion in C++
Recursion in C++
 
Nullable type in C#
Nullable type in C#Nullable type in C#
Nullable type in C#
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdm
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
Php and MySQL
Php and MySQLPhp and MySQL
Php and MySQL
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
linked list (c#)
 linked list (c#) linked list (c#)
linked list (c#)
 
Javascript
JavascriptJavascript
Javascript
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVA
 

Similar a C# Generics

Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Andrew Petryk
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3mohamedsamyali
 
3 functions and class
3   functions and class3   functions and class
3 functions and classtrixiacruz
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6sotlsoc
 
麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)ProCharm
 
Templates presentation
Templates presentationTemplates presentation
Templates presentationmalaybpramanik
 
Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++Jay Patel
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined MethodPRN USM
 
C# Starter L04-Collections
C# Starter L04-CollectionsC# Starter L04-Collections
C# Starter L04-CollectionsMohammad Shaker
 
2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templates2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templateskinan keshkeh
 
Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++Hoang Nguyen
 
Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Palak Sanghani
 
Chapter 1 Presentation
Chapter 1 PresentationChapter 1 Presentation
Chapter 1 Presentationguest0d6229
 

Similar a C# Generics (20)

Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++
 
Getters_And_Setters.pptx
Getters_And_Setters.pptxGetters_And_Setters.pptx
Getters_And_Setters.pptx
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
 
C# Starter L04-Collections
C# Starter L04-CollectionsC# Starter L04-Collections
C# Starter L04-Collections
 
2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templates2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templates
 
Java generics
Java genericsJava generics
Java generics
 
Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++
 
Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]
 
Java class
Java classJava class
Java class
 
Templates2
Templates2Templates2
Templates2
 
Chapter 1 Presentation
Chapter 1 PresentationChapter 1 Presentation
Chapter 1 Presentation
 
Op ps
Op psOp ps
Op ps
 

Último

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 

Último (20)

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 

C# Generics

  • 2. Topics Why Generics are required? Generic types and functions , Type parameters and Constraints Difference between templates in C++ and Generics in C# Generic Delegates and event handling Generic Interfaces
  • 3. Introduction Generics are the most powerful feature of C# 2.0. Generics allow you to define type-safe data structures, without committing to actual data types. This results in a significant performance boost and higher quality code, because you get to reuse data processing algorithms without duplicating type-specific code. In concept, generics are similar to C++ templates, but are drastically different in implementation and capabilities.
  • 4. Why Generics are required? Consider an everyday data structure such as a stack, providing the classic Push() and Pop() methods. When developing a general-purpose stack, you would like to use it to store instances of various types. Under C# 1.1, you have to use an Object-based stack, meaning that the internal data type used in the stack is an amorphous Object, and the stack methods interact with Objects.
  • 5. An Object-based stack public class Stack { int m_Size; int m_StackPointer = 0; object[] m_Items; public Stack():this(100) {} public Stack(int size) { m_Size = size; m_Items = new object[m_Size]; }
  • 6. public void Push(object item) { if(m_StackPointer >= m_Size) throw new StackOverflowException(); m_Items[m_StackPointer] = item; m_StackPointer++; } public object Pop() { m_StackPointer--; if(m_StackPointer >= 0) return m_Items[m_StackPointer]; else { m_StackPointer = 0; throw new InvalidOperationException("empty stack"); } } }
  • 7. Problems with Object-based solutions Performance – When using value types, you have to box them in order to push and store them, and unbox the value types when popping them off the stack. Boxing and unboxing incurs a significant performance penalty it also increases the pressure on the managed heap, resulting in more garbage collections
  • 8. Type safety – the compiler lets you cast anything to and from Object, you lose compile-time type safety. Eg: the following code compiles fine, but raises an invalid cast exception at run time: Stack stack = new Stack(); stack.Push(1); string number = (string)stack.Pop();
  • 9. Generics Generics allow you to define type-safe classes without compromising type safety, performance, or productivity. public class Stack<T> {...} Stack<int> stack = new Stack<int>();
  • 10. Generic stack public class Stack<T> { int m_Size; int m_StackPointer = 0; T[] m_Items; public Stack():this(100){ } public Stack(int size) { m_Size = size; m_Items = new T[m_Size]; }
  • 11. public void Push(T item) { if(m_StackPointer >= m_Size) throw new StackOverflowException(); m_Items[m_StackPointer] = item; m_StackPointer++; } public T Pop() { m_StackPointer--; if(m_StackPointer >= 0) return m_Items[m_StackPointer]; else { m_StackPointer = 0; throw new InvalidOperationException("Cannot pop an empty stack"); } } }
  • 12. default() operator public T Pop() { m_StackPointer--; if(m_StackPointer >= 0) return m_Items[m_StackPointer]; else { m_StackPointer = 0; return default(T); } }
  • 13. Multiple Generic Types class Node<K,T> { public K Key; public T Item; public Node<K,T> NextNode; public Node() { Key = default(K); Item = default(T); NextNode = null; } public Node(K key,T item,Node<K,T> nextNode) { Key = key; Item = item; NextNode = nextNode; } }
  • 14. public class LinkedList<K,T> { Node<K,T> m_Head; public LinkedList() { m_Head = new Node<K,T>(); } public void AddHead(K key,T item) { Node<K,T> newNode = new Node<K,T>(key,item,m_Head.NextNode); m_Head.NextNode = newNode; } } LinkedList<int,string> list = new LinkedList<int,string>(); list.AddHead(123,"AAA");
  • 15. Generic type aliasing using List = LinkedList<int,string>; class ListClient { static void Main(string[] args) { List list = new List(); list.AddHead(123,"AAA"); } }
  • 16. Generic Constraints The compiler compiles the generic code into IL independent of any type arguments that the clients will use. As a result, the generic code could try to use methods, properties, or members of the generic type parameters that are incompatible with the specific type arguments the client uses. This is unacceptable because it amounts to lack of type safety.
  • 17. There are three types of constraints. A derivation constraint indicates to the compiler that the generic type parameter derives from a base type such an interface or a particular base class. A default constructor constraint indicates to the compiler that the generic type parameter exposes a default public constructor (a public constructor with no parameters). A reference/value type constraint constrains the generic type parameter to be a reference or a value type.
  • 18. Derivation Constraints The “where” keyword on the generic type parameter followed by a derivation colon to indicate to the compiler that the generic type parameter implements a particular interface.
  • 19. public class LinkedList<K,T> where K : IComparable { T Find(K key) { Node<K,T> current = m_Head; while(current.NextNode != null) { if(current.Key.CompareTo(key) == 0) break; else current = current.NextNode; } return current.Item; } ... }
  • 20. Multiple interfaces on the same generic type parameter, separated by a comma. For example: public class LinkedList<K,T> where K : IComparable<K>,Iconvertible {...} Constraints for every generic type parameter your class uses, for example: public class LinkedList<K,T> where K : IComparable<K> where T : ICloneable
  • 21. base class constraint public class MyBaseClass {...} public class LinkedList<K,T> where K : MyBaseClass {...} constrain both a base class and one or more interfaces public class LinkedList<K,T> where K : MyBaseClass, IComparable<K> {...}
  • 22. Constructor Constraint Suppose you want to instantiate a new generic object inside a generic class. The problem is the C# compiler does not know whether the type argument the client will use has a matching constructor, and it will refuse to compile the instantiation line. Its overcome using the “new()” constraint.
  • 23. class Node<K,T> where T : new() { public K Key; public T Item; public Node<K,T> NextNode; public Node() { Key = default(K); Item = new T(); NextNode = null; } }
  • 24. Reference/Value Type Constraint Value Type Constraint public class MyClass<T> where T : struct {...} Reference Type Constraint public class MyClass<T> where T : class {...}
  • 25. Generic Methods A method can define generic type parameters, specific to its execution scope. Generic Class: public class MyClass<T> { public void MyMethod<X>(X x) {...} } Non Generic Class: public class MyClass { public void MyMethod<T>(T t) {...} }
  • 26. Generic Delegates A delegate defined in a class can take advantage of the generic type parameter of that class. For example: public class MyClass<T> { public delegate void GenericDelegate(T t); public void SomeMethod(T t) {...} } MyClass<int> obj = new MyClass<int>(); MyClass<int>.GenericDelegate del; del = obj.SomeMethod;
  • 27. Generic Event Handiling namespace Generic_Delegates_and_Events { public delegate void GenericEventHandler<S,A>(S sender,A args); //generic delegate public class MyPublisher { public event GenericEventHandler<MyPublisher,EventArgs> MyEvent; public void FireEvent() { MyEvent(this,EventArgs.Empty); } } public class MySubscriber<A> //Optional: can be a specific type {
  • 28. public class MySubscriber2<A> //Optional: can be a specific type { public void SomeMethod2(MyPublisher sender, A args) { Console.WriteLine("MySubscriber2::SomeMethod2()"); } } class Program { static void Main(string[] args) { MyPublisher publisher = new MyPublisher(); MySubscriber<EventArgs> subscriber = new MySubscriber<EventArgs>(); publisher.MyEvent += subscriber.SomeMethod; MySubscriber2<EventArgs> subscriber2 = new MySubscriber2<EventArgs>(); publisher.MyEvent += subscriber2.SomeMethod2; publisher.FireEvent(); } } }
  • 29. Differences Between C++ Templates and C# Generics C# generics do not provide the same amount of flexibility as C++ templates. C# does not allow non-type template parameters, such as template C<int i> {}. C# does not support explicit specialization; that is, a custom implementation of a template for a specific type. C# does not support partial specialization: a custom implementation for a subset of the type arguments. C# does not allow the type parameter to be used as the base class for the generic type. C# does not allow type parameters to have default types. In C#, a generic type parameter cannot itself be a generic, although constructed types can be used as generics. C++ does allow template parameters.
  • 30. C# Generics is more type safe than C++ templates. C++ templates use a compile-time model. C# generics are not just a feature of the compiler, but also a feature of the runtime. Code Bloating is reduced in C# compared to C++. Generics have full run time support. Which is not available to templates.
  • 31. Generic Interfaces The System.Collections.Generic namespace contains interfaces and classes that define generic collections, which allow users to create strongly typed collections that provide better type safety and performance than non-generic strongly typed collections.
  • 32.
  • 33. ICollection<T> • Add(), Clear(), Contains(), CopyTo(), Remove(),Count, IsReadOnly • The interface ICollection<T> is implemented by collection classes. Methods of this interface can be used to add and remove elements from the collection. The generic interface ICollection<T> inherits from the non-generic interface IEnumerable. With this it is possible to pass objects implementing ICollection<T> to methods that require IEnumerable objects as parameters. IList<T> • Insert(), RemoveAt(), IndexOf(),Item • The interface IList<T> allows you to access a collection using an indexer. It is also possible to insert or remove elements at any position of the collection. Similar to ICollection<T>, the interface IList<T> inherits from IEnumerable. IEnumerable<T> • GetEnumerator() • The interface IEnumerable<T> is required if a foreach statement is used with the collection. This interface defines the method GetEnumerator() that returns an enumerator implementing IEnumerator<T>.The generic interface IEnumerable<T> inherits from the non- generic interface IEnumerable.
  • 34. IEnumerator<T> • Current • The foreach statement uses an enumerator implementing IEnumerator<T> for accessing all elements in a collection. The interface IEnumerator<T> inherits from the non-generic interfaces IEnumerator and IDisposable. The interface IEnumerator defines the methods MoveNext() and Reset(), IEnumerator<T> defines the type-safe version of the property Current. IDictionary<TKey, TValue> • Add(), ContainsKey(), Remove(), TryGetValue(),Item, Keys, Values • The interface IDictionary<K, V> is implemented by collections whose elements have a key and a value. IComparer<T> • Compare() • The interface IComparer<T> is used to sort elements inside a collection with the Compare() method. IEqualityComparer<T> • Equals(), GetHashCode() • IEqualityComparer<T> is the second interface to compare objects. With this interface the objects can be compared for equality. The method GetHashCode() should return a unique value for every object. The method Equals() returns true if the objects are equal, false otherwise.
  • 35. The ICollection<T> interface is the base interface for classes in the System.Collections.Generic namespace. The ICollection<T> interface extends IEnumerable<T>. IDictionary<TKey, TValue> and IList<T> are more specialized interfaces that extend ICollection<T>. A IDictionary<TKey, TValue> implementation is a collection of key/value pairs, like the Dictionary<TKey, TValue> class. A IList<T> implementation is a collection of values, and its members can be accessed by index, like the List<T> class.
  • 36. IEnumerable is an interface that defines one method GetEnumerator which returns an IEnumerator interface, this in turn allows readonly access to a collection. A collection that implements IEnumerable can be used with a foreach statement.
  • 37. public interface ICustomInterface<T> { void ShowMethod(); void SomeMethod(T t); } class CustomClass<U> : ICustomInterface<U> { U u; public CustomClass(U temp) { u = temp; } public void ShowMethod() { Console.WriteLine("Value: " + u); }
  • 38. public void SomeMethod(U t) { Console.WriteLine(t + " " + u); } } class Program { static void Main(string[] args) { CustomClass<int> MyClass = new CustomClass<int>(10); MyClass.ShowMethod(); CustomClass<int> MyClass2 = new CustomClass<int>(10); MyClass2.SomeMethod(20); } }