Interfaces and Collections Chapter - 6
Objectives Interface – basic concepts How to implement Interfaces in C#? Difference between Interfaces and Abstract base Classes Interface References: 'is', 'as', etc. Interfaces as Parameters Interfaces and Polymorphism Building Customized Types IConvertible, IEnumerator, ICloneable, and IComparable, Interfaces System.Collections Interface ArrayList, Hashtable, Queue, SortedList, and Stack S. Nandagopalan, BIT
Part - I Interface – basic concepts How to implement Interfaces in C#? Difference between Interfaces and Abstract base Classes Interface References: 'is', 'as', etc. Interfaces as Parameters Interfaces and Polymorphism S. Nandagopalan, BIT
Interface – Basic Concepts Definition: An interface is nothing more than a named collection of semantically related abstract members Interface is to achieve polymorphism in another way Interfaces can have static members, nested types, and abstract, virtual members, properties, and events COM programmers lived only with interfaces, as the client can communicate only through interface pointers with COM classes (not through object references) Interfaces do not specify a base class, or access modifier, etc, but provide polymorphism Interfaces do not implement any methods S. Nandagopalan, BIT
Advantages of Interfaces So, what are interfaces good for if they don't implement functionality? They're great for putting together plug-n-play like architectures where components can be interchanged at will (example follows…). Since all interchangeable components implement the same interface, they can be used without any extra programming. The interface forces each component to expose specific public members that will be used in a certain way. S. Nandagopalan, BIT
Real World Example Interface3 Interface1 Interface2 USB S. Nandagopalan, BIT
Implementing an Interface A class that implements an interface can explicitly implement a member of that interface Interfaces may be implemented by classes and structures When a member is explicitly implemented, it can not be accessed through a class instance, but only through an instance of the interface public interface ISomeInterface { // Members….. } public class SomeClass : ISomeInterface // implementation details of the interface public class AnotherClass : BaseClass, ISomeInterface // derives from BaseClass and implents the interface S. Nandagopalan, BIT
Shapes Hierarchy Shapes Class Draw( ) Hexagon Circle Class Class Triangle Class Circle Class Hexagon Class Draw() Draw() Draw() S. Nandagopalan, BIT
Example-1 : Shapes Hierarchy public interface IPoints { byte GetNumberOfPoints( ); } public abstract class Shape protected string petName; // Constructors. public Shape(){petName = "NoName";} public Shape(string s) { this.petName = s; } // All child objects must define for themselves what // it means to be drawn. public abstract void Draw(); public string PetName get {return this.petName;} set {this.petName = value;} S. Nandagopalan, BIT
Circle SubClass The Circle subclass does not implement the interface IPoints! public class Circle : Shape { public Circle() { } // Call base class constructor. public Circle(string name): base(name) { } public override void Draw() Console.WriteLine("Drawing " + PetName + " Circle"); } S. Nandagopalan, BIT
Hexagon SubClass public class Hexagon : Shape, IPoints { public Hexagon(){} public Hexagon(string name): base(name){} public override void Draw() Console.WriteLine("Drawing " + PetName + "Hexagon"); } // Implements IPoints byte IPoints.GetNumberOfPoints() { return 6; } S. Nandagopalan, BIT
Example-1… public static int Main(string[] args) { Circle c = new Circle("Red"); c.Draw(); Hexagon h = new Hexagon("Blue"); h.Draw(); //IPoints MyShape = (IPoints) h; //Console.WriteLine(MyShape.GetNumberOfPoints()); Console.WriteLine(h.GetNumberOfPoints()); return 0; } ERROR S. Nandagopalan, BIT
Example - 2 Interfaces can contain named properties Person Example: public interface IAge { int Age {get; } string Name {get;} } S. Nandagopalan, BIT
Example – 2… class Person : IAge { private string firstName; private string lastname = "......"; private int yearBorn; public int Age get { return DateTime.Now.Year - yearBorn; } set { yearBorn = value; } } public string Name get { return firstName + " " + lastname; } set { firstName = value; } S. Nandagopalan, BIT
Example – 2… static void Main(string[] args) { Person p = new Person(); p.Name = "Geetha"; p.Age = 1986; Console.WriteLine("Name = {0}",p.Name); Console.WriteLine("Age = {0}",p.Age); IAge[ ] AgeArray = new IAge[2]; // ……….. } S. Nandagopalan, BIT
Example - 3 Explicit Interface Implementation public interface IDimensions { float Length(); float Width(); } class Box : IDimensions float lengthInches; float widthInches; public Box(float length, float width) lengthInches = length; widthInches = width; S. Nandagopalan, BIT
Example-3… // Explicit interface member implementation: float IDimensions.Length() { return lengthInches; } float IDimensions.Width() return widthInches; S. Nandagopalan, BIT
Example-3… public static void Main() { // Declare a class instance "myBox": Box myBox = new Box(30.0f, 20.0f); // Declare an interface instance "myDimensions": IDimensions myDimensions = (IDimensions) myBox; // Print out the dimensions of the box: /* The following commented lines would produce compilation errors because they try to access an explicitly implemented interface member from a class instance: */ //Console.WriteLine("Length: {0}", myBox.Length()); //Console.WriteLine("Width: {0}", myBox.Width()); /* Print out the dimensions of the box by calling the methods from an instance of the interface: */ Console.WriteLine("Length: {0}", myDimensions.Length()); Console.WriteLine("Width: {0}", myDimensions.Width()); } S. Nandagopalan, BIT
Interfaces Abstract base Classes Why do we need "interface"? Because C# allows abstract methods in base classes Abstract base classes permit more than the abstract methods – private, public, protected member data and methods which could be accessed in derived classes In Interfaces, you can't define other than abstract methods and implementations for them interface IPoints { byte GetNumberOfPoints() { } // ERROR } Interfaced programming provides another way of polymorphism S. Nandagopalan, BIT
Interface Reference through is & as Using "as" keyword, you can reference the interface members Hexagon h2 = new Hexagon(); IPoints ipts2; ipts2 = h2 as IPoints; Console.WriteLine(ipts2.GetNumberOfPoints()); ipts2 may be set to null if a given interface is not supported by the object You can also use "is" keyword if (h2 is IPoints) Console.WriteLine(ipts2.GetNumberOfPoints()); else ERROR S. Nandagopalan, BIT
Exercising the Shapes Hierarchy Shape[ ] s = {new Hexagon(), new Circle(), new Triangle("Joe"), new Circle("JoJo")}; for (int i = 0; i < s.Length; i++) { s[i].Draw(); // Who's points? if (s[i] is IPoints) Console.WriteLine("-> Points: {0}", ((IPoints)s[i]).GetNumberOfPoints()); else Console.WriteLine("-> {0}\'s not points!", s[i].PetName); } S. Nandagopalan, BIT
Interfaces as Parameters Methods can take interfaces as parameters Assume the following interface: public interface IDraw3D { void Draw3D(); } Now assume that the Circle subclass is revised to provide an additional implementation for IDraw3D public class Circle : Shape, IDraw3D // ………. public void Draw3D() { Console.WriteLine("Drawing a 3D Circle"); S. Nandagopalan, BIT
Interface as Parameter… The following method declares the interface as a parameter public static void DrawIn3D(IDraw3D int3D) { Console.WriteLine("Drawing in 3D:"); int3D.Draw3D(); } public static void Main() { …. if (s[i] is IDraw3D) DrawIn3D((IDraw3D)s[i]); ….. S. Nandagopalan, BIT
Explicit Implementation Issues Can we write like the one that follows? The answer is yes public interface IDraw3D { void Draw(); } Won't it clash with the overriding method as shown below: public class Line : Shape, IDraw3D public override void Draw() { Console.WriteLine("Drawing an ordinary line"); } public void IDraw3D.Draw() { Console.WriteLine("Drawing a 3D line"); } } // given interface method is bound at interface level. // Hence, public doesn't make any sense ERROR S. Nandagopalan, BIT
Part - II IConvertible IEnumerator and IEnumerable ICloneable Dynamic conversion of data types IEnumerator and IEnumerable Standard interface implemented by classes that support iteration over contained objects ICloneable To provide a standard way to create copies of existing objects IComparable and IComparer For oredering purpose (string and numeric) IDictionary To map keys to values – “Associative arrays” IList Access to individual items, removal, and insertion at any point S. Nandagopalan, BIT
IConvertible Interface Allows dynamic conversion of data types through interface based programming technique What are the methods defined in IConvertible Interface? public interface IConvertible { bool ToBoolean(IFormatProvider provider); char ToChar(IFormatProvider provider); …… UInt64 ToUInt64(IFormatProvider provider); } S. Nandagopalan, BIT
Accessing Members To gain access to each member of IConvertible interface, you must explicitly request access to the interface // uses explicit interface implementation bool myBoll = true; IConvertible i = (IConvertible) myBool; Now i is convertible to any valid type IConvertible.ToXXXX() Methods These methods provide a way to convert from one type into another (is it always?!!!) From char to DateTime possible? No If attempted, InvalidCastException will be raised S. Nandagopalan, BIT
using System.Globalization; Type Conversions Integer int theInt = 65; Console.WriteLine("Type code of int is: ",theInt.GetTypeCode()); Int to Char using Type Casting char theChar = (char)theInt; Console.WriteLine("Type code int converted to char is: {0}", theChar.GetTypeCode()); Console.WriteLine("Value of converted char: {0}", theChar); Int to Byte using IConvertible IConvertible itfConvert = (IConvertible)theInt; byte theByte = itfConvert.ToByte(CultureInfo.CurrentCulture); Console.WriteLine("Type code int converted to byte is: {0}", theByte.GetTypeCode()); Console.WriteLine("Value of converted int: {0}", theByte); using System.Globalization; S. Nandagopalan, BIT
Type Conversion… Convert a System.String into a System.Boolean using System.Convert string theString = "true"; bool theBool = Convert.ToBoolean(theString); Console.WriteLine("Type code string converted to bool is: {0}", theBool.GetTypeCode()); Console.WriteLine("Value of converted string: {0}", theBool); Add two integers int a = Convert.ToInt32(Console.ReadLine()); int b = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("a + b = {0}", a+b); S. Nandagopalan, BIT
Invalid Type Conversion // Exception bool myBool = true; IConvertible i = (IConvertible) myBool; try { DateTime t = i.ToDateTime(CultureInfo.CurrentCulture); } catch (InvalidCastException e) Console.WriteLine(e.Message); Objects that implement this interface are able to format their contents based on culture specific information Invalid type conversion S. Nandagopalan, BIT
Building a Custom Enumerator IEnumerable: Exposes the enumerator, which supports a simple iteration over a collection GetEnumerator(): Public method that returns an enumerator that can iterate through a collection Defined in System.Collections namespace IEnumerator: Supports a simple iteration over a collection MoveNext(): Public method which advances the enumerator to the next element of the collection There are several classes which implement IEnumerable and IEnumerator interfaces. For example, Array, ArrayList, Stack, Queue, etc. are the classes that implement IEnumerable interface S. Nandagopalan, BIT
Example – Car Class Cars class is a collection of Car objects using Array type public class Cars { // This class maintains an array of cars. private Car[ ] carArray; // Current position in array. // int pos = -1; public Cars() carArray = new Car[4]; carArray[0] = new Car("FeeFee", 200, 0); carArray[1] = new Car("Clunker", 90, 0); carArray[2] = new Car("Zippy", 30, 0); carArray[3] = new Car("Fred", 30, 0); } S. Nandagopalan, BIT
Iterating thro' the Collection Can we write the following code to iterate through the collection? public class CarDriver { public static void Main() Cars carLot = new Cars(); Console.WriteLine("Here are the cars in your lot"); foreach (Car c in carLot) Console.WriteLine("-> Name: {0}", c.PetName); Console.WriteLine("-> Max speed: {0}", c.MaxSpeed); Console.WriteLine(); } This code issues an error for not implementing the GetEnumerator() method S. Nandagopalan, BIT
Implementing GetEnumerator() To get around the problem of compilation error, we must use public class Cars : IEnumerable { …….. // GetEnumerator() returns IEnumerator public IEnumerator GetEnumerator() { // ??????? } } IEnumerable.GetEnumerator() returns an object implementing IEnumerator public interface IEnumerator bool MoveNext(); object Current { get; } void Reset(); S. Nandagopalan, BIT
Updating Cars Type public class Cars : IEnumerable, IEnumerator { …….. public IEnumerator GetEnumerator() return (IEnumerator) this; } S. Nandagopalan, BIT
Implementation of MoveNext()…. public bool MoveNext() { if(pos < carArray.Length) pos++; return true; } else return false; public void Reset() { pos = 0; } public object Current get return carArray[pos]; S. Nandagopalan, BIT
Advantages User types can be iterated through 'foreach' loop When the IEnumerator members are explicitly implemented, we provide an alternate method of accessing the objects in the container ……. Add some more points ……… S. Nandagopalan, BIT
Reducing the Code Size Since the System.Array type already implements IEnumerator, you need not add this interface to Cars class public class Cars : IEnumerable //, IEnumerator { private car[ ] carArray; …….. public IEnumerator GetEnumerator() return carArray.GetEnumerator( ); } With this, there is no need to implement manually MoveNext(), Reset(), etc. (refer ObjEnum folder) S. Nandagopalan, BIT
Building Cloneable Objects Implementing ICloneable interface using a Point Class Recall System.Object has a member MemberwiseClone() which does shallow copy Object users can call this method with an instance for cloning process Let us make things clear…… S. Nandagopalan, BIT
Example public class Point { public int x, y; public Point(){} public Point(int x, int y) { this.x = x; this.y = y; } public override string ToString() { return "X: " + x + " Y: " + y; } } The following piece of code makes two references pointing to the same copy of the objects in heap Point p1 = new Point(50, 50); Point p2 = p1; p2.x = 0; Notice that by modifying p2, the object p1 also gets modified. S. Nandagopalan, BIT
ICloneable Interface To avoid the shallow copy problem we must implement the ICloneable interface public interface ICloneable { object Clone(); } This means the Clone() method need to be redefined to suit the customer type. This ensures deep copy semantics public class Point : ICloneable ….. public object Clone() { return new Point(this.x, this.y); } …. S. Nandagopalan, BIT
Calling Clone() Method Point p1 = new Point(50, 50); // p2 will point to the copy of p1 Point p2 = (Point)p1.Clone(); p2.x = 0; // will not affect p1 Console.WriteLine(p1); Console.WriteLine(p2); The above WriteLine commands will print two different objects If a type does not contain references to other internal reference types, then we can write public object Clone() { return this.MemberwiseClone(); } What happens if the Point type contains references to other internal reference types? S. Nandagopalan, BIT
Building Comparable Objects Let us show how to implement IComparable interface Defines a generalized comparison method that a value type or class implements to create a type-specific comparison method CompareTo(object o) - Compares the current instance with another object of the same type public interface IComparable { int CompareTo(object o); } Recall, the System.Array class defines a method Sort() which sorts int, float, char, etc. However, if the array contains a set of Cars, it fails. Array.Sort(intArr); // OK Array.Sort(myCars); // ArgumentException will be thrown So the advantage of IComparable is to provide a way to sort your own types S. Nandagopalan, BIT
Example – Student Class public class Student : IComparable { private int USN; public Student() {USN = 0; } public Student(int USN) { this.USN = USN; } public int RegNo get { return USN; } } int IComparable.CompareTo(object o) Student temp = (Student) o; if(this.USN > temp.USN) return 1; if(this.USN < temp.USN) return -1; else return 0; CompareTo() return Value: < 0 : less than object 0 : equal to object > 0 : greater than object S. Nandagopalan, BIT
Sorting the Objects static void Main(string[] args) { Student[] cseStd = new Student[3]; cseStd[0] = new Student(111); cseStd[1] = new Student(100); cseStd[2] = new Student(45); try Array.Sort(cseStd); } catch(Exception e) Console.WriteLine(e.StackTrace); Console.WriteLine("Array after sorting"); foreach(Student s in cseStd) Console.WriteLine(s.RegNo); S. Nandagopalan, BIT
Sorting Order (IComparer) Suppose if you wish to sort the student objects based on USN and also Name – how do we solve this problem? This could be solved by using another interface called IComparer public interface IComparer { int Compare(object o1, object o2) } Recall, the IComparable interface was implemented using the type name (Student). But, IComparer is implemented using some helper classes, one for each sort order (USN, Name, etc). S. Nandagopalan, BIT
Modified Student Class using System.Collections; public class Student { public int USN; public string Name; public Student() {USN = 0; Name = null;} public Student(int USN, string Name) this.USN = USN; this.Name = Name; } public class SortName : IComparer // helper class public SortName() {} int Compare(object o1, object o2) Student s1 = (Student) o1; Student s2 = (Student) o2; return String.Compare(s1.Name, s2.Name); S. Nandagopalan, BIT
Using Multiple Sort Order System.Sort has a number of overloaded methods. One of them is to take an object implementing IComparer static void Main(string[] args) { Student[] cseStd = new Student[3]; cseStd[0] = new Student(111,"Scott"); cseStd[1] = new Student(100,"Allen"); cseStd[2] = new Student(45,"John"); try Array.Sort(cseStd, new SortName()); } catch(Exception e) Console.WriteLine(e.StackTrace); Console.WriteLine("Array after Sorting by Name:"); foreach(Student s in cseStd) Console.WriteLine(s.USN + " " + s.Name); S. Nandagopalan, BIT
Static Helper Class public static IComparer class SortName The helper classes may be static public static IComparer class SortName { …. } // Calling program Array.Sort(cseStd, Student.SortName()); S. Nandagopalan, BIT
System.Collections Namespace Sytem.Collections has many classes ArrayList Dynamic array of objects IList, ICollection, IEnumerable, & ICloneable Hashtable collection of objects identified by keys IDictionary, ICollection, IEnumerable, & ICloneable Queue FIFO ICollection, IEnumerable, & ICloneable SortedList Same as Dictionary, but accessed by index Stack LIFO ICollection and IEnumerable S. Nandagopalan, BIT
ArrayList Basics The ArrayList is not guaranteed to be sorted. You must sort the ArrayList prior to performing operations (such as BinarySearch) that require the ArrayList to be sorted. The capacity of a ArrayList is the number of elements the ArrayList can hold. The default initial capacity for an ArrayList is 0. As elements are added to a ArrayList, the capacity is automatically increased as required through reallocation. The capacity can be decreased by calling TrimToSize or by setting the Capacity property explicitly. Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based. ArrayList accepts a null reference as a valid value and allows duplicate elements. S. Nandagopalan, BIT
Example myAL Count: 3 Capacity: 16 Values: Hello World ! using System; using System.Collections; public class SamplesArrayList { public static void Main() { // Creates and initializes a new ArrayList. ArrayList myAL = new ArrayList(); myAL.Add("Hello"); myAL.Add("World"); myAL.Add("!"); // Displays the properties and values of the ArrayList. Console.Write( "myAL" ); Console.WriteLine( " Count: {0}", myAL.Count ); Console.WriteLine( " Capacity: {0}", myAL.Capacity ); Console.Write( " Values:" ); PrintValues( myAL ); } public static void PrintValues( IEnumerable myList ) foreach ( Object obj in myList ) Console.Write( " {0}", obj ); Console.WriteLine(); S. Nandagopalan, BIT
System.ArrayList AddRange() populates the array with Cars // Create ArrayList and fill with some initial values. Console.WriteLine("***** Fun with ArrayList *****"); ArrayList carArList = new ArrayList(); carArList.AddRange(new Car[ ] { new Car("Fred", 90, 10), new Car("Mary", 100, 50), new Car("MB", 190, 0)}); Console.WriteLine("Items in carArList: {0}", carArList.Count); // Print out current values. foreach(Car c in carArList) { Console.WriteLine("Car pet name: {0}", c.PetName); } S. Nandagopalan, BIT
System.ArrayList…. Index() is used to plug a new Car at any position/index // Insert a new item. Console.WriteLine("-> Inserting new item"); carArList.Insert(2, new Car("TheNewCar", 0, 0)); Console.WriteLine("Items in carArList: {0}", carArList.Count); // Get object array from ArrayList & print again. object[] arrayOfCars = carArList.ToArray(); for(int i = 0; i < arrayOfCars.Length; i++) { Console.WriteLine("Car pet name: {0}", ((Car)arrayOfCars[i]).PetName); } S. Nandagopalan, BIT
System.Collections.Queue Dequeue() – Delete and return first object from the Queue Enqueue() – Insert an object into the Queue Peek() – Return the first object without deleting Console.WriteLine("\n***** Queue Demo *****"); // Now make a Q with three items Queue carWashQ = new Queue(); carWashQ.Enqueue(new Car("FirstCar", 0, 0)); carWashQ.Enqueue(new Car("SecondCar", 0, 0)); carWashQ.Enqueue(new Car("ThirdCar", 0, 0)); // Peek at first car in Q Console.WriteLine("First in Q is {0}", ((Car)carWashQ.Peek()).PetName); S. Nandagopalan, BIT
System.Collections.Queue // Remove each item from Q WashCar((Car)carWashQ.Dequeue()); // Try to de-Q again? try { } catch(Exception e) { Console.WriteLine("Error!! {0}", e.Message);} S. Nandagopalan, BIT
System.Collections.Stack Stack stringStack = new Stack(); stringStack.Push("One"); stringStack.Push("Two"); stringStack.Push("Three"); // Now look at the top item. Console.WriteLine("Top item is: {0}", stringStack.Peek()); Console.WriteLine("Popped off {0}", stringStack.Pop()); try { } catch(Exception e) { Console.WriteLine("Error!! {0}\n", e.Message);} S. Nandagopalan, BIT
End of Chapter 6 S. Nandagopalan, BIT