Sei sulla pagina 1di 35

Module 10:

More About Classes

By

SRIRAM . B
Overview

 Collections
 Indexers
 Delegates
 Operator Overloading
Collections

 Collections are objects that can contain arrays of other objects and contain
functionality that controls access to these objects.

 Collection classes are generally used for maintains list of objects and may expose
additional functionality over arrays.

 This functionality comes through implementing interfaces from System.Collections


namespace.
Collections..

 There are number of interfaces in System.Collections namespace that provide


basic collection functionality :-

 IEnumerable – Provides the capability to loop through items of collection.

 ICollection – Provides ability to obtain the number of items in a collection, and


to copy in simple array type.

 IList – Provides list of items for collection as well as capability for accessing
these elements.
Types of Collections
Stack -> L I F O

Queue -> F I F O

ArrayList -> Array is whose size can increase and decrease dynamically. It can
hold items of different types. It can increase and decrease size dynamically you don't
have to use REDIM keyword . You can access any item in array using the INDEX
value of the array position.

Hashtable -> You can access array using INDEX value of array, but how many times
you know the real value of index. Hashtable provides way of accessing the index using
a user identified KEY value, thus removing the INDEX problem.

SortedArrayList ->It works like Arraylist in the sorted manner.


Collection Methods
 ArrayList
Argument :-
– ArrayList( ), ArrayList(int)
– Methods :-

– Count – Gets the number of elements actually contained in the list

– Add(Object) – Adds to the end of the list

– Clear() – Removes all elements

– Insert(int index, Object)

– Remove(Object) – removes first occurrence of the object

– GetEnumerator() returns IEnumerator

» -> Use MoveNext method and current property


Collection Methods
 Stack
– Push, pop, peek
 Queue
– Enqueue, Dequeue, peek
 Hashtable
– Key-value pairs
– Add(Object, Object) – Key and value
– Clear – removes all elements
– Remove(Object) – removes the element with the specified key
– GetEnumerator – returns IDictionaryEnumerator
» MoveNext, Key, Value
Example – Stack Collection
using System;
using System.Collections;
namespace Collections
{
class sampleStack
{
static void Main(string[] args)
{
Stack numbers = new Stack();

// fill the stack


foreach (int number in new int[4]
{ 9, 3, 7, 2 })
{
numbers.Push(number);
Console.WriteLine(number + " has been
pushed on the stack");
}
Example – Stack Collection..
// iterate through the stack
foreach (int number in numbers)
{
Console.WriteLine(number);
}

// empty the stack


while (numbers.Count != 0)
{
int number = (int)numbers.Pop();
Console.WriteLine(number + "has been
popped off the stack");
}

Console.ReadLine();

}
}
}
Example – Queue Collection
using System;
using System.Collections;
namespace Collections
{
class sampleQueue
{
static void Main(string[] args)
{
Queue numbers = new Queue();
// fill the queue
foreach (int number in new int[4]
{ 9, 3, 7, 2 })
{
numbers.Enqueue(number);
Console.WriteLine(number + " has
joined the queue");

}
Example – Queue Collection..

// iterate through the queue


foreach (int number in numbers)
{
Console.WriteLine(number);
}

// empty the queue


while (numbers.Count != 0)
{
int number =
(int)numbers.Dequeue();
Console.WriteLine(number + " has
left the queue");
}

Console.ReadLine();

}
}
}
Example - Hashtable
using System;
using System.Collections;
namespace Collections
{
class sampleHash
{
static void Main(string[] args)
{
Hashtable ages = new Hashtable();
// fill the SortedList
ages["John"] = 41;
ages["Diana"] = 42;
ages["James"] = 13;
ages["Francesca"] = 11;
Example - Hashtable
// iterate using a foreach statement
// the iterator generates a DictionaryEntry object
containing a key/value pair
foreach (DictionaryEntry element in ages)
{
string name = (string)element.Key;
int age = (int)element.Value;
Console.WriteLine("Name: {0}, Age: {1}", name,
age);
}
Console.ReadLine();

}
}
}
Example – Array List
using System;
using System.Collections;
namespace Collections
{
class arrayList2
{
static void Main(string[] args)
{
ArrayList numbers = new ArrayList();
// fill the ArrayList
foreach (int number in new int[12] { 10, 9,
8, 7, 7, 6, 5, 10, 4, 3, 2, 1 })
{
numbers.Add(number);
}
// remove first element whose value is 7
(the 4th element, index 3)
numbers.Remove(7);
// remove the element that's now the 7th
element, index 6 (10)
numbers.RemoveAt(6);
Example – Array List..
//iterate remaining 10 elements using a for
statement
for (int i = 0; i != numbers.Count; i++)
{
int number = (int)numbers[i];
// Notice the cast
Console.WriteLine(number);
}
// iterate remaining 10 using a foreach statement
foreach (int number in numbers)
// No cast needed
{
Console.WriteLine(number);
}
Console.ReadLine();

}
}
}
Example – Sorted List
using System;
using System.Collections;
namespace Collections
{
class sampleSortedList
{
static void Main(string[] args)
{
SortedList ages = new SortedList();
// fill the SortedList
ages["John"] = 39;
ages["Diana"] = 40;
ages["James"] = 12;
ages["Francesca"] = 10;
Example – Sorted List..

// iterate using a foreach statement

// the iterator generates a DictionaryEntry


object containing a key/value pair

foreach (DictionaryEntry element in ages)


{
string name = (string)element.Key;
int age = (int)element.Value;
Console.WriteLine("Name: {0}, Age:
{1}", name, age);
}
Console.ReadLine();

}
}
}
Indexers
 You can use an indexer to access members of a class as if it was an array.

 Indexers are nameless and use a reserved word this for implementation.

 Indexers include indexing parameters between square brackets.

 To read and write values, the get and set accessors are used.

 The signature of an indexer is used as a means of identification, which consists of a


number and the type of the indexer’s formal parameters.
Indexers..
 An indexer is a member that enables an object to be indexed in the same way as
an array.

 Example :-

– public string []s2 = new String[3];

– public string this[int ind] {

– get {return s2[ind];}

– set {s2[ind] = value;} }

– obj[0] = “test”

– Console.WriteLine(“{0}”, obj[0]);
Indexers..
 Array & Indexers

 Both use array notation

 Indexers can use non-integer subscripts and atleast one subscript should be
provided

 Indexers can be overloaded – define several indexers, each using a different


index type

 They are not variables, so cannot be passed to methods

 Indexers cannot be static

 Can be passed more than one parameter to the indexer (mainly used for 2D
array)
Example – Indexers
public class Index
{
public static void Main()
{
//Create a new IndexTest object a
IndexTest a = new IndexTest();

//Print the value of a


System.Console.WriteLine(a[1]);
}
}
Example – Indexers..

public class IndexTest


{
return 25;
}
}
}
Delegates

 Delegates are reference types that derive from the common base class:
System.Delegate.

 An instance of delegate encapsulates a method, which can be called.

 A delegate is independent of the object that it references.

 The signature of the method should match the delegate’s signature.

 Delegates are declared using the following syntax:

public delegate void SimpleDelegate();

Declares a delegate named SimpleDelegate that takes no argument and


returns a void.
Delegates..
 Equivalent to function pointers

 Allows a method to be called indirectly

 It contains a reference to a method

 All methods invoked by the same delegate must have the same parameters and
return value

 To use a delegate

– First define it and then instantiate it


Delegates..

 Defining
– public delegate void mydelegate( );
– Defines a delegate for methods that return no value and takes no
parameters
 Instantiating
– After defining it instantiate it and refer to a method
– myclass ed1 = new myclass( );
– mydelegate callback = new mydelegate (ed1.method);
 To call a Delegate
callback();
Example - Delegates
class DelegateTest
{ static void func()
{ //Static method

System.Console.WriteLine(“DelegateTest.func”
);
}
static void Main(){
//Static method on the class
//Instantiation
SimpleDelegate d = new
SimpleDelegate(func);
// Invocation
d();
} }
Operator Overloading
 Overloading operators that act upon objects

 All are public static methods

 These method names are operatorop where op specifies exactly which operator is
being overloaded. Ex: operator+

 All arithmetic operators return an instance of the class and manipulate objects of
the same class.
Operator Overloading..
 Relational operators

 must be paired

 If you overload > then you should overload <

 >= and <=, = = and !=

 If you overload = = and != operators, then you should override the Equals method,
such that if both returns true in a same situation

 GetHashCode to be overloaded along with Equals method


Operator Overloading..
 Same operator can be overloaded multiple times.
 public static Time operator+(Time t1, int hours)
 public static Time operator+(Time t1, float hours)
Example – Operator Overloading
using System;
namespace _10thLesson
{
public class Complex
{
public int real = 0;
public int imaginary = 0;

public Complex(int real, int imaginary)


{
this.real = real;
this.imaginary = imaginary;
}

public static Complex operator +(Complex


c1, Complex c2)
{
return new Complex(c1.real + c2.real,
c1.imaginary + c2.imaginary);
}
Example – Operator Overloading..
public static Complex operator *(Complex c1,
Complex c2)
{
return new Complex((c1.real * c2.real -
c1.imaginary * c2.imaginary), (c1.real *
c2.imaginary + c1.imaginary * c2.real));

}
static void Main(string[] ar)
{
Complex num1 = new Complex(5, 6);
Complex num2 = new Complex(2, 4);
Complex sum = num1 + num2;
Complex prod = num1 * num2;
Example – Operator Overloading..
Console.WriteLine("Number1 = {0} + {1}i",
num1.real, num1.imaginary);
Console.WriteLine("Number2 = {0} + {1}i",
num2.real, num2.imaginary);
Console.WriteLine("Sum = {0} + {1}i",
sum.real, sum.imaginary);
Console.WriteLine("Product = {0} + {1}i",
prod.real, prod.imaginary);
Console.ReadLine();
}
}
}
Session Ends
Exercise
Relax

Potrebbero piacerti anche