Inheritance and More C#

parkmooseupvalleySoftware and s/w Development

Jul 5, 2012 (5 years and 4 months ago)

522 views

Växjö universitet
Inheritance and More C#
Lecture 4 and 5!
http://www.msi.vxu.se/users/jonasl/da3033
Dr Jonas Lundberg,oce B3024
Jonas.Lundberg@vxu.se
23 september 2009
The Software Technology Group
Inheritance and More C#1(44)
Växjö universitet
Agenda
Inheritance in C#(Lecture 4)
I
Inheritance in C#
I
The class Object
I
The Uniform Type System
I
Boxing
I
Parameter passing
More C#!(Lecture 5)
I
Exceptions
I
File IO
I
Predened Collection Classes
I
Generics
The Software Technology Group
Inheritance and More C#2(44)
Växjö universitet
OO Design { Inheritance
I
Designing an OO system ) identify suitable classes to model the system.
I
A class describes (models) an abstraction of a real-world entity.
I
A class consists of properties and behavior
I
Example:
class Person:
//Properties//Behavior
string name SetName(string n)
int length SetLength(int l)
int weight SetWeight(int w)
I
However,many classes (e.g.
Person,Employee,Student,Teacher,Customer) may be very
similar and have many properties (conceptual and implementation) in
common.
I
Inheritance is a fundamental OO technique for organizing and creating
groups of of classes that have many properties in common.
Inheritance The Software Technology Group
Inheritance and More C#3(44)
Växjö universitet
The Shape Hierarchy
A simple hierarchy of graphical objects
<<abstract>>
Shape
int x_posint y_posvoid Move(int x, int y)double GetArea()void Print()
double heightdouble widthdouble GetArea()void Print()
Rectangle
Triangle
double heightdouble width
Circle
double radiusdouble GetArea()
double GetArea()void Print()
void Print()
The above type of diagrams is called UML (Unied Modelling Language) diagrams.
A!B means A inherits from B.
Inheritance The Software Technology Group
Inheritance and More C#4(44)
Växjö universitet
Implementing Shape
public abstract class Shape {//An abstract base class
protected int x;//x-position
protected int y;//y-position
public Shape(int x_pos,int y_pos) {x = x_pos;y = y_pos;}
public void Move(int x_pos,int y_pos) {x = x_pos;y = y_pos;}
public abstract double GetArea();//Abstract methods
public abstract void Print();
}
public class Rectangle:Shape {
private double h;
private double w;
public Rectangle(int x_pos,int y_pos,double height,double width)
:base(x_pos,y_pos) {
h = height;w = width;
}
public override double GetArea() { return h * w;}
public override void Print() {
Console.WriteLine("Rectangle:h = {0},w = {1}",h,w);
}
}
Inheritance The Software Technology Group
Inheritance and More C#5(44)
Växjö universitet
Shape (cont.)
Shape[] shapes = new Shape[3];
shapes[0] = new Rectangle(0,0,5,7);
shapes[1] = new Triangle(0,0,5,7);
shapes[2] = new Circle(0,0,5);
for (int i=0;i<shapes.Length;i++) {
Shape s = shapes[i];
s.Move(i,i);//Defined in Shape
s.Print();//Subclass specific
Console.WriteLine("Area:"+ s.GetArea());
}
Notice
I
A Rectangle can be assigned to Shape variable
)a Rectangle is a Shape
Terminology
I
Shape is a superclass (or base class) of Rectangle.
I
Rectangle is a subclass of (or derived from) Shape.
I
Also,parent (Shape) and child (Rectangle).
Inheritance The Software Technology Group
Inheritance and More C#6(44)
Växjö universitet
Why Inheritance?
I
Code Reuse:Because a child class can inherit behavior from a parent
class,the code does not need to be rewritten for the child.
I
Concept Reuse:This occurs when a child class overrides behavior dened
in a parent.Although no code is shared,the child and the parent share
the denition of the method.
I
Organization:Grouping entities into categories simplies the
understanding of a complex system.
I
Exploit Commonalities:We can in certain cases treat dierent objects
uniformly.
I
Extendability:It is often simple to add a new entity to a class hierachy
(e.g.,add Puma or Beaver to the Animal hierarchy).
Design Rule
The simple is-a test can be used to decide whether two concepts can be
linked by an inheritance relation.
I
A bird is an animal
I
A Rectangle is a GraphicalObject
Inheritance The Software Technology Group
Inheritance and More C#7(44)
Växjö universitet
Inheritance in C#
I
A class may only be derived from a single superclass (or base class).
(The same as in Java.C++ allows multiple inheritance.)
I
A class may implement multiple interfaces.
I
Example
class A {...}
interface I1 {...}
interface I2 {...}
class B:A,I1,I2 {...}//extends A,implements I1 and I2
I
The class (A) must be given before the interfaces (I1,I2)
I
Structs can not inherit from another type
Inheritance in C#The Software Technology Group
Inheritance and More C#8(44)
Växjö universitet
The operators is and as
Run-time Type Checks
v is C returns true if the object referenced by v is of class C or a subclass of
C.
A a = new C()
class A {...} if (a is C) {...}//true
class B:A {...} if (a is B) {...}//true
class C:B {...} if (a is A) {...}//warning since always true
a = null;if (a is C) {...}//false
Soft Type Casts v as C performs the cast (C) v if possible,returns null
otherwise.
A a = new B()
class A {...} B b = a as B;//OK!,cast applied
class B:A {...} C c = a as C;//No cast possible,c = null
class C:B {...} c = (C) a//Cast fails at run-time,error!
a = null;c = a as C;//c = null
Inheritance in C#The Software Technology Group
Inheritance and More C#9(44)
Växjö universitet
Accessing base class data
I
Members declared as protected can be accessed by derived classes.
)private is still private to any other class.
I
Example:The two elds in Person can be directly accessed by the
subclass Student.
public class Person {
protected string n;//name
protected int a;//age
....
}
public class Student:Person {
protected string id;//student id
public Student(string name,int age,string studentID) {
n = name;a = age;id = studentID;
}
}
Inheritance in C#The Software Technology Group
Inheritance and More C#10(44)
Växjö universitet
Constructors and Inheritance
public class Person {
public Person(string name,int age) { n = name;a = age;}
}
public class Student:Person {
public Student(string name,int age,string sID) {
n = name;a = age;id = sID;//Accessing
}//superclass fields
}
I
The above scenario would produce a compile error
No overload for method'Person'takes'0'arguments
I
Two options:
1.Insert a zero-parameter (default) constructor in the base class
2.Explicitely call the base class constructor
public Student(string name,int age,string sID):base(name,age) {
id = sID;//|
}//notice ---------------|
Inheritance in C#The Software Technology Group
Inheritance and More C#11(44)
Växjö universitet
Polymorphism
I
The word polymorphism comes from the Greek for"many forms".
I
Polymorphic call:a call a.m(...) with many possible target methods m.
I
Example
class A { A[] array = new A[3];
public void m() {...} array[0] = new A();
} array[1] = new B();
class B:A { array[2] = new C();
public void m() {...} foreach (A a in array)
} a.m();//Which method is called?
class C;A {
public void m() {...}
}
I
dispatch:the process of binding a call a.m(..) to a concrete target method m.
Polymorphism in C#The Software Technology Group
Inheritance and More C#12(44)
Växjö universitet
Static or Dynamic Dispatch
A variable has a xed static type (the declared type)
and a variable dynamic type (the current value type)
a:static type a:dynamic type
class A {...} A a = new A();A A
class B:A {...} a = new B();A B
class C:B {...} a = new C();A C
I
Static dispatch
I
A call a.m(...) is resolved using the static type of a
I
)dispatch takes place at compile time
I
Dynamic dispatch
I
A call a.m(...) is resolved using the dynaimc type of a
I
)dispatch takes place at run-time
I
dynamic dispatch ) more work at run-time ) slower execution
I
Java uses dynamic dispatch
I
C#uses both dynamic and static dispatch
I
Static or dynamic depends on how the methods are declared
I
Keyword virtual ) dynamic dispatch
Polymorphism in C#The Software Technology Group
Inheritance and More C#13(44)
Växjö universitet
Static or Dynamic Binding
dynamic binding
class A {
virtual void m() {...}//virtual ==> dynamic dispatch
}
class B:A {
override void m() {...}//overrides A.m()
}
A a = new B();//a:dynamic type B
a.m();//resolved using current type B ==> calls B.m(),
static binding
class A {
void m() {...}//non-virtual ==> static dispatch
}
class B:A {
new void m() {...}
}
A a = new B();//a:static type A
a.m();//resolved using declared type A ==> calls A.m(),
Polymorphism in C#The Software Technology Group
Inheritance and More C#14(44)
Växjö universitet
Inheritance related Keywords
I
Members (methods,properties,and indexers) with identical signatures
can hide or override each other.
I
Two members have identical signatures if they have the same name and:
I
same number and type of parameters (return type)
I
same visibility (public,private,protected)
I
static/dynamic dispatch depends on the method modiers
I
virtual:dynamic dispatch,can be overridden
I
override:overrides virtual
I
new:hides but doesn't override
I
abstract:no implementation,implies virtual
I
sealed:can't be changed in subtype,as final in Java
I
virtual ) dynamic binding
) call target decided at run-time using the dynamic type
I
non-virtual ) static binding
) call target decided at compile-time using the static type
I
The dispatch rules are much more complex in C#than in Java
I
virtual with override in sub-classes
) ordinary dynamic binding (as in Java)
I
new terminates the"line of overriding methods
) it hides any sub-class implementations
Polymorphism in C#The Software Technology Group
Inheritance and More C#15(44)
Växjö universitet
Mixing new and override
public class A { Testing
public virtual void print() {...} =======
public virtual void write() {...} A c = new C();
public virtual void skriv() {...} c.print();//--> C.print()
} c.write();//--> B.write(),
public class B:A {//stopped by C.write()
public override void print() {...} c.skriv();//--> A.skriv(),
public override void write() {...}//stopped by B.skriv()
public new virtual void skriv() {...}
}
public class C:B {
public override void print() {}
public new void write() {}
public override void skriv() {}
}
Conclusion:Mixing new with virtual/override produces tricky code
) try to avoid it.
Polymorphism in C#The Software Technology Group
Inheritance and More C#16(44)
Växjö universitet
Abstract Classes and Interfaces
Abstract Classes
I
An abstract method has no implementation and is always virtual
I
If a class has an abstract method,it must be declared abstract itself
I
One cannot create objects of abstract classes
Interfaces
I
interface ) purely abstract class,only signatures,no implementation
I
Interface members (methods,properties,indexers) are:
I
implicitely public abstract (virtual)
I
never static
I
Classes and structs may implement multiple interfaces
I
Interfaces can extend multiple interfaces
Polymorphism in C#The Software Technology Group
Inheritance and More C#17(44)
Växjö universitet
The Uniform C#Type System
Types
Value types Reference types
DelegatesArrays InterfacesClassesPrimitive types Enumerations Structs
I
Value types are stored on the stack,value variables stores a\copy"of a value.
I
Reference types are stored on the heap,reference variables stores the address to
an object on the heap.
I
Notice:All (also primitive) types inherit from System.Object.
class Point { class Point:Object {
int x;<----> int x;
int y;equals int y;
........
} }
The Uniform Type System The Software Technology Group
Inheritance and More C#18(44)
Växjö universitet
The Object Class
All (also primitive) types inherit from System.Object
) the Object members are common,and can be applied,on all values.
I
bool Equals(Object other):Determine whether two instances are equal,
i.e.,refer to the same object or have equal primitive values.
Used in many scenarios (e.g.,data structures) to determine equality.
I
int GetHashCode():Returns a hash number for this object.
(Used in data structures based on hashing,e.g.,
System.Collections.Hashtable.)
I
Type GetType():Gets the Type of the current instance.
(The Type object exposes the metadata associated with the class of the current
Object.)
I
string ToString():Returns a string representing the current Object.
Usually the value for primitive types and the type name for reference types.
(Used to generate a string in Console.WriteLine(Object o).)
I
Object MemberwiseClone():Protected method generating a shallow copy of
the current Object.
shallow ) new instance with equal eld values.
These members are all virtual and often overridden in other classes.
The Object Class The Software Technology Group
Inheritance and More C#19(44)
Växjö universitet
Example:Using Object Members
string s ="Jonas";
Console.WriteLine(s);//Jonas,uses ToString()
Console.WriteLine(s.GetHashCode());//-117955272
Console.WriteLine(s.GetType().ToString());//System.String,
//ToString() can be dropped
Console.WriteLine(s.Equals("Jonas"));//True,overridden in String
int[] a = new int[5];
Console.WriteLine(a);//System.Int32[],uses ToString()
Console.WriteLine(a.GetHashCode());//58225482
Console.WriteLine(a.GetType().ToString());//System.Int32[],
//ToString() can be dropped
Console.WriteLine(a.Equals(new int[5]));//False
The Object Class The Software Technology Group
Inheritance and More C#20(44)
Växjö universitet
Example:Overriding Object Members
class Point {
int x;
int y;
public Point(int x,int y) { this.x = x;this.y = y;}
public override string ToString() { return"("+x+","+y+")";}
public override bool Equals(object obj) {
if (obj is Point) {
Point other = (Point)obj;
return x == other.x && y == other.y;
} else
return false;
}
public override int GetHashCode() { return x ^ y;//bitwise XOR }
}
The Object Class The Software Technology Group
Inheritance and More C#21(44)
Växjö universitet
Boxing and Unboxing
I
Strange (but legal) assignments
object o = 7;//reference to a value?
int a = (int) o;//object to integer conversion?
I
The primitive to object conversion is called boxing/unboxing.
I
Examples of boxing
int a = 3;ArrayList list = new ArrayList();
object obj = a;list.add(3);
I
The value 3 is wrapped in a temporary object (of type System.Int32))
and placed on the heap.Variable obj stores the address to that object.
I
Examples of unboxing
a = (int) obj;a = (int) list[i];
I
The object is unwrapped from the temporary object and converted to an
int.
I
The temporary object is garbage collected in the usual way.
I
Result:
I
Uniform treatment of primitive and reference types.
I
We can store primitive types in the collection classes.
Boxing The Software Technology Group
Inheritance and More C#22(44)
Växjö universitet
Ordinary Method Calls
Call-by-value:target receives a copy of the argument value
A a = new A();public class A {
int x = 7;public void m(int p) {...}
a.m(x);}
Call-by-reference:target receives a reference to the argument object
A a = new A();public class A {
B b = new B();public void m(B p) {...}
a.m(b);}
Notice:Variable b and method m(B p) holds a reference to the same object
) changes of the object within m(B p) might aect further use
of variable a (aliasing)
) be careful
Boxing The Software Technology Group
Inheritance and More C#23(44)
Växjö universitet
Call Parameters (CallParams.cs)
public struct Pair {
int X,Y;
public Pair(int x,int y) {X = x;Y = y;}
public void getPair(out int x,out int y) {x = X;y = Y;}
public static void addOne(ref int x,ref int y) {
Console.WriteLine("x-Type:"+ x.GetType().FullName);
x++;y++;
}
}
Usage:
Pair p = new Pair(5,5);
int a = 1,b = 2;
p.getPair(out a,out b);//a = 5,b = 5
Pair.addOne(ref a,ref b);//a = 6,b = 6
Console.WriteLine("a = {0},b = {1}",a,b);
Generated output
x-Type:System.Int32
a = 6,b = 6
Boxing The Software Technology Group
Inheritance and More C#24(44)
Växjö universitet
Parameters
I
C#has dierent kinds of parameters for values
I
Value parameters (default)
void Inc(int n) {n = n +1;} int val = 3;
Inc(val);//val is still 3
I
Reference parameters (uses boxing)
void Inc(ref int n) {n = n +1;} int val = 3;
Inc(ref val);//val is now 4
Converts argument value 3 to a System.Int32 which gets updated and returned
) val must have a value before the call.
I
Out parameters (uses boxing)
void Add(out int sum,params int[] val) { Usage:
sum = 0;int s;
foreach(int i in val) sum += i;Add(out s,1,2,3,4,5);
}//s is 15
Assigns the variable s a value during the call ) previous s value irrelevant.
I
Notice:the declaration params int[] makes it possible to use a variable
number of parameters.The declarations out and ref make it possible to receive
multiple results from a method call
Boxing The Software Technology Group
Inheritance and More C#25(44)
Växjö universitet
Exceptions:An Example (ExceptionMain.cs)
static void Main(string[] args) {
int p = 7,q = 0;
try {
int res = MyDivide(p,q);
Console.WriteLine("{0}/{1} = {2}",p,q,res);
}
catch (Exception e) {
Console.WriteLine("Exception caught!\n\tMSG:"+e.Message);
Console.WriteLine("\tLOCATION:{0} in {1}",e.TargetSite,e.Source);
}
}
static int MyDivide(int a,int b) {
if (b == 0)
throw new DivideByZeroException();
else
return a/b;
}
Exceptions and IO The Software Technology Group
Inheritance and More C#26(44)
Växjö universitet
Exceptions:Basics
I
C#handles all errors and abnormal conditions using exceptions.
I
An exception is an object that encapsulates information about an error.
I
Error ) program throws (or raises) an exception.
(e.g.,throw new IndexOutOfRangeException())
I
) execution halts immediately
I
) call stack is unwounded until an appropriate enclosing exception handler is
found.
(e.g.,catch(IndexOutOfRangeException exc) {...})
I
No enclosing exception handler ) VM handles exception and abruptly
terminates program.
I
Advantages
I
Uniform handling of all abnormal contitions
I
Separation of responsibilities:
The programmer identies problems and raises exceptions.
The client determines how to handle the problem
(ignore and continue,recover,try again,exit,...).
Exceptions and IO The Software Technology Group
Inheritance and More C#27(44)
Växjö universitet
Predened Exceptions
C#comes with a large number of predened execeptions.
Many are dened in the System namespace.
Others are dened among related classes (e.g.IO related in namespace System.IO).
Exception
SystemException
ArithmeticException
DivideByZeroException
OverflowException
...
IndexOutOfRangeException
InvalidCastException
IOException
FileNotFoundException
DirectoryNotFoundException
....
ApplicationException
"user defined exceptions"
...
...
That is,you can throw an appropriate predened exception or implement an exception
type of your own by extending ApplicationException
Exceptions and IO The Software Technology Group
Inheritance and More C#28(44)
Växjö universitet
Working with Directories and Files
I
C#comes with two classes that can be used to manipulate directories and les:
I
System.IO.DirectoryInfo
I
System.IO.FileInfo
I
They can be used to
I
create new les/directories
I
move and remove les/directories
I
nd last access/write time
I
query about priviliges
I
query about content
I
Example:
DirectoryInfo dir = new DirectoryInfo("C:\\");//\\is escape for\
Console.WriteLine(dir.FullName);//C:\
Console.WriteLine(dir.CreationTime);//2004-06-10 16:28:40
Console.WriteLine(dir.GetDirectories().Length);//18
Console.WriteLine(dir.GetFiles().Length);//24
I
Classes with similar static methods:
System.IO.Directory,System.IO.File
Exceptions and IO The Software Technology Group
Inheritance and More C#29(44)
Växjö universitet
Streams (FilesMain.cs)
I
Streams are used to read and write to les
I
Streams are also used in networking
FileInfo file = new FileInfo("C:\\TEMP\\tmp.txt");
if (file.Exists) file.Delete();//Ensure that the target does not exist.
/* Sloppy approach with no exception handling */
StreamWriter sw = file.CreateText();//create file and open output stream
sw.WriteLine ("This is my file.");
sw.WriteLine ("I can write ints {0} or floats {1},and so on.",1,4.2);
sw.Close();
I
There are other streams available.For example
I
BinaryReader,BinaryWriter:Handles primitive data
I
FileStream:Bidirectional (both read and write)
Exceptions and IO The Software Technology Group
Inheritance and More C#30(44)
Växjö universitet
Reading text (FilesMain.cs)
I
File manipulations are likely to fail ) use exception handling
StreamReader sr = null;
try {
sr = new StreamReader("C:\\TEMP\\tmp.txt");
string line;
while ((line = sr.ReadLine())!= null) {//read line
Console.WriteLine(line);
}
} catch (IOException e) {
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
} finally {
if (sr!= null)
sr.Close();
}
I
The finally block is always executed after the try block.
I
) The above approach ensures that no les are left open.
Exceptions and IO The Software Technology Group
Inheritance and More C#31(44)
Växjö universitet
Collection Classes
I
The C#library comes with a number of pre-dened collection classes
)data-structures like list,stack,and hash table.
I
They are dened in the namespace System.Collections.
I
They all take object values as input
)can be used on any type of data (both primitive and reference).
I
A few examples from System.Collections:
I
Stack:ICollection,ICloneable
(a last in,rst out,data structure)
I
Queue:ICollection,ICloneable
(a rst in,rst out,data structure)
I
ArrayList:IList,ICloneable
(an array-based list implementation)
I
Hashtable:IDictionary,ISerializable,ICloneable
(a key-value mapping)
I
SortedList:IDictionary,ICloneable
(a key-value mapping with sorted keys)
Collection Classes The Software Technology Group
Inheritance and More C#32(44)
Växjö universitet
Collection Example:Hashtable
Provides an unordered key-to-value mapping ) a set of key/value pairs.
Some Hashtable members:
void Add(object key,object value)//Adds an key/value pair.
ICollection Keys {get;}//Gets all keys in the table.
ICollection Values {get;}//Gets all values in the table.
bool ContainsKey(object key)//"true"if the table contains key.
bool ContainsValue(object value)//"true"if table contains value.
Object this [Object key] {get;set;}//indexer,gets/sets value for a key.
Usage:
HashTable ht = new HashTable();
ht.Add("first","Hello");
ht.Add("second","World");
ht.Add("third","!");
ICollection coll = ht.Keys;//ICollection extends IEnumerable,
the iteration order is undefined.
foreach (string key in coll)
Console.WriteLine("key:{0},value:{1},key,ht[key]);
Collection Classes The Software Technology Group
Inheritance and More C#33(44)
Växjö universitet
Collection Example:SortedList
Provides a key-to-value mapping sorted by the keys
Some SortedList members:
void Add(object key,object value)//Adds an key/value pair,
//key should implement IComparable
Object this [Object key] {get;set;}//indexer,gets/sets value for a key.
object GetKey(int n)//Gets the key at position n.
object GetByIndex(int n)//Gets the value at position n.
Usage:
SortedList mySL = new SortedList();
mySL.Add("C","Hello");
mySL.Add("A","World");
mySL.Add("B","!");
for ( int i = 0;i < mySL.Count;i++ ) {
Console.WriteLine("\t{0}:\t{1}",mySL.GetKey(i),mySL.GetByIndex(i) );
} Output:A:World
B:!
C:Hello
Notice:All keys must implement IComparable
Collection Classes The Software Technology Group
Inheritance and More C#34(44)
Växjö universitet
Sortable classes:System.IComparable
Classes implementing the interface System.IComparable are sortable.
class Temperature:IComparable {
int temp;
public Temp(int temp) { this.temp = temp}
public int Value {//Set/get temperature
get { return temp;}
set { temp = value;}
}
/* Implement IComparable,result > 0 ==> this > obj */
public int CompareTo(object obj) {
if(obj is Temperature) {
Temperature t = (Temperature) obj;
return temp - t.temp;
}
throw new ArgumentException(obj+"is not a Temperature");
}
}
Collection Classes The Software Technology Group
Inheritance and More C#35(44)
Växjö universitet
Generic Classes (or Templates) { Introduction
I
Generic classes (parametrisized class declarations)
is new to C#version 2.0
I
Generic classes was at the same time introduced in Java
I
The current approach is inspired by C++ templates
I
A generic class is instantiated by providing a concrete type
as a parameter to the constructor call.
I
It might be more than one type parameter.
I
C#has a number of predened generic collection classes (abstract data
types)
I
ArrayList,LinkedList,Stack,Queue
I
Hashtable,SortedList (a key-value mapping)
Generics The Software Technology Group
Inheritance and More C#36(44)
Växjö universitet
Using Generics
using System.Collections;using System.Collections.Generic;
...
public static void Main() {
//No generics
Stack s = new Stack();
for (int i=0;i<10;i++) s.Push(i*10);//Boxing
int sum = 0;
while (s.Count > 0) sum += (int)s.Pop();//Unboxing
Console.WriteLine("Sum:"+ sum);
//Using generics
Stack<int> gs = new Stack<int>();
for (int i=0;i<10;i++) gs.Push(i*10);//Static type checking
sum = 0;
while (gs.Count > 0) sum += gs.Pop();//No cast!
Console.WriteLine("Sum:"+ sum);
}
Generics The Software Technology Group
Inheritance and More C#37(44)
Växjö universitet
Why Generics?
Why generics,why not use object as a parameter?
I
Use object )repeated down casts ) type checking at run-time
I
Generic classes )static type checking )errors discovered when
compiling
I
Use object instead of primitive values )boxing )object creation )
time and memory consuming
I
Generic classes )no boxing when using primitive arguments
Using generic classes is simple )Use them!
Generics The Software Technology Group
Inheritance and More C#38(44)
Växjö universitet
Implementing Generics
I
Implementing generic classes is a bit more tricky
public class A<T> {
public void Aa(T t) {"do something with t"}
public T Ab(T t) {"return something of type T"}
}
I
Remember:It must work on every possible type (both value and reference)
Generic Conditions
I
Generic conditions are used to limit the scope of a generic class
I
They add conditions on the type of applicable parameter types.
public class A<T> where T:IComparable {
==> All parameter types must implement the IComparable interface
==> they have a method
int CompareTo()
that can used to compare two objects
}
Implementing Generics The Software Technology Group
Inheritance and More C#39(44)
Växjö universitet
A Generic List (GenericListMain.cs)
public interface IMyList<T>://Testing MyGenericList
IEnumerable<T> { IMyList<int> list = new MyGenericList<int>();
//Properties for (int i=0;i<10;i++)
int Size{get;}//read only list.Add(i*10);
//Methods for (int i=0;i<list.Size;i++)
void Add(T o);Console.WriteLine("{0}\t{1}",i,list[i]);
bool Contains(T o);list[1] = 3;
list[7] = 33;
//Indexer
T this [int index] {get;set;} foreach(int n in list)
} Console.WriteLine("Item:{0}",n);
Implementing Generics The Software Technology Group
Inheritance and More C#40(44)
Växjö universitet
MyGenericList (GenericListMain.cs)
public class MyGenericList<T>:IMyList<T> {
int length = 4;
int top = 0;
T[] items;//element storage structure
public MyGenericArrayList() {items = new T[length];}
public void Add(T o) {
if (top == length)
resize();
items[top++] = o;
}
private void resize() {
length = 2*length;
T[] tmp = new T[length];
for (int i=0;i<top;i++)
tmp[i] = items[i];
items = tmp;
}
Implementing Generics The Software Technology Group
Inheritance and More C#41(44)
Växjö universitet
Properties and Indexers
public int Size {
get {return top;}
}
public T this [int index] {
get {
if (index > -1 && index < top)
return items[index];
else
throw new ArgumentException("Index is out of range","index");
}
set {
if (index > -1 && index < top)
items[index] = value;
else
throw new ArgumentException("Index is out of range","index");
}
}
Implementing Generics The Software Technology Group
Inheritance and More C#42(44)
Växjö universitet
The Enumerator (GenericListMain.cs)
/* IEnumerable<T> extends IEnumerable ==> We must implement both versions.*/
public IEnumerator<T> GetEnumerator() { return new MyEnumerator<T>(this);}
/* A so-called"explicit interface implementation"*/
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator();}
class MyEnumerator<X>:IEnumerator<X> {//An inner class
int index = -1;
MyGenericList<X> list;
public MyListEnumerator(MyGenericList<X> l) {list = l;}
/* IEnumerator<X> extends IEnumerator ==> We must implement both versions.*/
public object Current { get {return list.items[index];}}
object IEnumerator.Current { get { return Current;} }
/* Methods shared by IEnumerator<X> and IEnumerator*/
public bool MoveNext() { return (++index < list.top)?true:false;}
public void Reset() {index = -1;}
}
Implementing Generics The Software Technology Group
Inheritance and More C#43(44)
Växjö universitet
Practical Assignment 2 is now available!
I
Four exercises using Inheritance,Generics,and Exceptions.
I
No Red-black Trees!
I
Exercises 1 and 2 are also used in the FoST course
) some of you might already have solved them in Java.
I
Finally,no lectures next week
) work on the practical assignments
Course Information The Software Technology Group
Inheritance and More C#44(44)