Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
H.Mssenbck
University of Linz, Austria
moessenboeck@ssw.uni-linz.ac.at
Contents
Inheritance
Interfaces
Delegates
Exceptions
Namespaces and Assemblies
Attributes
Threads
XML Comments
1
Inheritance
Syntax
class A {
int a;
public A() {...}
public void F() {...}
}
// base class
class B : A{
int b;
public B() {...}
public void G() {...}
}
Assignments
A a = new A();
a = new B();
a = new C();
B b = a;
= new C();
(a is C) ...
(a is B) ...
(a is A) ...
a = null;
if (a is C) ...
as
A a = new C();
B b = a as B;
C c = a as C;
a = null;
c = a as C;
// c == null
Overriding of Methods
Only methods that are declared as virtual can be overridden in subclasses
class A {
public
public virtual
}
A message invokes the method belonging to the dynamic type of the receiver
(not quite true, see later)
A a = new B();
a.WhoAreYou();
// "I am a B"
Every method that can work with A can also work with B
void Use (A x) {
x.WhoAreYou();
}
Use(new A());
Use(new B());
// "I am an A"
// "I am a B"
7
Hiding
Members can be declared as new in a subclass.
They hide inherited members with the same name.
class A {
public int x;
public void F() {...}
public virtual void G() {...}
}
class B : A {
public new int x;
public new void F() {...}
public new void G() {...}
}
B b = new B();
b.x = ...;
b.F(); ... b.G();
// accesses B.x
// calls B.F and B.G
((A)b).x = ...;
((A)b).F(); ... ((A)b).G();
// accesses A.x !
// calls A.F and A.G !
8
C c = new D();
c.WhoAreYou();
// "I am a D"
A a = new D();
a.WhoAreYou();
// "I am a B" !!
Explicit call
class A {
...
}
class A {
public A() {...}
}
class A {
public A(int x) {...}
}
class A {
public A(int x) {...}
}
class B : A {
public B(int x) {...}
}
class B : A {
public B(int x) {...}
}
class B : A {
public B(int x) {...}
}
class B : A {
public B(int x)
: base(x) {...}
}
B b = new B(3);
B b = new B(3);
B b = new B(3);
B b = new B(3);
OK
- default constr. A()
- B(int x)
OK
- A()
- B(int x)
Error!
- no explicit call of
the A() constructor
- default constr. A()
does not exist
OK
- A(int x)
- B(int x)
11
Example
class Stack {
protected int[] values = new int[32];
protected int top = -1;
public void Push(int x) {...}
public int Pop() {...}
}
class BetterStack : Stack {
public bool Contains(int x) {
foreach (int y in values ) if (x == y) return true;
return false;
}
}
class Client {
Stack s = new Stack();
... s.values[0] ... // compilation error!
}
12
Abstract Classes
Example
abstract class Stream {
public abstract void Write(char ch);
public void WriteString(string s) { foreach (char ch in s) Write(s); }
}
class File : Stream {
public override void Write(char ch) {... write ch to disk ...}
}
Note
13
// method
// property
// indexer
}
class List : Sequence {
public override void Add(object x) {...}
public override string Name { get {...} }
public override object this [int i] { get {...} set {...} }
}
Note
Overridden indexers and properties must have the same get and set methods as in the
base class
14
Sealed Classes
Example
sealed class Account : Asset {
long val;
public void Deposit (long x) { ... }
public void Withdraw (long x) { ... }
...
}
Note
15
Interfaces
16
Syntax
public interface IList : ICollection, IEnumerable {
int Add (object value);
// methods
bool Contains (object value);
...
bool IsReadOnly { get; }
// property
...
object this [int index] { get; set; } // indexer
}
17
A class can inherit from a single base class, but implement multiple interfaces.
A struct cannot inherit from any type, but can implement multiple interfaces.
Implemented interface methods can be declared virtualor abstract (i.e. an interface can
be implemented by an abstract class).
18
MyBaseClass
IList
<<interface>>
ISerializable
MyClass
Assignments:
Method calls:
list.Add("Tom");
Type checks:
// true
Type casts:
c = list as MyClass;
c = (MyClass) list;
ISerializable ser = (ISerializable) list;
19
Example
interface ISimpleReader {
int Read();
}
interface IReader : ISimpleReader {
void Open(string name);
void Close();
}
class Terminal : ISimpleReader {
public int Read() { ... }
}
<<interface>>
ISimpleReader
Read
Terminal
Read
<<interface>>
IReader
Open
Close
File
Read
Open
Close
10
21
22
11
Note
A delegate variable can have the value null (no method assigned).
If null, a delegate variable must not be called (otherwise exception).
Delegate variables are first class objects: can be stored in a data structure, passed as
parameter, etc.
23
Method can be static. In this case the class name must be specified instead of obj.
new Notifier(MyClass.StaticSayHello);
24
12
Multicast Delegates
A delegate variable can hold multiple values at the same time
Notifier greetings;
greetings = new Notifier(SayHello);
greetings += new Notifier(SayGoodbye);
greetings("John");
greetings("John");
Note
if the multicast delegate is a function, the value of the last call is returned
if the multicast delegate has an out parameter, the parameter of the last call is returned
25
13
Exceptions
27
try Statement
FileStream s = null;
try {
s = new FileStream(curName, FileMode.Open);
...
} catch (FileNotFoundException e) {
Console.WriteLine("file {0} not found", e.FileName);
} catch (IOException) {
Console.WriteLine("some IO exception occurred");
} catch {
Console.WriteLine("some unknown error occurred");
} finally {
if (s != null) s.Close();
}
14
System.Exception
Properties
e.Message
e.StackTrace
e.Source
e.TargetSite
...
Methods
e.ToString()
...
29
Throwing an Exception
By an invalid operation (implicit exception)
Division by 0
Index overflow
Acess via a null reference
...
30
15
try {
G();
....
} catch (Exc e) {
...
}
G
...
H();
....
H
...
throw new FooException(...);
....
Caller chain is traversed backwards until a method with a matching catch clause is found.
If none is found => Program is aborted with a stack trace
32
16
C#
void myMethod() {
... throw new IOException(); ...
}
34
17
Java
A file may contain just 1 package
xxx.java
namespace A {...}
namespace B {...}
namespace C {...}
package A;
...
...
namespace A {
class C {...}
}
package A;
class C {...}
Samples
Samples
xxx.cs
A
C.java
35
Java
Imports classes
import java.util.LinkedList;
import java.awt.*;
using A;
namespace B {
using C;
...
}
import java.util.LinkedList;
using F = System.Windows.Forms;
...
F.Button b;
for explicit qualification and short names.
package A;
class C {
void f() {...} // package
}
C# has only visibility internal (!= namespace)
36
18
Assemblies
Run time unit consisting of types and other resources (e.g. icons)
C1
C2
namespace A
C3
C4
namespace B
assembly
icon
37
A.cs
B.cs
modules
.exe executable
.dll library
with
manifest
.netmodule
without
manifest
csc
C.netmodule
module
libraries
D.dll
Only metadata are embedded
19
Compiler Options
Which output file should be generated?
/t[arget]: exe
| winexe
| library
| module
/out:name
/doc:name
Example:
generates an XML file with the specified name from /// comments
39
Compiler Options
How should libraries and modules be embedded?
/r[eference]:name
/lib:dirpath{,dirpath}
/addmodule:name {,name}
Example
csc /r:MyLib.dll /lib:C: \project A.cs B.cs
40
20
=> A.exe
=> B.exe (if B.cs contains Main )
=> X.exe
=> A.dll
=> A.dll
=> X.dll
41
Attributes
42
21
Attributes
User-defined metainformation about program elements
Example
[Serializable]
class C {...}
eters
eters
aram os. param
meter
a
p
r
a
e
p
nam after p
onal
positi
e
com
Valid variants:
[Obsolete]
[Obsolete("some Message")]
[Obsolete("some Message", false)]
[Obsolete("some Message", IsError=false)]
44
22
Example: ConditionalAttribute
Allows a conditional call of methods
#define debug
// preprocessor command
class C {
[Conditional("debug")]
// only possible for void methods
static void Assert (bool ok, string errorMsg) {
if (!ok) {
Console.WriteString(errorMsg);
System.Environment.Exit(0); // graceful program termination
}
}
static void Main (string[] arg) {
Assert(arg.Length > 0, "no arguments specified");
Assert(arg[0] == "...", "invalid argument");
...
}
}
Use
[Comment ("This is a demo class for Attributes", Author="XX")]
class C { ... }
search should
also be continued
in subclasses
}
46
23
Threads
47
// properties
// methods
}
public delegate void ThreadStart();
24
Example
using System;
using System.Threading;
class Printer {
char ch;
int sleepTime;
public Printer(char c, int t) {ch = c; sleepTime = t;}
public void Print() {
for (int i = 0; i < 100; i++) {
Console.Write(ch);
Thread.Sleep(sleepTime);
}
}
}
class Test {
static void Main() {
Printer a = new Printer('.', 10);
Printer b = new Printer('*', 100);
new Thread(new ThreadStart(a.Print)).Start();
new Thread(new ThreadStart(b.Print)).Start();
}
}
Thread States
Thread t = new Thread(new ThreadStart(P));
Console.WriteLine("name={0}, priority={1}, state={2}", t.Name, t.Priority, t.ThreadState);
t.Name = "Worker"; t.Priority = ThreadPriority.BelowNormal;
t.Start();
Thread.Sleep(0);
Console.WriteLine("name={0}, priority={1}, state={2}", t.Name, t.Priority, t.ThreadState);
t.Suspend();
Console.WriteLine("state={0}", t.ThreadState);
t.Resume();
Console.WriteLine("state={0}", t.ThreadState);
t.Abort();
Thread.Sleep(0);
Console.WriteLine("state={0}", t.ThreadState);
Output
name=, priority=Normal, state=Unstarted
name=Worker, priority=BelowNormal, state=Running
state=Suspended
state=Running
state=Stopped
50
25
Output
start--------------------end
51
Example
class Account {
long val = 0;
26
Class Monitor
lock(v) Statement
is a shortcut for
Monitor.Enter(v);
try {
Statement
} finally {
Monitor.Exit(v);
}
53
Monitor.Wait(lockedVar);
Monitor.Pulse(lockedVar);
Monitor.PulseAll(lockedVar);
Example
Thread A
lock(v) {
...
2 Monitor.Wait(v);5
...
}
Thread B
lock(v) {
...
4 Monitor.Pulse(v);
...
}6
1.
2.
3.
4.
27
If producer is faster
Put
Put
Put
Put
Get
Put
Get
...
If consumer is faster
Put
Get
Put
Get
...
55
XML Comments
56
28
57
58
29
59
XML Tags
Predefined Tags
Main tags
<summary> short description of a program element </summary>
<remarks> extensive description of a program element </remarks>
<param name="ParamName"> description of a parameter </param>
<returns> description of the return value </returns>
Tags that are used within other tags
<exception [cref="ExceptionType"]> used in the documentation of a method:
describes an exception </exception>
<example> sample code </example>
<code> arbitrary code </code>
<see cref=" ProgramElement" > name of a crossreference link </see>
<paramref name="ParamName"> name of a parameter </paramref>
User-defined Tags
Users may add arbitrary tags, e.g. <author>, <version>, ...
60
30
Summary
61
Summary of C#
Familiar
Safe
Expressive
62
31