SlideShare ist ein Scribd-Unternehmen logo
1 von 19
Generics 
Collections
Why do we need Generics? 
 Another method of software re-use. 
 When we implement an algorithm, we want to re-use it for 
different types. 
 Example: We write a generic method for sorting an array of 
objects, then call the generic method with an array of any type. 
 The compiler performs type checking to ensure that the array 
passed to the sorting method contains only elements of the 
same type. 
 Generics provide compile-time type safety.
Generic Methods 
 Generic methods enable you to specify, with a single method 
declaration, a set of related methods. 
 Example: OverloadedMethods.cs 
‱ Note that the array element type (int, double or char) 
appears only once in each method—in the method header. 
‱ If we replace the element types in each method with a 
generic name then all three methods would look like follows: 
private static void DisplayArray( T[] inputArray ) 
{ 
foreach ( T element in inputArray ) 
Console.Write( element + " " ); 
Console.WriteLine( "n" ); 
} 
 However, it will not compile, because its syntax is not correct. 
 GenericMethods.cs
Generic Methods 
 All generic method declarations have a type-parameter list delimited by 
angle brackets that follows the method’s name. 
 Each type-parameter list contains one or more type parameters. 
 A type parameter is an identifier that is used in place of actual type names. 
 The type parameters can be used to declare the return type, the parameter 
types and the local variable types in a generic method declaration. 
 Type parameters act as placeholders for type arguments that represent the 
types of data that will be passed to the generic method. 
 A generic method’s body is declared like that of any other method. 
 The type-parameter names throughout the method declaration must 
match those declared in the type-parameter list. 
 A type parameter can be declared only once in the type-parameter list but 
can appear more than once in the method’s parameter list. 
 You can also use explicit type arguments to indicate the 
exact type that should be used to call a generic function, as in 
DisplayArray< int >( intArray );
Generic Classes 
 A generic class describes a class in a type-independent 
manner. 
 We can then instantiate type-specific objects of the generic 
class. 
 Let’s look at example: Stack.sln 
 StackTest.cs: repeats code in 
TestPopInt/TestPopDouble and 
TestPushInt/TestPushDouble 
 How to fix this? Let’s code this together first. 
 NewStackTest.cs
Generic Interfaces 
 In NewStackTest.cs, we used a generic interface: 
IEnumerable < T > 
 Similar to generic classes, generic interfaces enable you to 
specify, with a single interface declaration, a set of related 
interfaces.
Common Data Structures - summary 
 We’ve seen Array only so far  fixed-size (can grow with 
Resize) 
 Dynamic data structures can automatically grow and shrink 
at execution time. 
 Linked lists are collections of data items that are “chained 
together”. 
 Stacks have insertions and deletions made at only 
one end: the top. 
 Queues represent waiting lines; insertions are made 
at the back and deletions are made from the front. 
 Binary trees facilitate high-speed searching and sorting of 
data.
Collections 
 For the vast majority of applications, there is no need to 
build custom data structures. 
 Instead, you can use the prepackaged data-structure 
classes provided by the .NET Framework. 
 These classes are known as collection classes—they store 
collections of data. Each instance of one of these classes is 
a collection of items. 
 Collection classes enable programmers to store sets of 
items by using existing data structures, without concern for 
how they are implemented. 
 System.Collections contains collections that store 
references to objects.
ArrayList 
 The ArrayList collection class is a conventional arrays and 
provides dynamic resizing of the collection. 
Method / Property Description 
Add Adds an object to the end of the ArrayList. 
Capacity Property that gets and sets the number of elements for which space 
is currently reserved in the ArrayList. 
Clear Removes all elements from the ArrayList. 
Contains Determines whether an element is in the ArrayList. 
Count Read-only property that gets the number of elements stored in the 
ArrayList. 
IndexOf Returns the zero-based index of the first occurrence of a value in the 
ArrayList 
Insert Inserts an element into the ArrayList at the specified index. 
Remove Removes the first occurrence of a specific object from the ArrayList. 
RemoveAt Removes the element at the specified index of the ArrayList. 
TrimToSize Sets the capacity to the actual number of elements in the ArrayList.
ArrayList 
 Let’s write code to use ArrayList. 
 Suppose we have two color string arrays as follows: 
private static readonly string[] colors = 
{ "MAGENTA", "RED", "WHITE", "BLUE", "CYAN" }; 
private static readonly string[] removeColors = 
{ "RED", "WHITE", "BLUE" }; 
1. Let’s create an arrayList and add items in colors into it. 
2. Let’s display the size and capacity of arrayList. 
3. Let’s find the index of the item “BLUE”. 
4. Let’s write a method that removes the items in one 
ArrayList from another. And then call that method to 
remove removeColors array from our first arrayList. 
5. ArrayListTest.cs
Generic Collections 
Problems with Nongeneric Collections 
 Having to store data as object references causes less efficient 
code due to unboxing. 
 The .NET Framework also includes the 
System.Collections.Generic namespace, which 
uses C#’s generics capabilities. 
 Many of these new classes are simply generic counterparts 
of the classes in namespace System.Collections. 
 Generic collections eliminate the need for explicit type casts 
that decrease type safety and efficiency. 
 Generic collections are especially useful for storing structs, 
since they eliminate the overhead of boxing and unboxing.
SortedDictionary<TKey, TValue> 
 A dictionary is the general term for a collection of key/value 
pairs. 
 A hash table is one way to implement a dictionary. 
 Example: Let’s write a program that counts the number of 
occurrences of each word in a string read from console using 
SortedDictionary. 
 To split the sentence into words, we will use this: 
// split input text into tokens 
string[] words = Regex.Split( input, @"s+" ); 
 http://msdn.microsoft.com/en-us/library/xfhwa508.aspx 
 Members: 
 http://msdn.microsoft.com/en-us/library/3eayzh46.aspx
Collection Interfaces 
 All collection classes in the .NET Framework implement 
some combination of the collection interfaces. 
Interface Description 
ICollection The root interface from which interfaces IList and IDictionary inherit. 
Contains a Count property to determine the size of a collection and a 
CopyTo method for copying a collection’s contents into a traditional array. 
IList An ordered collection that can be manipulated like an array. Provides an 
indexer for accessing elements with an int index. Also has methods for 
searching and modifying a collection, including Add, Remove, Contains 
and IndexOf. 
IEnumerable An object that can be enumerated. This interface contains exactly one 
method, GetEnumerator, which returns an IEnumerator object. ICollection 
implements IEnumerable, so all collection classes implement IEnumerable 
directly or indirectly. 
IDictionary A collection of values, indexed by an arbitrary “key” object. Provides an 
indexer for accessing elements with an object index and methods for 
modifying the collection (e.g., Add, Remove). IDictionary property Keys 
contains the objects used as indices, and property Values contains all the 
stored objects.
HashTable 
 Arrays uses nonnegative integer indexes as keys. Sometimes 
associating these integer keys with objects to store them is 
impractical, so we develop a scheme for using arbitrary keys. 
 When an application needs to store something, the scheme 
could convert the application key rapidly to an index. 
 Once the application has a key for which it wants to retrieve 
the data, simply apply the conversion to the key to find the 
array index where the data resides. 
 The scheme we describe here is the basis of a technique 
called hashing, in which we store data in a data structure 
called a hash table.
HashTable 
 A hash function performs a calculation that determines 
where to place data in the hash table. 
 The hash function is applied to the key in a key/value pair 
of objects. 
 Class Hashtable can accept any object as a key. For this 
reason, class object defines method GetHashCode, 
which all objects inherit. 
 Example: Let’s write a program that counts the number of 
occurrences of each word in a string read from console. 
 To split the sentence into words, we will use this: 
// split input text into tokens 
string[] words = Regex.Split( input, @"s+" ); 
 HashTable solution.
HashTable 
 Hashtable method ContainsKey determines whether a key is in the 
hash table. 
 Read-only property Keys returns an ICollection that contains all 
the keys. 
 Hashtable property Count returns the number of key/value pairs in the 
Hashtable. 
 If you use a foreach statement with a Hashtable object, the iteration 
variable will be of type DictionaryEntry. 
 The enumerator of a Hashtable (or any other class that implements 
IDictionary) uses the DictionaryEntry structure to store key/value pairs. 
 This structure provides properties Key and Value for retrieving the key 
and value of the current element. 
 If you do not need the key, class Hashtable also provides a read-only 
Values property that gets an ICollection of all the values stored in 
the Hashtable.
Stack & Queue 
 Stack: 
 Push 
 Pop 
 Peek 
 Example: 
 StackTest.cs 
 Queue: 
 Enqueue 
 Dequeue 
 Peek 
 Exercise: re-write the 
StackTest.cs example at home 
using a Queue this time.
Generic Collection Interfaces 
Interface Description 
ICollection(T) Defines methods to manipulate generic collections. 
IList(T) Represents a collection of objects that can be individually 
accessed by index. 
IEnumerable(T) Exposes the enumerator, which supports a simple iteration 
over a collection of a specified type. 
IEnumerator(T) Supports a simple iteration over a generic collection. 
IDictionary(TKey,TValue) Represents a generic collection of key/value pairs. 
IComparer(T) Defines a method that a type implements to compare two 
objects. 
http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx
Other Generic Collection Classes 
 List(T) 
 Let’s re-write the ArrayListTest.cs using List<T> this time. 
 Stack(T) 
 Queue(T) 
 LinkedList(T) 
 SortedList(TKey, TValue)

Weitere Àhnliche Inhalte

Was ist angesagt?

SQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJSQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJDharita Chokshi
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events WebStackAcademy
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in JavaVadym Lotar
 
SQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONSQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONArun Sial
 
Active Server Page(ASP)
Active Server Page(ASP)Active Server Page(ASP)
Active Server Page(ASP)Keshab Nath
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScriptBala Narayanan
 
Aggregate functions
Aggregate functionsAggregate functions
Aggregate functionssinhacp
 
Ddl &amp; dml commands
Ddl &amp; dml commandsDdl &amp; dml commands
Ddl &amp; dml commandsAnjaliJain167
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScriptShahDhruv21
 
Computer Science-Data Structures :Abstract DataType (ADT)
Computer Science-Data Structures :Abstract DataType (ADT)Computer Science-Data Structures :Abstract DataType (ADT)
Computer Science-Data Structures :Abstract DataType (ADT)St Mary's College,Thrissur,Kerala
 
Java collections concept
Java collections conceptJava collections concept
Java collections conceptkumar gaurav
 
collection framework in java
collection framework in javacollection framework in java
collection framework in javaMANOJ KUMAR
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List Hitesh-Java
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types pptkamal kotecha
 
Entity Relationship Diagram
Entity Relationship DiagramEntity Relationship Diagram
Entity Relationship DiagramShakila Mahjabin
 
Integrity Constraints
Integrity ConstraintsIntegrity Constraints
Integrity Constraintsmadhav bansal
 
The Stack And Recursion
The Stack And RecursionThe Stack And Recursion
The Stack And RecursionAshim Lamichhane
 

Was ist angesagt? (20)

SQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJSQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJ
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
SQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONSQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTION
 
Active Server Page(ASP)
Active Server Page(ASP)Active Server Page(ASP)
Active Server Page(ASP)
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Android adapters
Android adaptersAndroid adapters
Android adapters
 
Aggregate functions
Aggregate functionsAggregate functions
Aggregate functions
 
Ddl &amp; dml commands
Ddl &amp; dml commandsDdl &amp; dml commands
Ddl &amp; dml commands
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
 
Computer Science-Data Structures :Abstract DataType (ADT)
Computer Science-Data Structures :Abstract DataType (ADT)Computer Science-Data Structures :Abstract DataType (ADT)
Computer Science-Data Structures :Abstract DataType (ADT)
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
NUMPY
NUMPY NUMPY
NUMPY
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
Entity Relationship Diagram
Entity Relationship DiagramEntity Relationship Diagram
Entity Relationship Diagram
 
Integrity Constraints
Integrity ConstraintsIntegrity Constraints
Integrity Constraints
 
The Stack And Recursion
The Stack And RecursionThe Stack And Recursion
The Stack And Recursion
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 

Andere mochten auch

Requirements elicitation
Requirements elicitationRequirements elicitation
Requirements elicitationAbdul Basit
 
Usecase diagram railway reservation system
Usecase diagram railway reservation systemUsecase diagram railway reservation system
Usecase diagram railway reservation systemmuthumeenakshim
 
use case diagramHospital managment system
use case diagramHospital managment systemuse case diagramHospital managment system
use case diagramHospital managment systemYaswanth Babu Gummadivelli
 
business analyst interview questions and answers
business analyst interview questions and answersbusiness analyst interview questions and answers
business analyst interview questions and answersCongress Man
 
Business analyst interview questions and answers
Business analyst interview questions and answersBusiness analyst interview questions and answers
Business analyst interview questions and answersRobin G
 
Use of ict tools for teaching –learning
Use of ict tools for teaching –learningUse of ict tools for teaching –learning
Use of ict tools for teaching –learningVenkat Srinivasan
 
Business Analyst Training
Business  Analyst  TrainingBusiness  Analyst  Training
Business Analyst TrainingCraig Brown
 
Business Analysis Fundamentals
Business Analysis FundamentalsBusiness Analysis Fundamentals
Business Analysis Fundamentalswaelsaid75
 
Business analysis interview question and answers
Business analysis interview question and answersBusiness analysis interview question and answers
Business analysis interview question and answersGaruda Trainings
 
85 business analyst interview questions and answers
85 business analyst interview questions and answers85 business analyst interview questions and answers
85 business analyst interview questions and answersBusinessAnalyst247
 

Andere mochten auch (17)

Requirements elicitation
Requirements elicitationRequirements elicitation
Requirements elicitation
 
collections
 collections collections
collections
 
multi threading
multi threadingmulti threading
multi threading
 
Usecase diagram railway reservation system
Usecase diagram railway reservation systemUsecase diagram railway reservation system
Usecase diagram railway reservation system
 
use case diagramHospital managment system
use case diagramHospital managment systemuse case diagramHospital managment system
use case diagramHospital managment system
 
exception handling
 exception handling exception handling
exception handling
 
C#4.0 features
C#4.0 featuresC#4.0 features
C#4.0 features
 
business analyst interview questions and answers
business analyst interview questions and answersbusiness analyst interview questions and answers
business analyst interview questions and answers
 
Bill Gates
Bill GatesBill Gates
Bill Gates
 
Business analyst interview questions and answers
Business analyst interview questions and answersBusiness analyst interview questions and answers
Business analyst interview questions and answers
 
Use of ict tools for teaching –learning
Use of ict tools for teaching –learningUse of ict tools for teaching –learning
Use of ict tools for teaching –learning
 
Use Case Modeling
Use Case ModelingUse Case Modeling
Use Case Modeling
 
Business Analyst Training
Business  Analyst  TrainingBusiness  Analyst  Training
Business Analyst Training
 
Business Analysis Fundamentals
Business Analysis FundamentalsBusiness Analysis Fundamentals
Business Analysis Fundamentals
 
Business analyst ppt
Business analyst pptBusiness analyst ppt
Business analyst ppt
 
Business analysis interview question and answers
Business analysis interview question and answersBusiness analysis interview question and answers
Business analysis interview question and answers
 
85 business analyst interview questions and answers
85 business analyst interview questions and answers85 business analyst interview questions and answers
85 business analyst interview questions and answers
 

Ähnlich wie Generics collections

Generics Collections
Generics CollectionsGenerics Collections
Generics Collectionsphanleson
 
Collections
CollectionsCollections
Collectionssagsharma
 
Collections generic
Collections genericCollections generic
Collections genericsandhish
 
Array list(1)
Array list(1)Array list(1)
Array list(1)abdullah619
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections TutorialsProf. Erwin Globio
 
Md08 collection api
Md08 collection apiMd08 collection api
Md08 collection apiRakesh Madugula
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanZeeshan Khan
 
Net framework session02
Net framework session02Net framework session02
Net framework session02Vivek chan
 
Ap Power Point Chpt6
Ap Power Point Chpt6Ap Power Point Chpt6
Ap Power Point Chpt6dplunkett
 
Java collections
Java collectionsJava collections
Java collectionspadmad2291
 
Generic Programming &amp; Collection
Generic Programming &amp; CollectionGeneric Programming &amp; Collection
Generic Programming &amp; CollectionArya
 
Generic Programming &amp; Collection
Generic Programming &amp; CollectionGeneric Programming &amp; Collection
Generic Programming &amp; CollectionArya
 
oop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionoop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionssuseredfbe9
 
Data structures and algorithms arrays
Data structures and algorithms   arraysData structures and algorithms   arrays
Data structures and algorithms arrayschauhankapil
 
Ppt lesson 12
Ppt lesson 12Ppt lesson 12
Ppt lesson 12Linda Bodrie
 
A04
A04A04
A04lksoo
 

Ähnlich wie Generics collections (20)

Generics Collections
Generics CollectionsGenerics Collections
Generics Collections
 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
 
Collections
CollectionsCollections
Collections
 
Collections generic
Collections genericCollections generic
Collections generic
 
Array list(1)
Array list(1)Array list(1)
Array list(1)
 
Java.util
Java.utilJava.util
Java.util
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Md08 collection api
Md08 collection apiMd08 collection api
Md08 collection api
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
Net framework session02
Net framework session02Net framework session02
Net framework session02
 
Ap Power Point Chpt6
Ap Power Point Chpt6Ap Power Point Chpt6
Ap Power Point Chpt6
 
Arrays C#
Arrays C#Arrays C#
Arrays C#
 
Java collections
Java collectionsJava collections
Java collections
 
Generic Programming &amp; Collection
Generic Programming &amp; CollectionGeneric Programming &amp; Collection
Generic Programming &amp; Collection
 
Generic Programming &amp; Collection
Generic Programming &amp; CollectionGeneric Programming &amp; Collection
Generic Programming &amp; Collection
 
oop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionoop lecture framework,list,maps,collection
oop lecture framework,list,maps,collection
 
Data structures and algorithms arrays
Data structures and algorithms   arraysData structures and algorithms   arrays
Data structures and algorithms arrays
 
Arrays
ArraysArrays
Arrays
 
Ppt lesson 12
Ppt lesson 12Ppt lesson 12
Ppt lesson 12
 
A04
A04A04
A04
 

Mehr von Yaswanth Babu Gummadivelli (20)

Presentation on BA
Presentation on BAPresentation on BA
Presentation on BA
 
ERP
ERPERP
ERP
 
Ba -content
Ba -contentBa -content
Ba -content
 
E commerce use case documentation.
E commerce use case documentation.E commerce use case documentation.
E commerce use case documentation.
 
MOM on activity diagram
MOM on activity diagramMOM on activity diagram
MOM on activity diagram
 
UML Diagrams
UML DiagramsUML Diagrams
UML Diagrams
 
MOM on BA
MOM on BAMOM on BA
MOM on BA
 
Constructors
Constructors Constructors
Constructors
 
array
array array
array
 
Use case for atm
Use case for atmUse case for atm
Use case for atm
 
Activity diagram for ticket vending machine
Activity diagram for ticket vending machineActivity diagram for ticket vending machine
Activity diagram for ticket vending machine
 
Extreme programming
Extreme programmingExtreme programming
Extreme programming
 
Agile model
Agile model Agile model
Agile model
 
Business Analyst
Business AnalystBusiness Analyst
Business Analyst
 
CRM and ERP
CRM and ERPCRM and ERP
CRM and ERP
 
Reflection
ReflectionReflection
Reflection
 
Exceptions in SQL Server
Exceptions in SQL ServerExceptions in SQL Server
Exceptions in SQL Server
 
Views
ViewsViews
Views
 
Triggers
TriggersTriggers
Triggers
 
Subqueries
SubqueriesSubqueries
Subqueries
 

KĂŒrzlich hochgeladen

Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 

KĂŒrzlich hochgeladen (20)

Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 

Generics collections

  • 2. Why do we need Generics?  Another method of software re-use.  When we implement an algorithm, we want to re-use it for different types.  Example: We write a generic method for sorting an array of objects, then call the generic method with an array of any type.  The compiler performs type checking to ensure that the array passed to the sorting method contains only elements of the same type.  Generics provide compile-time type safety.
  • 3. Generic Methods  Generic methods enable you to specify, with a single method declaration, a set of related methods.  Example: OverloadedMethods.cs ‱ Note that the array element type (int, double or char) appears only once in each method—in the method header. ‱ If we replace the element types in each method with a generic name then all three methods would look like follows: private static void DisplayArray( T[] inputArray ) { foreach ( T element in inputArray ) Console.Write( element + " " ); Console.WriteLine( "n" ); }  However, it will not compile, because its syntax is not correct.  GenericMethods.cs
  • 4. Generic Methods  All generic method declarations have a type-parameter list delimited by angle brackets that follows the method’s name.  Each type-parameter list contains one or more type parameters.  A type parameter is an identifier that is used in place of actual type names.  The type parameters can be used to declare the return type, the parameter types and the local variable types in a generic method declaration.  Type parameters act as placeholders for type arguments that represent the types of data that will be passed to the generic method.  A generic method’s body is declared like that of any other method.  The type-parameter names throughout the method declaration must match those declared in the type-parameter list.  A type parameter can be declared only once in the type-parameter list but can appear more than once in the method’s parameter list.  You can also use explicit type arguments to indicate the exact type that should be used to call a generic function, as in DisplayArray< int >( intArray );
  • 5. Generic Classes  A generic class describes a class in a type-independent manner.  We can then instantiate type-specific objects of the generic class.  Let’s look at example: Stack.sln  StackTest.cs: repeats code in TestPopInt/TestPopDouble and TestPushInt/TestPushDouble  How to fix this? Let’s code this together first.  NewStackTest.cs
  • 6. Generic Interfaces  In NewStackTest.cs, we used a generic interface: IEnumerable < T >  Similar to generic classes, generic interfaces enable you to specify, with a single interface declaration, a set of related interfaces.
  • 7. Common Data Structures - summary  We’ve seen Array only so far  fixed-size (can grow with Resize)  Dynamic data structures can automatically grow and shrink at execution time.  Linked lists are collections of data items that are “chained together”.  Stacks have insertions and deletions made at only one end: the top.  Queues represent waiting lines; insertions are made at the back and deletions are made from the front.  Binary trees facilitate high-speed searching and sorting of data.
  • 8. Collections  For the vast majority of applications, there is no need to build custom data structures.  Instead, you can use the prepackaged data-structure classes provided by the .NET Framework.  These classes are known as collection classes—they store collections of data. Each instance of one of these classes is a collection of items.  Collection classes enable programmers to store sets of items by using existing data structures, without concern for how they are implemented.  System.Collections contains collections that store references to objects.
  • 9. ArrayList  The ArrayList collection class is a conventional arrays and provides dynamic resizing of the collection. Method / Property Description Add Adds an object to the end of the ArrayList. Capacity Property that gets and sets the number of elements for which space is currently reserved in the ArrayList. Clear Removes all elements from the ArrayList. Contains Determines whether an element is in the ArrayList. Count Read-only property that gets the number of elements stored in the ArrayList. IndexOf Returns the zero-based index of the first occurrence of a value in the ArrayList Insert Inserts an element into the ArrayList at the specified index. Remove Removes the first occurrence of a specific object from the ArrayList. RemoveAt Removes the element at the specified index of the ArrayList. TrimToSize Sets the capacity to the actual number of elements in the ArrayList.
  • 10. ArrayList  Let’s write code to use ArrayList.  Suppose we have two color string arrays as follows: private static readonly string[] colors = { "MAGENTA", "RED", "WHITE", "BLUE", "CYAN" }; private static readonly string[] removeColors = { "RED", "WHITE", "BLUE" }; 1. Let’s create an arrayList and add items in colors into it. 2. Let’s display the size and capacity of arrayList. 3. Let’s find the index of the item “BLUE”. 4. Let’s write a method that removes the items in one ArrayList from another. And then call that method to remove removeColors array from our first arrayList. 5. ArrayListTest.cs
  • 11. Generic Collections Problems with Nongeneric Collections  Having to store data as object references causes less efficient code due to unboxing.  The .NET Framework also includes the System.Collections.Generic namespace, which uses C#’s generics capabilities.  Many of these new classes are simply generic counterparts of the classes in namespace System.Collections.  Generic collections eliminate the need for explicit type casts that decrease type safety and efficiency.  Generic collections are especially useful for storing structs, since they eliminate the overhead of boxing and unboxing.
  • 12. SortedDictionary<TKey, TValue>  A dictionary is the general term for a collection of key/value pairs.  A hash table is one way to implement a dictionary.  Example: Let’s write a program that counts the number of occurrences of each word in a string read from console using SortedDictionary.  To split the sentence into words, we will use this: // split input text into tokens string[] words = Regex.Split( input, @"s+" );  http://msdn.microsoft.com/en-us/library/xfhwa508.aspx  Members:  http://msdn.microsoft.com/en-us/library/3eayzh46.aspx
  • 13. Collection Interfaces  All collection classes in the .NET Framework implement some combination of the collection interfaces. Interface Description ICollection The root interface from which interfaces IList and IDictionary inherit. Contains a Count property to determine the size of a collection and a CopyTo method for copying a collection’s contents into a traditional array. IList An ordered collection that can be manipulated like an array. Provides an indexer for accessing elements with an int index. Also has methods for searching and modifying a collection, including Add, Remove, Contains and IndexOf. IEnumerable An object that can be enumerated. This interface contains exactly one method, GetEnumerator, which returns an IEnumerator object. ICollection implements IEnumerable, so all collection classes implement IEnumerable directly or indirectly. IDictionary A collection of values, indexed by an arbitrary “key” object. Provides an indexer for accessing elements with an object index and methods for modifying the collection (e.g., Add, Remove). IDictionary property Keys contains the objects used as indices, and property Values contains all the stored objects.
  • 14. HashTable  Arrays uses nonnegative integer indexes as keys. Sometimes associating these integer keys with objects to store them is impractical, so we develop a scheme for using arbitrary keys.  When an application needs to store something, the scheme could convert the application key rapidly to an index.  Once the application has a key for which it wants to retrieve the data, simply apply the conversion to the key to find the array index where the data resides.  The scheme we describe here is the basis of a technique called hashing, in which we store data in a data structure called a hash table.
  • 15. HashTable  A hash function performs a calculation that determines where to place data in the hash table.  The hash function is applied to the key in a key/value pair of objects.  Class Hashtable can accept any object as a key. For this reason, class object defines method GetHashCode, which all objects inherit.  Example: Let’s write a program that counts the number of occurrences of each word in a string read from console.  To split the sentence into words, we will use this: // split input text into tokens string[] words = Regex.Split( input, @"s+" );  HashTable solution.
  • 16. HashTable  Hashtable method ContainsKey determines whether a key is in the hash table.  Read-only property Keys returns an ICollection that contains all the keys.  Hashtable property Count returns the number of key/value pairs in the Hashtable.  If you use a foreach statement with a Hashtable object, the iteration variable will be of type DictionaryEntry.  The enumerator of a Hashtable (or any other class that implements IDictionary) uses the DictionaryEntry structure to store key/value pairs.  This structure provides properties Key and Value for retrieving the key and value of the current element.  If you do not need the key, class Hashtable also provides a read-only Values property that gets an ICollection of all the values stored in the Hashtable.
  • 17. Stack & Queue  Stack:  Push  Pop  Peek  Example:  StackTest.cs  Queue:  Enqueue  Dequeue  Peek  Exercise: re-write the StackTest.cs example at home using a Queue this time.
  • 18. Generic Collection Interfaces Interface Description ICollection(T) Defines methods to manipulate generic collections. IList(T) Represents a collection of objects that can be individually accessed by index. IEnumerable(T) Exposes the enumerator, which supports a simple iteration over a collection of a specified type. IEnumerator(T) Supports a simple iteration over a generic collection. IDictionary(TKey,TValue) Represents a generic collection of key/value pairs. IComparer(T) Defines a method that a type implements to compare two objects. http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx
  • 19. Other Generic Collection Classes  List(T)  Let’s re-write the ArrayListTest.cs using List<T> this time.  Stack(T)  Queue(T)  LinkedList(T)  SortedList(TKey, TValue)