Professional Documents
Culture Documents
Unit 5 Delegates, Collection Classes
Unit 5 Delegates, Collection Classes
In C#, delegates are first-class objects, fully supported by the language. Technically, a
delegate is a reference type used to encapsulate a method with a specific signature and
return type. You can encapsulate any matching method in that delegate. (In C++ and
many other languages, you can accomplish this requirement with function pointers and
pointers to member functions. Unlike function pointers, delegates are object-oriented
and type-safe.)
A delegate is created with the delegate keyword, followed by a return type and the
signature of the methods that can be delegated to it, as in the following:
This declaration defines a delegate named WhichIsFirst, which will encapsulate any
method that takes two objects as parameters and returns an int.
Once the delegate is defined, you can encapsulate a member method with that delegate
by
instantiating the delegate, i.e., passing in a method that matches the return type and
signature.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace delegateeg
{
public delegate int DelegatSample(int a,int b);
}
}
}
}
Types of Delegates
• Single Delegate
• Multicast Delegate
• Generic Delegate
Single Delegate
• Multicast Delegate
Delegate objects can be composed using the "+" operator. A composed delegate calls
the two delegates it was composed from. Only delegates of the same type can be
composed. The "-" operator can be used to remove a component delegate from a
composed delegate.
Generic Delegate
A generic delegate can be defined the same way as a delegate but using generic type
parameters or return type. The generic type must be specified when you set a target
method.
using System;
using System. Collections. Generic;
using System.Linq;
using System.Text;
namespace genericdelegateeg
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(sum(10, 20));
Console.WriteLine(conct("Hello","World!!"));
Console.ReadLine();
}
C# - Anonymous Method
As the name suggests, an anonymous method is a method without a name.
Anonymous methods in C# can be defined using the delegate keyword and can be
assigned to a variable of delegate type.
using System;
using System.Collections. Generic;
using System.Linq;
using System.Text;
namespace anonymouseg
{
print(100);
}
}
}
❖ Collections
The Non-Generic Collection Classes
Non-generic
Collections Usage
ArrayList ArrayList stores objects of any type like an array. However, there is no
need to specify the size of the ArrayList like with an array as it grows
automatically.
SortedList SortedList stores key and value pairs. It automatically arranges elements
in ascending order of key by default. C# includes both, generic and non-
generic SortedList collection.
Stack Stack stores the values in LIFO style (Last In First Out). It provides a
Push() method to add a value and Pop() & Peek() methods to retrieve
values. C# includes both, generic and non-generic Stack.
Queue Queue stores the values in FIFO style (First In First Out). It keeps the
order in which the values were added. It provides an Enqueue() method to
add values and a Dequeue() method to retrieve values from the collection.
C# includes generic and non-generic Queue.
Hashtable Hashtable stores key and value pairs. It retrieves the values by comparing
the hash value of the keys.
Now that you are familiar with the non-generic collection interfaces, we can examine the
standard classes that implement them. With the exception of BitArray, described later,
the
non-generic collection classes are summarized here:
ArrayList
ArrayList implements the IList interface using an array whose size is dynamically
increased as required. In this article I explain how to create the ArrayList and the
various methods and properties of the ArrayList.
Property Description
Capacity Gets or sets the number of elements that the ArrayList can
contain.
IsFixedSize Gets a value indicating whether the ArrayList has a fixed size.
Method Description
RemoveAt() Removes the element at the specified index from the ArrayList.
namespace ArrayList1
{
class Program
{
static void Main(string[] args)
{
ArrayList arr = new ArrayList();
arr.Add("Sunday");
arr.Add("Monday");
arr.Add("Tuesday");
arr.Add("Wednesday");
arr.Add("Thusday");
arr.Add("Friday");
arr.Add("Saturday");
Console.WriteLine("The elements of the ArrayList are:");
foreach (object obj in arr)
{
Console.WriteLine(obj);
}
}
}
}
Hashtable
The Hashtable class represents a collection of key-and-value pairs that are organized
based on the hash code of the key. It uses the key to access the elements in the
collection.
A hash table is used when you need to access elements by using key, and you can
identify a useful key value. Each item in the hash table has a key/value pair. The key is
used to access the items in the collection.
using System;
using System.Collections;
namespace CollectionsApplication {
class Program {
if (ht.ContainsValue("Nuha Ali")) {
Console.WriteLine("This student name is already in the list");
} else {
ht.Add("008", "Nuha Ali");
}
// Get a collection of the keys.
ICollection key = ht.Keys;
Stack
It represents a last-in, first out collection of object. It is used when you need a last-in,
first-out access of items. When you add an item in the list, it is called pushing the item
and when you remove it, it is called popping the item.
Property Usage
Method Usage
Pop Removes and returns items from the top of the stack.
using System;
using System.Collections;
class Program
{
static Stack GetStack()
{
Stack stack = new Stack();
stack.Push(100);
stack.Push(1000);
stack.Push(10000);
return stack;
}
Property Usage
Method Usage
Dequeue Removes and returns an item from the beginning of the queue.
TrimToSize Sets the capacity of the queue to the actual number of items in the queue.
using System;
using System.Collections;
class Program
{
static void Main()
{
// New Queue of integers.
Queue q = new Queue ();
Queue<T> Queue<T> stores the values in FIFO style (First In First Out).
It keeps the order in which the values were added. It provides
an Enqueue() method to add values and a Dequeue() method
to retrieve values from the collection.
C# List<T> -
C# List<T> class is used to store and fetch elements. It can have duplicate elements. It
is found in System.Collections.Generic namespace.
using System;
using System.Collections.Generic;
C# HashSet<T>
C# HashSet class can be used to store, remove or view elements. It does not store
duplicate elements. It is suggested to use HashSet class if you have to store only unique
elements. It is found in System.Collections.Generic namespace.
using System;
using System.Collections.Generic;
C# SortedSet<T>
using System;
using System.Collections.Generic;
C# Stack<T>
C# Stack<T> class is used to push and pop elements. It uses the concept of Stack that
arranges elements in LIFO (Last In First Out) order. It can have duplicate elements. It is
found in System.Collections.Generic namespace.
using System;
using System.Collections.Generic;
}
}
C# Queue<T>
C# Queue<T> class is used to Enqueue and Dequeue elements. It uses the concept of
Queue that arranges elements in FIFO (First In First Out) order. It can have duplicate
elements. It is found in System.Collections.Generic namespace.
using System;
using System.Collections.Generic;
C# LinkedList<T>
C# LinkedList<T> class uses the concept of linked list. It allows us to insert and delete
elements fastly. It can have duplicate elements. It is found in
System.Collections.Generic namespace.
It allows us to add and remove element at before or last index.
using System;
using System.Collections.Generic;
Example 1:
class MyClass<T>
{
public T myVar;
public void SetVar(T var)
{
myVar = var;
}
public void getVar()
{
Console.WriteLine("Variable Type = {0} and Value = {1}
",typeof(T).ToString(),myVar);
}
}
class Example
{
static void Main(string[] args)
{
MyClass<int> ob = new MyClass<int>();
ob.SetVar(10);
ob.getVar();
Example 2:
class MyGenericClass<T>
{
private T genericMemberVariable;
return genericMemberVariable;
}
Example 2:
Usage:
Code Snippet:
/// <summary>
/// Helps to create generic class
/// </summary>
public class GenericTupleOfTwo<T1, T2>
{
private T1 first;
private T2 second;
public T1 First
{
get { return first; }
set { first = value; }
}
public T2 Second
{
get { return second; }
set { second = value; }
}
public GenericTupleOfTwo()
{
}
public GenericTupleOfTwo(T1 first, T2 second)
{
this.First = first;
this.Second = second;
}
}
❖ Working with Generic Collection Classes.
HashSet<T>
HashSet<T> supports a collection that implements a set. It uses a hash table for
storage. HashSet<T> implements a set in which all elements are unique. In other
words, duplicates are not allowed. The order of the elements is not specified. This makes
HashSet the perfect choice for working with sets of objects when order does not matter.
HashSet is a dynamic collection that grows as needed to accommodate the elements it
must store.
Here are four commonly used constructors defined by HashSet:
public HashSet( )
public HashSet(IEnumerable collection)
Stack<T> is the generic equivalent of the non-generic Stack class. Stack<T> supports a
first-in, last-out stack. Stack is a dynamic collection that grows as needed to
accommodate the elements it must store. It defines the following constructors:
public Stack( )
public Stack(int capacity)
public Stack(IEnumerable collection)
class GenStackDemo {
static void Main() {
Stack st = new Stack();
st.Push("One");
st.Push("Two");
st.Push("Three");
st.Push("Four");
st.Push("Five");
while(st.Count > 0) {
string str = st.Pop();
Console.Write(str + " ");
}
Console.WriteLine();
}
}
Queue is the generic equivalent of the non-generic Queue class. It supports a first-in,
first-out list Queue<T> is a dynamic collection that grows as needed to accommodate
the elements it must store.
It defines the following constructors:
public Queue( )
public Queue(int capacity)
public Queue(IEnumerable collection)
class GenQueueDemo {
static void Main() {
Queue q = new Queue();
q.Enqueue(98.6);
q.Enqueue(212.0);
q.Enqueue(32.0);
q.Enqueue(3.1416);
double sum = 0.0;
Console.Write("Queue contents: ");
while(q.Count > 0) {
double val = q.Dequeue();
Console.Write(val + " ");
sum += val;
}
Console.WriteLine("\nTotal is " + sum);
}
}
public SortedList( )
public SortedList(IDictionary dictionary)
public SortedList(int capacity)
// Demonstrate a SortedList.
using System;
using System.Collections.Generic;
class GenSLDemo {
static void Main() {
// Create a SortedList for
// employee names and salary.
SortedList<string,double> sl = new SortedList<string,double>();
// Add elements to the collection.
sl.Add("Butler, John", 73000);
sl.Add("Swartz, Sarah", 59000);
sl.Add("Pyke, Thomas", 45000);
sl.Add("Frank, Ed", 99000);
// Get a collection of the keys.
ICollection c = sl.Keys;
// Use the keys to obtain the values.
foreach(string str in c)
Console.WriteLine("{0}, Salary: {1:C}", str, sl[str]);
Console.WriteLine();
}
}