SlideShare uma empresa Scribd logo
1 de 18
Generics In and Out

Jaliya Udagedara
What are we going to discuss today?
• Non-Generic Collections
• Demo 1 : Non-Generic Collections
• Generic Collections
• Generic List<T> Class
• Generic IEnumerable<T> Interface
• Constraints on Type Parameter (T)
• Demo 2 : Generic Collections (List<T>)
• Demo 3 : Creating Custom Generic Class and more.

• Advantages of Generics
• Some Recommandations
Collections

ICollection

IList

IDictionary
Non-Generic Collections
• System.Collections (Not included in the default C#
template)
• Examples
• ArrayList
• HashTable etc.
• Store objects
• Add anything.

• Typecast on removal.
Demo 1
ArrayList and HashTable
Generic Collections
• System.Collections.Generic (Included in the default C#
template)
• Examples
• List<T>
• Dictionary<TKey, TValue> etc.
• Store objects
• Add item of specific type.

• No need to box/unbox.
Generic Collections contd.
• Generic Classes
• Generic Interfaces
• Generic Methods
• Generic Delegates
The Generic List Class (List<T>)
public class List<T> : IList<T>, ICollection<T>,
IList, ICollection, IReadOnlyList<T>,
IReadOnlyCollection<T>, IEnumerable<T>,
IEnumerable
• List<T> is the generic List class

• T represents the type parameter to be supplied in
declarations.
• Provides traditional list operations

• Insert/Delete
List<T> Methods
• Add (T item)
• Add item at end of list
• Insert (int index, T item)
• Insert item at a specific position
• Remove (T item)
• Remove first occurrence of item
• RemoveAt (int index)

• Remove item at specified position
List<T> Methods contd.
• Clear()
• Removes all items from the list
• bool Contains(T item)
• Determines if item is in the list
• int IndexOf(T item)
• Returns index of item, or -1 if not in list.
• Sort()
• Array.Sort method
• Insertion Sort / Heap Sort or Quick Sort
• …more
The Generic IEnumerable<T> Interface
public interface IEnumerable<out T> : IEnumerable

• Exposes the enumerator.
• Simple iteration over a collection of a specified type.
• List<T> implements IEnumerable<T>

• Methods
• GetEnumerator()
• A lot of extension methods (visit MSDN)
Generic Delegates
• What is a Delegate?
• Function Pointer in C++.
static void Method1(string s)
{
// body
}
static void Method2(int i)
{
// body
}
delegate void MyGenericDelegate<T>(T data);
Constraints on Type Parameter (T)
• where T : struct
• T must be a value type

• where T : class
• T must be reference type

• where T : <base class>
• T must be deriving from base class

• where T : <interface>
• T must be implementing the interface

• where T : new()
• T must have parameter less constructor
Demo 2
List<T>
Demo 3
Custom Generic Class, Generic
Methods, Type Constraints etc.
So what’s the advantage?

Reusable
Efficient

Type Safe (in compile time too)
Recommendations
• For all the applications which targets .NET 2.0 and above
use new generic collection classes instead of the older
non-generic counterparts.
• For most scenarios that require collection classes, the
recommended approach is to use the ones provided in
the .NET Framework class library.
• If the items in the collection are being added/removed
from different threads, use collections in the
System.Collections.Concurrent which is introduced with
.NET Framework 4.
Thank You!
http://www.jaliyaudagedara.blogspot.com/

Mais conteúdo relacionado

Mais procurados

Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6Berk Soysal
 
introduction to c #
introduction to c #introduction to c #
introduction to c #Sireesh K
 
Introduction to Type Script by Sam Goldman, SmartLogic
Introduction to Type Script by Sam Goldman, SmartLogicIntroduction to Type Script by Sam Goldman, SmartLogic
Introduction to Type Script by Sam Goldman, SmartLogicSmartLogic
 
Reflection power pointpresentation ppt
Reflection power pointpresentation pptReflection power pointpresentation ppt
Reflection power pointpresentation pptRohit Vipin Mathews
 
An introduction to java programming
An introduction to java programmingAn introduction to java programming
An introduction to java programminghoshmand kareem
 
Java Tutorial Lab 2
Java Tutorial Lab 2Java Tutorial Lab 2
Java Tutorial Lab 2Berk Soysal
 
Session 14 - Object Class
Session 14 - Object ClassSession 14 - Object Class
Session 14 - Object ClassPawanMM
 
Static Import and access modifiers
Static Import and access modifiersStatic Import and access modifiers
Static Import and access modifiersMaitree Patel
 
How to choose best containers in STL (C++)
How to choose best containers in STL (C++)How to choose best containers in STL (C++)
How to choose best containers in STL (C++)Sangharsh agarwal
 
Java Tutorial Lab 4
Java Tutorial Lab 4Java Tutorial Lab 4
Java Tutorial Lab 4Berk Soysal
 
Java Tutorial Lab 7
Java Tutorial Lab 7Java Tutorial Lab 7
Java Tutorial Lab 7Berk Soysal
 
Standard template library
Standard template libraryStandard template library
Standard template librarySukriti Singh
 
JAVA VIRTUAL MACHINE
JAVA VIRTUAL MACHINEJAVA VIRTUAL MACHINE
JAVA VIRTUAL MACHINEAadil Ansari
 

Mais procurados (20)

Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6
 
Python programming l2
Python programming l2Python programming l2
Python programming l2
 
introduction to c #
introduction to c #introduction to c #
introduction to c #
 
Introduction to Type Script by Sam Goldman, SmartLogic
Introduction to Type Script by Sam Goldman, SmartLogicIntroduction to Type Script by Sam Goldman, SmartLogic
Introduction to Type Script by Sam Goldman, SmartLogic
 
STL in C++
STL in C++STL in C++
STL in C++
 
Reflection power pointpresentation ppt
Reflection power pointpresentation pptReflection power pointpresentation ppt
Reflection power pointpresentation ppt
 
An introduction to java programming
An introduction to java programmingAn introduction to java programming
An introduction to java programming
 
#_ varible function
#_ varible function #_ varible function
#_ varible function
 
Variable
VariableVariable
Variable
 
Files io
Files ioFiles io
Files io
 
Java Tutorial Lab 2
Java Tutorial Lab 2Java Tutorial Lab 2
Java Tutorial Lab 2
 
Session 14 - Object Class
Session 14 - Object ClassSession 14 - Object Class
Session 14 - Object Class
 
Static Import and access modifiers
Static Import and access modifiersStatic Import and access modifiers
Static Import and access modifiers
 
How to choose best containers in STL (C++)
How to choose best containers in STL (C++)How to choose best containers in STL (C++)
How to choose best containers in STL (C++)
 
Java Tutorial Lab 4
Java Tutorial Lab 4Java Tutorial Lab 4
Java Tutorial Lab 4
 
ITFT - Java
ITFT - JavaITFT - Java
ITFT - Java
 
Java Tutorial Lab 7
Java Tutorial Lab 7Java Tutorial Lab 7
Java Tutorial Lab 7
 
Standard template library
Standard template libraryStandard template library
Standard template library
 
Namespace and methods
Namespace and methodsNamespace and methods
Namespace and methods
 
JAVA VIRTUAL MACHINE
JAVA VIRTUAL MACHINEJAVA VIRTUAL MACHINE
JAVA VIRTUAL MACHINE
 

Destaque

Windows communication foundation (part1) jaliya udagedara
Windows communication foundation (part1)    jaliya udagedaraWindows communication foundation (part1)    jaliya udagedara
Windows communication foundation (part1) jaliya udagedaraJaliya Udagedara
 
Windows communication foundation (part2) jaliya udagedara
Windows communication foundation (part2) jaliya udagedaraWindows communication foundation (part2) jaliya udagedara
Windows communication foundation (part2) jaliya udagedaraJaliya Udagedara
 
Introduction to Universal Apps-Jaliya Udagedara
Introduction to Universal Apps-Jaliya UdagedaraIntroduction to Universal Apps-Jaliya Udagedara
Introduction to Universal Apps-Jaliya UdagedaraJaliya Udagedara
 
Introduction to Universal Apps
Introduction to Universal AppsIntroduction to Universal Apps
Introduction to Universal AppsJaliya Udagedara
 
Universal Apps for Windows Devices
Universal Apps for Windows DevicesUniversal Apps for Windows Devices
Universal Apps for Windows DevicesJaliya Udagedara
 
Building Universal Apps for Windows and Windows Phone
Building Universal Apps for Windows and Windows PhoneBuilding Universal Apps for Windows and Windows Phone
Building Universal Apps for Windows and Windows PhoneJaliya Udagedara
 
Windows Phone Application Development
Windows Phone Application DevelopmentWindows Phone Application Development
Windows Phone Application DevelopmentJaliya Udagedara
 
Getting Started Developing Universal Windows Platform (UWP) Apps
Getting Started Developing Universal Windows Platform (UWP) AppsGetting Started Developing Universal Windows Platform (UWP) Apps
Getting Started Developing Universal Windows Platform (UWP) AppsJaliya Udagedara
 
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraLambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraJaliya Udagedara
 

Destaque (13)

Windows communication foundation (part1) jaliya udagedara
Windows communication foundation (part1)    jaliya udagedaraWindows communication foundation (part1)    jaliya udagedara
Windows communication foundation (part1) jaliya udagedara
 
Windows communication foundation (part2) jaliya udagedara
Windows communication foundation (part2) jaliya udagedaraWindows communication foundation (part2) jaliya udagedara
Windows communication foundation (part2) jaliya udagedara
 
Debugging C# Applications
Debugging C# ApplicationsDebugging C# Applications
Debugging C# Applications
 
Windows Runtime Apps
Windows Runtime AppsWindows Runtime Apps
Windows Runtime Apps
 
Introduction to Universal Apps-Jaliya Udagedara
Introduction to Universal Apps-Jaliya UdagedaraIntroduction to Universal Apps-Jaliya Udagedara
Introduction to Universal Apps-Jaliya Udagedara
 
Introduction to Universal Apps
Introduction to Universal AppsIntroduction to Universal Apps
Introduction to Universal Apps
 
Windows Runtime Apps
Windows Runtime AppsWindows Runtime Apps
Windows Runtime Apps
 
Universal Apps for Windows Devices
Universal Apps for Windows DevicesUniversal Apps for Windows Devices
Universal Apps for Windows Devices
 
Let's Explore C# 6
Let's Explore C# 6Let's Explore C# 6
Let's Explore C# 6
 
Building Universal Apps for Windows and Windows Phone
Building Universal Apps for Windows and Windows PhoneBuilding Universal Apps for Windows and Windows Phone
Building Universal Apps for Windows and Windows Phone
 
Windows Phone Application Development
Windows Phone Application DevelopmentWindows Phone Application Development
Windows Phone Application Development
 
Getting Started Developing Universal Windows Platform (UWP) Apps
Getting Started Developing Universal Windows Platform (UWP) AppsGetting Started Developing Universal Windows Platform (UWP) Apps
Getting Started Developing Universal Windows Platform (UWP) Apps
 
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraLambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
 

Semelhante a Generics In and Out

Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and JavaSasha Goldshtein
 
Tuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingTuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingPranavSB
 
CSharp for Unity - Day 1
CSharp for Unity - Day 1CSharp for Unity - Day 1
CSharp for Unity - Day 1Duong Thanh
 
.NET Fest 2018. Дмитрий Иванов. Иммутабельные структуры данных в .NET: зачем ...
.NET Fest 2018. Дмитрий Иванов. Иммутабельные структуры данных в .NET: зачем ....NET Fest 2018. Дмитрий Иванов. Иммутабельные структуры данных в .NET: зачем ...
.NET Fest 2018. Дмитрий Иванов. Иммутабельные структуры данных в .NET: зачем ...NETFest
 
an introduction to c++ templates-comprehensive guide.ppt
an introduction to c++ templates-comprehensive guide.pptan introduction to c++ templates-comprehensive guide.ppt
an introduction to c++ templates-comprehensive guide.pptAbdullah Yousafzai
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsRakesh Waghela
 
APEX 5 IR: Guts & Performance
APEX 5 IR:  Guts & PerformanceAPEX 5 IR:  Guts & Performance
APEX 5 IR: Guts & PerformanceKaren Cannell
 
APEX 5 IR Guts and Performance
APEX 5 IR Guts and PerformanceAPEX 5 IR Guts and Performance
APEX 5 IR Guts and PerformanceKaren Cannell
 

Semelhante a Generics In and Out (20)

Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and Java
 
c++ Unit III - PPT.pptx
c++ Unit III - PPT.pptxc++ Unit III - PPT.pptx
c++ Unit III - PPT.pptx
 
Tuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingTuples, Dicts and Exception Handling
Tuples, Dicts and Exception Handling
 
CSharp for Unity - Day 1
CSharp for Unity - Day 1CSharp for Unity - Day 1
CSharp for Unity - Day 1
 
.NET Fest 2018. Дмитрий Иванов. Иммутабельные структуры данных в .NET: зачем ...
.NET Fest 2018. Дмитрий Иванов. Иммутабельные структуры данных в .NET: зачем ....NET Fest 2018. Дмитрий Иванов. Иммутабельные структуры данных в .NET: зачем ...
.NET Fest 2018. Дмитрий Иванов. Иммутабельные структуры данных в .NET: зачем ...
 
Collections
CollectionsCollections
Collections
 
Generics in dot net
Generics in dot netGenerics in dot net
Generics in dot net
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
an introduction to c++ templates-comprehensive guide.ppt
an introduction to c++ templates-comprehensive guide.pptan introduction to c++ templates-comprehensive guide.ppt
an introduction to c++ templates-comprehensive guide.ppt
 
C# Colletion interfaces
C# Colletion interfacesC# Colletion interfaces
C# Colletion interfaces
 
C++ STL 概觀
C++ STL 概觀C++ STL 概觀
C++ STL 概觀
 
Ch02
Ch02Ch02
Ch02
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
 
Generics
GenericsGenerics
Generics
 
Java Advanced Features
Java Advanced FeaturesJava Advanced Features
Java Advanced Features
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
APEX 5 IR: Guts & Performance
APEX 5 IR:  Guts & PerformanceAPEX 5 IR:  Guts & Performance
APEX 5 IR: Guts & Performance
 
APEX 5 IR Guts and Performance
APEX 5 IR Guts and PerformanceAPEX 5 IR Guts and Performance
APEX 5 IR Guts and Performance
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 

Último

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
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
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
 
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
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
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
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
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
 
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
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
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
 

Último (20)

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
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
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
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
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
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
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, ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
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...
 
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...
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
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
 

Generics In and Out

  • 1. Generics In and Out Jaliya Udagedara
  • 2. What are we going to discuss today? • Non-Generic Collections • Demo 1 : Non-Generic Collections • Generic Collections • Generic List<T> Class • Generic IEnumerable<T> Interface • Constraints on Type Parameter (T) • Demo 2 : Generic Collections (List<T>) • Demo 3 : Creating Custom Generic Class and more. • Advantages of Generics • Some Recommandations
  • 4. Non-Generic Collections • System.Collections (Not included in the default C# template) • Examples • ArrayList • HashTable etc. • Store objects • Add anything. • Typecast on removal.
  • 6. Generic Collections • System.Collections.Generic (Included in the default C# template) • Examples • List<T> • Dictionary<TKey, TValue> etc. • Store objects • Add item of specific type. • No need to box/unbox.
  • 7. Generic Collections contd. • Generic Classes • Generic Interfaces • Generic Methods • Generic Delegates
  • 8. The Generic List Class (List<T>) public class List<T> : IList<T>, ICollection<T>, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable • List<T> is the generic List class • T represents the type parameter to be supplied in declarations. • Provides traditional list operations • Insert/Delete
  • 9. List<T> Methods • Add (T item) • Add item at end of list • Insert (int index, T item) • Insert item at a specific position • Remove (T item) • Remove first occurrence of item • RemoveAt (int index) • Remove item at specified position
  • 10. List<T> Methods contd. • Clear() • Removes all items from the list • bool Contains(T item) • Determines if item is in the list • int IndexOf(T item) • Returns index of item, or -1 if not in list. • Sort() • Array.Sort method • Insertion Sort / Heap Sort or Quick Sort • …more
  • 11. The Generic IEnumerable<T> Interface public interface IEnumerable<out T> : IEnumerable • Exposes the enumerator. • Simple iteration over a collection of a specified type. • List<T> implements IEnumerable<T> • Methods • GetEnumerator() • A lot of extension methods (visit MSDN)
  • 12. Generic Delegates • What is a Delegate? • Function Pointer in C++. static void Method1(string s) { // body } static void Method2(int i) { // body } delegate void MyGenericDelegate<T>(T data);
  • 13. Constraints on Type Parameter (T) • where T : struct • T must be a value type • where T : class • T must be reference type • where T : <base class> • T must be deriving from base class • where T : <interface> • T must be implementing the interface • where T : new() • T must have parameter less constructor
  • 15. Demo 3 Custom Generic Class, Generic Methods, Type Constraints etc.
  • 16. So what’s the advantage? Reusable Efficient Type Safe (in compile time too)
  • 17. Recommendations • For all the applications which targets .NET 2.0 and above use new generic collection classes instead of the older non-generic counterparts. • For most scenarios that require collection classes, the recommended approach is to use the ones provided in the .NET Framework class library. • If the items in the collection are being added/removed from different threads, use collections in the System.Collections.Concurrent which is introduced with .NET Framework 4.