SlideShare una empresa de 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/

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Destacado

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
 

Destacado (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
 

Similar 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
 

Similar 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

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
 
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
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
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
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
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
 
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
 
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
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
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
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
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
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
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
 

Último (20)

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
 
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
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
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
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
+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...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
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
 
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...
 
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
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
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 ...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
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
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
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
 

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.