SlideShare a Scribd company logo
1 of 11
Generics
Generics Overview
Generic Class
Generic interfaces
Generic Structs
Generic Methods
Generics Overview
 Generics introduce to the .NET Framework the
  concept of type parameters, 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.

 The .NET Framework class library contains several
  new generic collection classes in the
  System.Collections.Generic namespace.

 Generics allow you to define type-safe classes
  without compromising type safety, performance, or
  productivity.
Generics Overview
 We use generic types to maximize Code Reuse, Type
  Safety, Performance, and Code Bloat.
 Generics Features
   Default Values
     It is not possible to assign null to generic type
     You can use default keyword to initialize default (Either 0 or null) value.
   Constraints
     If Generic Class needs to invoke some methods from the generic type,
      you have to add constraints.
   Inheritance
     A generic type can implement a generic interface.
     When deriving from a generic base class, you must provide a type
      argument instead of the base-class's generic type parameter.
   Static Members
     Static Members of generic class are only shared with one instantiation of
      the class.
Generic Class
 Generic classes encapsulate operations that are not
  specific to a particular data type.
 The most common use for generic classes is with
  collections like linked lists, hash tables, stacks, queues,
  trees, and so on.
 Operations such as adding and removing items from the
  collection are performed in basically the same way
  regardless of the type of data being stored.
 Syntax:
      public class ClassName<T>
      {//Class Members………………}
Generic Class
 Constraints:
   When you define a generic class, you can apply restrictions
    to the kinds of types that client code can use for type
    arguments when it instantiates your class.
     EX:
      class EmployeeList<T> where T : Employee, IEmployee,
      System.IComparable<T>, new()
      { // ... }
 You can apply constraints to multiple parameters, and
  multiple constraints to a single parameter.
Generic Interfaces
 Generic Interfaces
    It is often useful to define interfaces either for generic
     collection classes, or for the generic classes that
     represent items in the collection.
    We use generic interfaces to avoid boxing and
     unboxing operations on value types.
    The .NET Framework class library defines several
     generic interfaces for use with the collection classes in
     the System.Collections.Generic namespace.
Generic Interfaces
 Covariance and Contra-variance in Generics
    Covariant and contra-variant generic type parameters
     provide greater flexibility in assigning and using
     generic types.
    For example, covariant type parameters enable you to
     make assignments that look much like ordinary
     polymorphism.
 Covariance with Generic Interface
    A generic Interface is Covariant if the type is
     annotated with out keyword.
 Contra-variance with Generic Interface
     A generic Interface is Contra-variant if the type is annotated
      with in keyword.
Generic Structs
 Generic Structs
   Similar to Classes structs can be generic as well.
   They are similar to generic classes with the
    exception of inheritance features.
   Ex:
     public struct Nullable<T>
     {//…….}
Generic Methods
 Generic Methods
    A generic method is a method that is declared with type
     parameters, as follows:
       static void Swap<T>(ref T lhs, ref T rhs)
       {
          T temp;
         temp = lhs;
         lhs = rhs;
         rhs = temp;
      }
 You can define method-specific generic type parameters
  even if the containing class does not use generics at all
Generic Methods with
  Constraints
 We can have Constraints on methods also.
 When a method defines its own generic type
  parameters, it can also define constraints for these
  types.
     public void SomeMethod<T>(T t ) where T : IComparable<T>
      {...}
 You cannot provide method-level constraints for class-
  level generic type parameters. All constraints for class-
  level generic type parameters must be defined at the
  class scope.
Generic Delegates
 A delegate defined in a class can take advantage of
 the generic type parameter of that class. For
 example:
   Ex:
     public delegate void Del<T>(T item);
     public static void Notify(int i) { }
     Del<int> m1 = new Del<int>(Notify);
 Generic Methods Specialization
     Generic methods can be overloaded to define specializations
      for specific types.
     This is true for methods with generic parameters as well.

More Related Content

What's hot

Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of ConstructorsDhrumil Panchal
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Conceptsthinkphp
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloadinggarishma bhatia
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introductionSohanur63
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaMOHIT AGARWAL
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonSujith Kumar
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and InterfaceHaris Bin Zahid
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functionsHarsh Patel
 
virtual function
virtual functionvirtual function
virtual functionVENNILAV6
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 

What's hot (20)

Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of Constructors
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloading
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introduction
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
 
Delegates and events in C#
Delegates and events in C#Delegates and events in C#
Delegates and events in C#
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
 
virtual function
virtual functionvirtual function
virtual function
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Methods and constructors in java
Methods and constructors in javaMethods and constructors in java
Methods and constructors in java
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 

Viewers also liked

Intro To .Net Threads
Intro To .Net ThreadsIntro To .Net Threads
Intro To .Net Threadsrchakra
 
Multi threading design pattern
Multi threading design patternMulti threading design pattern
Multi threading design patternYan Wang
 
C# Advanced L04-Threading
C# Advanced L04-ThreadingC# Advanced L04-Threading
C# Advanced L04-ThreadingMohammad Shaker
 
Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and JavaSasha Goldshtein
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101Tim Penhey
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done rightPlatonov Sergey
 
Threading in c#
Threading in c#Threading in c#
Threading in c#gohsiauken
 

Viewers also liked (11)

Delegates and events
Delegates and events   Delegates and events
Delegates and events
 
Intro To .Net Threads
Intro To .Net ThreadsIntro To .Net Threads
Intro To .Net Threads
 
Multi threading design pattern
Multi threading design patternMulti threading design pattern
Multi threading design pattern
 
C# Advanced L04-Threading
C# Advanced L04-ThreadingC# Advanced L04-Threading
C# Advanced L04-Threading
 
Collections in-csharp
Collections in-csharpCollections in-csharp
Collections in-csharp
 
Multithreading Design Patterns
Multithreading Design PatternsMultithreading Design Patterns
Multithreading Design Patterns
 
Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and Java
 
Threading in C#
Threading in C#Threading in C#
Threading in C#
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done right
 
Threading in c#
Threading in c#Threading in c#
Threading in c#
 

Similar to Generics C# (20)

Generics
GenericsGenerics
Generics
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
Evolution of c# - by K.Jegan
Evolution of c# - by K.JeganEvolution of c# - by K.Jegan
Evolution of c# - by K.Jegan
 
Generic Programming in java
Generic Programming in javaGeneric Programming in java
Generic Programming in java
 
LectureNotes-02-DSA
LectureNotes-02-DSALectureNotes-02-DSA
LectureNotes-02-DSA
 
SOEN6441.generics.ppt
SOEN6441.generics.pptSOEN6441.generics.ppt
SOEN6441.generics.ppt
 
Generics
GenericsGenerics
Generics
 
Lecture 8 Library classes
Lecture 8 Library classesLecture 8 Library classes
Lecture 8 Library classes
 
Generics
GenericsGenerics
Generics
 
Objects and Types C#
Objects and Types C#Objects and Types C#
Objects and Types C#
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
.Net F# Generic class
.Net F# Generic class.Net F# Generic class
.Net F# Generic class
 
C# program structure
C# program structureC# program structure
C# program structure
 
java tutorial 4
 java tutorial 4 java tutorial 4
java tutorial 4
 
Template C++ OOP
Template C++ OOPTemplate C++ OOP
Template C++ OOP
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
Csharp generics
Csharp genericsCsharp generics
Csharp generics
 
Generic programming in java
Generic programming in javaGeneric programming in java
Generic programming in java
 

More from Raghuveer Guthikonda (7)

C# String
C# StringC# String
C# String
 
C# Delegates
C# DelegatesC# Delegates
C# Delegates
 
Operators & Casts
Operators & CastsOperators & Casts
Operators & Casts
 
Arrays C#
Arrays C#Arrays C#
Arrays C#
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#
 
Introduction to .NET Framework
Introduction to .NET FrameworkIntroduction to .NET Framework
Introduction to .NET Framework
 
Regex in C#
Regex in C#Regex in C#
Regex in C#
 

Recently uploaded

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
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
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
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
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 

Recently uploaded (20)

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
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
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
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
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
+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...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 

Generics C#

  • 1. Generics Generics Overview Generic Class Generic interfaces Generic Structs Generic Methods
  • 2. Generics Overview  Generics introduce to the .NET Framework the concept of type parameters, 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.  The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace.  Generics allow you to define type-safe classes without compromising type safety, performance, or productivity.
  • 3. Generics Overview  We use generic types to maximize Code Reuse, Type Safety, Performance, and Code Bloat.  Generics Features  Default Values  It is not possible to assign null to generic type  You can use default keyword to initialize default (Either 0 or null) value.  Constraints  If Generic Class needs to invoke some methods from the generic type, you have to add constraints.  Inheritance  A generic type can implement a generic interface.  When deriving from a generic base class, you must provide a type argument instead of the base-class's generic type parameter.  Static Members  Static Members of generic class are only shared with one instantiation of the class.
  • 4. Generic Class  Generic classes encapsulate operations that are not specific to a particular data type.  The most common use for generic classes is with collections like linked lists, hash tables, stacks, queues, trees, and so on.  Operations such as adding and removing items from the collection are performed in basically the same way regardless of the type of data being stored.  Syntax: public class ClassName<T> {//Class Members………………}
  • 5. Generic Class  Constraints:  When you define a generic class, you can apply restrictions to the kinds of types that client code can use for type arguments when it instantiates your class.  EX: class EmployeeList<T> where T : Employee, IEmployee, System.IComparable<T>, new() { // ... }  You can apply constraints to multiple parameters, and multiple constraints to a single parameter.
  • 6. Generic Interfaces  Generic Interfaces  It is often useful to define interfaces either for generic collection classes, or for the generic classes that represent items in the collection.  We use generic interfaces to avoid boxing and unboxing operations on value types.  The .NET Framework class library defines several generic interfaces for use with the collection classes in the System.Collections.Generic namespace.
  • 7. Generic Interfaces  Covariance and Contra-variance in Generics  Covariant and contra-variant generic type parameters provide greater flexibility in assigning and using generic types.  For example, covariant type parameters enable you to make assignments that look much like ordinary polymorphism.  Covariance with Generic Interface  A generic Interface is Covariant if the type is annotated with out keyword.  Contra-variance with Generic Interface  A generic Interface is Contra-variant if the type is annotated with in keyword.
  • 8. Generic Structs  Generic Structs  Similar to Classes structs can be generic as well.  They are similar to generic classes with the exception of inheritance features.  Ex: public struct Nullable<T> {//…….}
  • 9. Generic Methods  Generic Methods  A generic method is a method that is declared with type parameters, as follows: static void Swap<T>(ref T lhs, ref T rhs) { T temp; temp = lhs; lhs = rhs; rhs = temp; }  You can define method-specific generic type parameters even if the containing class does not use generics at all
  • 10. Generic Methods with Constraints  We can have Constraints on methods also.  When a method defines its own generic type parameters, it can also define constraints for these types.  public void SomeMethod<T>(T t ) where T : IComparable<T> {...}  You cannot provide method-level constraints for class- level generic type parameters. All constraints for class- level generic type parameters must be defined at the class scope.
  • 11. Generic Delegates  A delegate defined in a class can take advantage of the generic type parameter of that class. For example:  Ex: public delegate void Del<T>(T item); public static void Notify(int i) { } Del<int> m1 = new Del<int>(Notify);  Generic Methods Specialization  Generic methods can be overloaded to define specializations for specific types.  This is true for methods with generic parameters as well.

Editor's Notes

  1. With C# generics, 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. In C# you need to instruct the compiler which constraints the client-specified types must obey in order for them to be used instead of the generic type parameters