SlideShare una empresa de Scribd logo
1 de 131
1
1. Introduction
2. C# versus Java : highlights
3. C# data types
4. Defining custom data types
5. Operator Overloading
6. Event driven programming
7. .NET Framework Class Library
8. A GUI in C#
9. A web service in C#
2
C# and .NET
1. Introduction
• History
• C# features
• .NET framework
2. C# versus Java : highlights
3. C# data types
4. Defining custom data types
5. ...
3
History
Builds on legacy from
• C/C++ tradition -> new programming language C#
• Java tradition : many ideas borrowed
• runtime environment : virtual machine
• platform/language abstraction
• guarded execution environment
• garbage collection
• single rooted hierarchy
• ...
Takes software development one step further towards
component based design
4
History
procedural/structured
design/programming
object oriented
design/programming
component based
design/programming
C/PASCAL
C++
JAVA
C#/.NET
component support possible
BUT NOT built into the language
- templates
- deployment descriptors
COM/COM+
CORBA component model
5
C# features :
component oriented
Modern large-scale systems are component based
Properties
get/set
event based communication
support to annotate component for
- deployment
- configuration at design and/or runtime
- component versioning
- documentation
6
C# features : OO paradigm
supports all typical OO mechanisms
• encapsulation
• inheritance
• polymorphism
• interface based programming
C++ legacy (NOT supported in Java)
• support for operator overloading
• user defined type conversions
• rectangular arrays
• pass-by-reference
7
C# features :
Excution model
NO own runtime library
- uses .NET library (redesign of MS-library)
(implemented in C#)
Compiles to intermediary language
(CIL - Common Intermediate Language)
Executed by virtual machine
(CLR – Common Language Runtime)
- memory management through garbage collection
- guarded execution (e.g. array bounds guarding)
- JIT compilation
8
.NET framework
“.NET framework”
CLR
FCL Framework
Class Library
Application Code
Version 1.0 released January 15, 2002
9
.NET execution model
Platform AND language portability
CLR can exploit processor/platform specific optimizations
Supported languages :
C#, J#, VB.NET, JScript, Microsoft IL, Managed Extensions for C++
Supplied by 3rd
parties :
COBOL, Eiffel, Haskell, Forth, Scheme, Smalltalk, Pascal, ...
CLR
Compiler
Application Code in “A Language”
CIL
10
.NET :
Common Type System
Cross language type system, allowing
- type safety
- cross language integration
- execution services (garbage collection, JIT, exceptions, ...)
Defines rules to define types, irrespective of source language
All types eventually mapped to CTS-types
e.g. cross language inheritance
J# class inherits from C# class
Minimum subset for language to be supported by .NET :
CLS – Common Language Specification
- CLS-compliant language = “CLS consumer”
- if more than CLS : “CLS extender”
C#= both CLS consumer and extender
11
.NET : FCL categories
comprises
- > 3500 classes
- > 1 000 000 lines of code
• core functions
• basic datatypes, collections
• IO (network, console, file)
• calls to runtime services
• database interaction
• transactions
• consuming/producing XML
• manipulation of tables
• web-based applications (thin clients)
• desktop applications (thick clients)
• SOAP-based XML web services
12
Hello
namespace Project1
{ using System;
class Class1
{ static void Main() {
Console.WriteLine("Hello there !");
for (int i = 0; i < 10; i++)
Console.WriteLine(i);
}
}
}
package project1;
import java.lang.*;
class Class1 {
public static void main(String[] args) {
System.out.println("Hello there !");
for (int i = 0; i < 10; i++)
System.out.println(i);
}
}
C#
Java
13
C# and .NET
1. Introduction
2. C# versus Java : highlights
3. C# data types
4. Defining custom data types
14
C# - Java :
common approaches
Both intended as improvement to C++
• Compilation to machine independent language, managed execution
• Garbage Collection, no pointers
(C# allows pointer usage in special “unsafe” code sections)
• Reflection API
• No header files, no problems with circular (type) references
• Single rooted hierarchy, objects allocated on the heap
• Thread support by object-level lock
• Multiple extension of interfaces, single inheritance for classes
• Inner classes (closure instead of nested class)
• Simple inheritance rules (no inheritance modifiers)
• Everything is in a class (no global data, no global functions)
• Arrays, strings : bounds checked at execution time
• Systematic usage of “.” (instead of “->” and “::”)
• Keywords for null pointer (null) and boolean type (boolean/bool)
• Guaranteed initialization
• if-statement controlled by boolean (instead of integer)
• Finally-clause in try-catch blocks
15
Properties
C# : special support for getters/setters
Java : implied by coding convention (template or “design pattern”)
Property int min
Java style :
public int getMin() {return min;}
public void setMin(int m) {min=m;}
C# style :
public int Min {
get {return min;}
set {min=value;}
}
// value : implicit variable used when
// calling setter method
- getter/setter grouped together
- encourages to think in terms of properties
16
IndexerMeans to index underlying datastructure
Java style :
public class Bookshop {
private Book[] books;
// ...
public void setBooks(int i,Book b) {
if(b!=null) books[i]=b;
}
public Book getBooks(int i) {return books[i];}
}
C# style :
public class Bookshop
{
private Book[] books;
// ...
public Book this[int i]{
get {return books[i];}
set {if(value!=null) books[i]=value;}
}
}
// ...
Bookshop standaard=new Bookshop();
standaard[10]=new Book(“Harry Potter”);
17
Event handling
Delegates used to handle events
- Java equivalent : inner class object
- C/C++ equivalent : function pointer
Direct support in C# for events
public delegate void TempChangeHandler(double t,ref bool cancel);
public class Thermometer {
public event TempChangeHandler TempChange;
double temp;
public double Temperature{
get{return temp;}
set{if(temp!=value) {
bool cancel=false;
TempChange(value,ref cancel); // fire event
if(!cancel) temp=value;
}
}
}
18
Event handling
public class TempController {
public TempController(Thermometer tm) {
tm.TempChange+=new TempChangeHandler(tm_TempChange);
}
private void tm_TempChange(double t,ref bool cancel) {
if(t>100) {
cancel=true;
System.Console.WriteLine(
"Way too hot : WRONG VALUE");
} else {
System.Console.WriteLine(
"New temperature registered.");
}
}
}
19
Event handling
public class Test {
public static void Main() {
Thermometer term=new Thermometer();
TempController tc=new TempController(term);
term.Temperature=30;
Console.WriteLine("Temp = {0}",term.Temperature);
term.Temperature=120;
Console.WriteLine("Temp = {0}",term.Temperature);
}
}
20
Enummerations
Standard Java approach
public class Period {
public final static int DAILY=1;
public final static int WEEKLY=2;
public final static int MONTHLY=3;
public final static int YEARLY=4;
}
// ...
int publicationPeriod=Period.DAILY;
// PROBLEM : does not prevent int publicationPeriod=12; ???
C# approach
public enum Period{DAILY=1,WEEKLY=2,MONTHLY=3,YEARLY=4};
Period publicationPeriod = Period.WEEKLY;
21
Enummerations
Java 5 approach
enum PeriodE{DAILY,WEEKLY,MONTHLY,YEARLY}
//...
int publicationPeriod=Period.DAILY;
System.out.println(publicationPeriod);
PeriodE pubPeriod=PeriodE.DAILY;
System.out.println(pubPeriod);
// OUTPUT :
// 1
// DAILY
22
Iterating over a Collection
Standard Java approach
for(Iterator i=collection.iterator();i.hasNext();) {
Object o=i.next();
// do something with o
}
for(int i=0;i<array.length;i++) {
// do something with array[i]
}
C# approach
foreach(object o in collection) {
// do something with o
}
foreach(int i in array) {
// do something with i
}
Java 5 approach
for(Object o : collection) {
// do something with o
}
for(int i : array) { // do something with i
}
23
Extension on
“primitive” typesC# struct datatype :
- very similar to class (defines attributes and methods)
- BUT : - allocated on the stack or in-line (instead of heap)
- value type -> pass by value by default
- efficient for small types
- usage similar to usage of primitive types in Java
struct CoupleV
{
private int x, y;
public int X
{
set { x = value; }
get { return x; }
}
public int Y
{
set { y = value; }
get { return y; }
}
public string ToString()
{
return "(" + x + "," + y + ")";
}
24
Extension on
“primitive” types
public static void Main()
{
CoupleV p = new CoupleV();
p.X = 10;
p.Y = 20;
CoupleV q=new CoupleV();
q.X = 20;
q.Y = 30;
Console.WriteLine(p.ToString());
Console.WriteLine(q.ToString());
CoupleV[] r = new CoupleV[4];
for (int i = 0; i < r.Length; i++)
r[i].X = r[i].Y=i;
foreach(CoupleV i in r)
Console.WriteLine(i.ToString());
}
25
Operator Overloading
Allows to program type specific operator semantics
More restrictive than C++ overloading mechanism
- always static
- NON virtual (static binding !) !
public static bool operator ==(CoupleV a, CoupleV b)
{
return ((a.x == b.x) && (a.y == b.y));
}
public static Boolean operator !=(CoupleV a, CoupleV b)
{
return !(a == b);
}
// ...
CoupleV p = new CoupleV();p.X = 10;p.Y = 20;
CoupleV q = new CoupleV();q.X = 10;q.Y = 20;
Console.WriteLine(p == q); // TRUE
Console.WriteLine((object)p == (object)q); // FALSE non-virtual !
26
Polymorphism
Java : all methods virtual (late binding) by default
C# (like C++) : methods MUST be declared virtual if late binding applies
class A
{
public virtual void f() {Console.WriteLine("A.f()");}
}
class B : A
{
public override void f() {Console.WriteLine("B.f()");}
}
- shows intention of programmer
- more efficient
- can prevent later extensions ...
- explicit interface implementation
(solving name conflicts in case of multiple interface implementation)
- possibility to hide base class type/method in derived class
27
Assemblies
Type boundaries
- class
- namespace (equivalent to Java package)
- assembly (equivalent to Java archive)
Assemby = exe/dll to deploy
- meta-data (files contained, security settings, versioning info,
dependencies)
- modules (compiled source files)
- resources
Versioning
- contained in assemby info
- allows to run multiple versions of same types on same CLR
28
Visibility
private
same as Java
= default for interface and enum members
public
same as Java
=default for struct and class members
protected
visible in type itself or derived types
internal
visible in assembly
= default for non-nested types
internal protected
visible from type itself, in same assembly and in derived
types (= private or protected or internal)
Type can not be more accessible then types used for its declaration
29
Parameter modifiers
Passing references
ref
pass reference to method
requires parameter is assigned definite value before method entry
out
requires definite parameter assignment before returning from
method call
Variable number of arguments
params
can be applied to last argument of method
Parameter modifiers are part of method signature
30
Parameter modifiers
static void swap(ref int a, ref int b)
{
int t = a; a = b; b = t;
}
static void OneMore(int i, out int j)
{
j = i + 1;
}
static int sum(params int[] x)
{
int r = 0;
foreach (int i in x) r += i;
return r;
}
// ...
int x = 1, y = 2;
swap(ref x, ref y);
Console.WriteLine("{0} - {1}",x, y); // 2 - 1
OneMore(x, out y);
Console.WriteLine("{0} - {1}", x, y); // 2 - 3
Console.WriteLine(sum(1, 2, 3)); // 6
Console.WriteLine(sum(3, 4, 5, 6)); // 18
31
Attributes
Allow to extend language built-in declarative constructs
- Pre-defined attributes (e.g. Serialized)
- Custom attributes
Can be applied to
- class
- method
- field
- parameter
Attributes and values can be retrieved at runtime
32
Field modifiers
const
- value calculated at compile time
- equivalent to Java final
readonly
- value calculated at runtime
- can only be assigned once !
- allows to retrieve setting
(“a not so constant constant ...”)
33
Pointer arithmetic
allowed in sections marked as unsafe
pointer type : <type>*
dereferencing : *<pointer expression>
address calculation : &<variable>
Garbage collector should NOT move around objects
used in unsafe regions
MUST be declared fixed
34
Pointer arithmetic
unsafe static void AdditionOne(int[] b)
{
int l=b.Length;
fixed (int* a = b)
{
int* p = a;
for (int i = 0; i < l; i++,p++) *p = (*p) + 1;
}
}
//...
int[] k ={ 1, 2, 3, 4 };
foreach (int a in k) Console.WriteLine("{0}", a); // 1 2 3 4
AdditionOne(k);
foreach (int a in k) Console.WriteLine("{0}", a); // 2 3 4 5
35
Rectangular Arrays
int[,,] a=new int[3,4,5]; // rectangular array
// single reference variable
a[1,2,3]=20;
int[][][] b=new int[3][4][5]; // jagged array
b[1][2][3]=30;
...
36
Constructors - Destructors
Very similar to Java constructors – finalizers
Constructor :
can contain explicit constructor call
specified outside constructor body
- call to other constructor of same type : this(...)
- call to base class constructor : base(...)
Destructor
NOT for value type
NO explicit calls to destructor
C++-like syntax (actually expands to calling Finalize)
class A
{
public A():this(1){}
public A(int i):base(i){}
~A() {/* Destructor */}
}
37
C# and .NET
1. Introduction
2. C# versus Java : highlights
3. C# data types
4. Defining custom data types
38
C# type system
Value types (struct, enum)
Reference types (class, array, delegate, interface)
Pointer type
struct CoupleV
{
private int x, y;
public CoupleV(int xx, int yy) { x = xx; y = yy; }
public int X
{
set { x = value; }
get { return x; }
}
public int Y
{
set { y = value; }
get { return y; }
}
public override string ToString()
{
return "(" + x + "," + y + ")";
}
}
39
C# type system
class CoupleR
{
private int x=0, y=0;
public CoupleR(int xx, int yy) { x = xx; y = yy; }
public int X
{
set { x = value; }
get { return x; }
}
public int Y
{
set { y = value; }
get { return y; }
}
public override string ToString()
{
return "(" + x + "," + y + ")";
}
}
40
C# type system
// ...
CoupleR a = new CoupleR(1, 2);
CoupleR b = a;
CoupleV c = new CoupleV(3, 4);
CoupleV d = c;
a.X = 7;
c.X = 7;
Console.WriteLine(a); // (7,2)
Console.WriteLine(b); // (7,2)
Console.WriteLine(c); // (7,4)
Console.WriteLine(d); // (3,4)
41
Type unification
all struct and class types derive from object
(pointer types do not ...)
“simple” (“primitive”) types are actually structs
int : alias for System.Int32
long : alias for System.Int64
...
boxing – unboxing
- value type -> reference type : copy made (automatic)
- reference type -> value type : explicit cast necessary
int x=12;
object o=x; // box
int y=(int)o; // unbox through downcast
42
Available types
Value types
signed integer : sbyte, short, int, long
unsigned integer : byte, ushort, uint, ulong
floating point : float, decimal, double
logical : bool
characters : char
Reference types
object
string
standard notations for constants apply (U : unsigned, L : long)
standard rules for conversions apply
43
Checked Arithmetic
checked(<expression>)
checked {/* block */}
checks for integral overflows
generates runtime exception OverflowException
unchecked(<expression>)
unchecked{/* block */}
turns off compile time bounds checking
44
Control flow statements
Same as in Java, BUT
switch :
no “fall through” behaviour
each case must end with jump (break, goto, ...)
foreach
goto label;
// ...
int x=0;
loop :
x++;
if(x<5) goto loop;
45
Namespaces
Similar to java packages w.r.t. avoiding name clashes
BUT : no boundary for accessibility
Can be nested
namespace A {
namespace B {
class CL {
}
}
}
// ...
A.B.CL x=new A.B.CL();
Alternative
using A.B;
CL x=new CL();
Global namespace = default surrounding namespace
46
C# and .NET
1. Introduction
2. C# versus Java : highlights
3. C# data types
4. Defining custom data types
47
Classes
[<attributes>][unsafe][<access modifier>][new]
[abstract | sealed] <class name>
[: <base class> |
: <interfaces> |
: <base class>,<interfaces> ] {
<class members>
}
Class members
• Fields
• Constants
• Properties
• Indexers
• Methods
• Events
• Nested type (like Java static inner class, no outer object)
48
Modifiers
Accessibility (visibility) : private, internal, protected, public
Inheritable
sealed : can not be overridden/inherited (Java equivalent : final)
- sealed class
- sealed method
abstract : MUST be overridden/inherited
- abstract class
- abstract method
class/method can not be sealed AND abstract
Parameter modifiers : ref,out,params
Class member/instance member : static
Late binding/static binding : virtual, override, new
Dangerous ? : unsafe
- unsafe class
- unsafe method
- unsafe property
49
Inheritance
class A {}
class B : A {}
class C : B {}
class D : A {}
Runtime type checking (RTTI)
operator is
if(a is A) {/* ... */}
if(b is A) {/* ... */} // true if b is A or B
Conversions :
- widening conversions (upcast) : automatic
B b = new B();
C c = new C();
D d = new D();
A ab = b;
A ac = c;
B bc = c;
B bd = d; // compile time error
A ad = d;
- narrowing (cntd.)
50
Inheritance
- narrowing conversions : cast necessary
- simple downcast :
B ba=(B)ab; // OK
C ca=(C)ac; // OK
D da=(D)ad; //OK
D dc=(D)ac; // runtime error
- safe downcast (evaluates to null if unsuccesful)
B ba = ab as B;
C ca = ac as C;
D dc = ac as D; // null
51
Polymorphism
Key idea : late binding, based on dynamic object type
C# : use virtual methods, override in derived class
class A
{
public virtual void f() {Console.WriteLine("A.f()");}
}
class B : A
{
public override void f() {Console.WriteLine("B.f()");}
}
class C : B
{
public override void f() { Console.WriteLine("C.f()"); }
}
class D : A
{
public override void f() {Console.WriteLine("D.f()");}
}
52
Polymorphism
A a = new A();
B b = new B();
C c = new C();
D d = new D();
a.f(); // A.f()
b.f(); // B.f()
c.f(); // C.f()
d.f(); // D.f()
A[] a = new A[] { new A(), new B(), new C(), new D() };
foreach(A aa in a) aa.f();
// A.f()
// B.f()
// C.f()
// D.f()
53
Polymorphism
Sealing
class A
{
public virtual void f() {Console.WriteLine("A.f()");}
}
class B : A
{
public sealed override void f() {Console.WriteLine("B.f()");}
}
class C : B
{
public override void f() { Console.WriteLine("C.f()"); }
}
NOT allowed
54
Polymorphism
Hiding base class member : new
class A
{public virtual void f() {Console.WriteLine("A.f()");}}
class B : A
{public override void f() {Console.WriteLine("B.f()");}}
class C : B
{public new void f() { Console.WriteLine("C.f()"); }}
class D : A
{public override void f() {Console.WriteLine("D.f()");}}
A aa = new A(); aa.f(); // A.f()
B bb = new B(); bb.f(); // B.f()
C cc = new C(); cc.f(); // C.f()
D dd = new D(); dd.f(); // D.f()
A ab = new B(); ab.f(); // B.f()
A ac = new C(); ac.f(); // B.f()
A ad = new D(); ad.f(); // D.f();
B bc = new C(); bc.f(); // B.f();
A[] a = new A[] { new A(), new B(), new C(), new D() };
foreach(A o in a) o.f(); // A.f() B.f() B.f() D.f()
55
Polymorphism
Hiding base class member : new
class A
{public virtual void f() {Console.WriteLine("A.f()");}}
class B : A
{public override void f() {Console.WriteLine("B.f()");}}
class C : B
{public new void f() { Console.WriteLine("C.f()"); }}
class D : A
{public new void f() {Console.WriteLine("D.f()");}}
A aa = new A(); aa.f(); // A.f()
B bb = new B(); bb.f(); // B.f()
C cc = new C(); cc.f(); // C.f()
D dd = new D(); dd.f(); // D.f()
A ab = new B(); ab.f(); // B.f()
A ac = new C(); ac.f(); // B.f()
A ad = new D(); ad.f(); // A.f();
B bc = new C(); bc.f(); // B.f();
A[] a = new A[] { new A(), new B(), new C(), new D() };
foreach(A o in a) o.f(); // A.f() B.f() B.f() A.f()
56
Polymorphism
new
- define method as new (even if method with
same signature, possibly sealed, exists in base class)
- define new property
- define new field
class A
{protected double i;
public double I
{set{i = value;}
get{return i;}
}
public sealed void f() {Console.WriteLine("A.f()");}
}
class B : A
{private new int i;
public new int I
{set{i = value;}
get{return i;}
}
public new void f() {Console.WriteLine(“B.f()");}
}
57
Structs
Struct = class except for
• value type, allocated on the stack
• is implicitely sealed (inherit from single type, System.ValueType),
can implement several interfaces
• can NOT have destructor
• NO field initializers (initialization to 0)
• NO constructor that leaves fields uninitialized
struct CoupleV : A // not allowed unless A is interface
{
private int x=1, y=1; // NOT allowed : field initializer
public CoupleV(int xx) { x = xx; }
// NOT allowed : partial initialization
public CoupleV(int xx, int yy) { x = xx; y = yy; } // allowed
}
58
Interfaces
Interface = class except for
• no implementation, (pure abstract class)
• can be supertype of struct (class can not !)
Interface members :
- methods
- properties
- indexers
- events
always : implicitly public, abstract, virtual and non static
59
Interfaces
interface IP{void f();}
interface IQ{void g();}
class A : IP{
public virtual void f() {Console.WriteLine("A.f()");}
}
class B : A,IQ {
public override void f() {Console.WriteLine("B.f()");}
public virtual void g() {Console.WriteLine("B.g()");}
}
class C : B {
public override void f() { Console.WriteLine("C.f()"); }
public override void g() { Console.WriteLine("C.g()"); }
}
class D : A{
public override void f(){Console.WriteLine("D.f()");}
}
class E : D,IQ {
public override void f() { Console.WriteLine("E.f()"); }
public virtual void g() { Console.WriteLine("E.g()"); }
}
60
Interfaces
IP[] p = new IP[] { new A(), new B(), new C(), new D(), new E() };
IQ[] q = new IQ[] { new B(), new C(), new E() };
foreach (IP pp in p) pp.f();
foreach (IQ qq in q) qq.g();
// A.f()
// B.f()
// C.f()
// D.f()
// E.f()
// B.g()
// C.g()
// E.g()
Extending an interface
interface IPP : IP {
void ff();
}
61
Explicit interface
implementation
PROBLEM : implement two interfaces with name collision
-> explicit (instead of implicit) interface implementation
interface U
{
void a();
}
interface V
{
void a();
}
class O : U, V
{
void U.a() { Console.WriteLine("A.ua()"); }
void V.a() { Console.WriteLine("A.va()"); }
}
// ...
O o = new O();
// o.a(); // NOT allowed
((U)o).a(); // A.ua()
((V)o).a(); // A.va()
62
Explicit interface
implementation
LIMITATIONS (compared to implicit implementations)
• NO late binding
no polymorphism related modifiers
(no abstract, virtual, override, new)
• NO access modifier
usage requires cast to interface
access modifier mentioned there is used implicitely
Same rules (as with classes) to
• convert between types
• to convert to structs
63
C# and .NET
1. Introduction
2. C# versus Java : highlights
3. C# data types
4. Defining custom data types
5. Operator Overloading
6. Event driven programming
7. .NET Framework Class Library
8. A GUI in C#
9. A web service in C#
64
Operator overloading
Idea
• treat operators (+,-,*,/,%,...) as special functions
(keyword operator)
• give special meaning to operator according to class
semantics
• allows elegant programming for math-oriented
software
• important issue : what happens in case of mixed type
expressions ?
-> need to overload also type conversion
-> quite complex to keep consistent
-> not available in Java (but proposals are on the way ...)
65
C# Operator overloading
Operators to overload
+ - ! ~ ++ -- (unary)
(binary)
+ - * / % arithmetic
& | ^ bit logic
<< >> bit shift
== != > < >= <= relational
CAN NOT BE OVERLOADED :
- address related operators (unary *, &)
- assignment ! (cf. C++ ...)
ONLY static operators allowed
LOGIC pairs (MUST be overloaded together)
== and !=
< and >
<= and >=
66
Indirect overloading
To keep things consistent
(developer might forget to overload ...)
- && and || are evaluated using & and |
- [] operator overloaded through indexers
- combined assignment operators (+=, -=, *=, /=, ...)
evaluated using non-combined counterparts
67
Value equality
Operators == and != default to reference equality
If other behavior is needed :
- override Equals method (cf. Java)
- redirect Equals to “==“ and “!=“
-> allows compatibility with .NET languages
NOT supporting operator overloading
-> allows polymorphism
68
Value equality
class Point
{
protected int x, y;
public Point(int xx, int yy) { x = xx; y = yy; }
public Point(int xx) : this(xx, xx) { }
public Point() : this(0) { }
public override string ToString()
{
return "<"+x+","+y+">";
}
public static bool operator ==(Point a, Point b)
{
return (a.x == b.x) && (a.y == b.y);
}
public static bool operator !=(Point a, Point b)
{
return !(a == b);
}
}
69
Value equalityProblem
Collections framework heavily uses Equals()-method
(implementation of no-duplicate collections such as Sets)
-> whenever == and != overloaded -> Equals() should be overridden
public override bool Equals(object o)
{
if (o is Point)
{
Point p = (Point)o;
return this == p;
}
else return false;
}
DO NOT call Equals() from within == and != ...
70
Value equality :
inheritance
class Point3D : Point
{
protected int z;
public Point3D(int xx,int yy,int zz):base(xx,yy){z=zz;}
public override string ToString()
{
return "<"+x+","+y+","+z+">";
}
}
// ...
Point a=new Point(1,1);
Point b=new Point(2,2);
Point c = new Point(2, 2);
Point3D d=new Point3D(3,3,3);
Point3D e = new Point3D(3, 3, 3);
Point3D f = new Point3D(3, 3, 4);
Console.WriteLine(a); // <1,1>
Console.WriteLine(b); // <2,2>
Console.WriteLine(e); // <3,3,3>
Console.WriteLine(f); // <3,3,4>
71
Value equality :
inheritance
Console.WriteLine(a == b); // False
Console.WriteLine(a == c); // False
Console.WriteLine(a == d); // False
Console.WriteLine(b == c); // True -> value !
Console.WriteLine(b == d); // False
Console.WriteLine(c == d); // False
Console.WriteLine(d == e); // True
Console.WriteLine(e == f); // True
Operators == and != should be overloaded in Point3D
public static bool operator ==(Point3D a, Point3D b)
{
return (a.x == b.x) && (a.y == b.y)&&(a.z==b.z);
}
public static bool operator !=(Point3D a, Point3D b)
{
return !(a == b);
}
// ...
Console.WriteLine(e == f); // False
72
Value equality :
polymorphismPoint[] p ={ new Point(1, 1), new Point(2, 2),
new Point3D(1, 1, 1), new Point3D(2, 2, 2) };
Point s1 = new Point(2, 2)
Point s2 = new Point3D(2, 2, 2);
foreach (Point pp in p) Console.WriteLine(pp == s1);
foreach (Point pp in p) Console.WriteLine(pp == s2);
// False True False True
// False True False True
CHANGE operator in base class (!)
public static bool operator ==(Point a, Point b)
{
if(((a is Point3D)&&!(b is Point3D))||
(!(a is Point3D)&&(b is Point3D))) return false;
else return (a.x == b.x) && (a.y == b.y);
}
public static bool operator !=(Point a, Point b)
{
return !(a == b);
}
// False True False False
// False False False True
73
Overloading arithmetic
operators
Operator + Point p: translate over p
Operator + int i: translate over Point(i,i)
public static Point operator +(Point a, Point b){
return new Point(a.x + b.x,a.y + b.y);
}
public static Point operator +(Point a,int i){
return new Point(a.x + i, a.y + i);
}
public static Point operator +(int i, Point a){
return a + i;
}
//...
Point a = new Point(10, 20);
Point b = new Point(20, 30);
Console.WriteLine(a + b); //<30,50>
Console.WriteLine(a + 100); //<110,120>
Console.WriteLine(100 + a + b); //<130,150>
74
Type Conversion
Two versions
implicit
not dangerous, can be invoked by compiler
whenever needed
explicit
dangerous, only done if explicitely asked
e.g. conversion to and from int
Point-to-int : max value of x and y (looses info !)
int-to-Point : Point on diagonal (no info lost !)
75
Type Conversion
public static Point operator +(Point a,int i)
{
Console.WriteLine("+(P,i)");
return new Point(a.x + i, a.y + i);
}
public static Point operator +(int i, Point a)
{
Console.WriteLine("+(i,P)");
return a + i;
}
public static implicit operator Point(int i)
{
Console.WriteLine("(P)i");
return new Point(i, i);
}
public static explicit operator int(Point p)
{
Console.WriteLine("(i)P");
return (p.x > p.y) ? p.x : p.y;
}
76
Type Conversion
Point a = new Point(10,20);
Console.WriteLine((Point)5); // (P)i <5,5>
Console.WriteLine(a + 5); // +(P,i) <15,25>
Console.WriteLine((int)a + 5); //(i)P 25
In case NO +(Point,int) and +(int,Point) operators :
Console.WriteLine((Point)5); // (P)i <5,5>
Console.WriteLine(a + 5); // (P)i <15,25>
Console.WriteLine((int)a + 5); // (i)P 25
77
C# and .NET
1. Introduction
2. C# versus Java : highlights
3. C# data types
4. Defining custom data types
5. Operator Overloading
6. Event driven programming
• delegates
• events
7. .NET Framework Class Library
8. A GUI in C#
9. A web service in C
78
Delegates[<attributes>][unsafe][<access modifiers>]
[new]delegate <return type> <delegate name>
(<parameter list>);
= type defining method signature
- instance can hold (list of) method(s) with matching signature
public delegate bool Filter(string s);
class Del{
public static void Main(){
String[] r = new String[] { "a fair Lady",
"the king and I", "hye buzz", "a beautiful mind",
"the zzz" };
Filter f=new Filter(StartWithA);
ArrayList a=Show(r,f);
Console.WriteLine("Starting with a :");
foreach (String s in a) Console.WriteLine(s);
f=new Filter(EndWithZ);
ArrayList z = Show(r, f);
Console.WriteLine("Ending with z :");
foreach (String s in z) Console.WriteLine(s);
}
//...
}
79
Delegatesclass Del
{
// ...
public static bool StartWithA(String s)
{
return s[0] == 'a';
}
public static bool EndWithZ(String s)
{
return s[s.Length-1] == 'z';
}
public static ArrayList Show(String[] s, Filter f)
{
ArrayList l = new ArrayList();
foreach(String i in s) if(f(i)) l.Add(i);
return l;
}
}
Starting with a :
a fair Lady
a beautiful mind
Ending with z :
hye buzz
the zzz
80
Multicast Delegates
Use operators += and -= to add/remove delegates to other delegate
if non-void : return value of last invocation is returned
public delegate void M(int i);
class Multi
{
// ...
public static void Print(int i)
{
Console.WriteLine("i = {0}",i);
}
public static void Sqrt(int i)
{
Console.WriteLine(Math.Sqrt(i));
}
public static void EndMessage(int i)
{
Console.WriteLine("Ending ...");
}
}
81
Multicast Delegates// public delegate void M(int i);
class Multi
{ // ...
public static void Main()
{
M m = null;
Console.WriteLine("----------------------------");
m += new M(Print);
m += new M(Sqrt);
m += new M(EndMessage);
m(12);
Console.WriteLine("----------------------------");
m += new M(Print);
m(16);
Console.WriteLine("----------------------------");
m -= new M(Sqrt);
m(25);
Console.WriteLine("----------------------------");
m -= new M(Print);
m(36);
Console.WriteLine("----------------------------");
}
}
-----------------
i = 12
3,46410161513775
Ending ...
-----------------
i = 16
4
Ending ...
i = 16
-----------------
i = 25
Ending ...
i = 25
-----------------
i = 36
Ending ...
-----------------
82
Multicast Delegates
From within object -> invoked on this-object
public delegate void F();
public class A
{ public F f;
private int i = 0;
public A(int i) {
this.i = i;
f=null;
f+=new F(Print);
f+=new F(Inc);
f+=new F(Print);
f+=new F(Dec);
f+=new F(Dec);
f+=new F(Print);
}
public void Inc() { i++; }
public void Dec() { i--; }
public void Print() {Console.WriteLine(this);}
public override string ToString(){return "<"+i+">";}
public void IncAndDec() {f();}
83
Multicast Delegates
From within object -> invoked on this-object
// ...
public static void Test() {
A a=new A(10);
a.IncAndDec();
a.f();
}
}
class MultiObj
{
public static void Main()
{
A.Test();
A a = new A(20);
a.f();
}
}
<10>
<11>
<9>
<9>
<10>
<8>
<20>
<21>
<19>
84
Delegate versus ...
Delegate vs. C function pointer
- type safe (unless in unsafe regions ...)
- can hold multiple methods to invoke
- can hold instance to invoke method upon
Delegate vs. Interface
- multiple methods to invoke
(could be implemented through list of
interface objects)
- any problem solved with delegates can be
solved using interface types
- “more elegant”
85
Delegate versus Inteface
interface IF
{
bool Filter(string s);
}
class StartWithAFilter : IF
{
public bool Filter(string s)
{
return s[0] == 'a';
}
}
class EndWithZFilter : IF
{
public bool Filter(string s)
{
return s[s.Length - 1] == 'z';
}
}
86
Delegate versus Inteface
class Test {
public static void Main()
{
String[] r = new String[] { "a very fair Lady",
"the king and a z", "hye buzzy",
"a beautiful mind for z", "the zzz" };
ArrayList a = Show(r, new StartWithAFilter());
Console.WriteLine("Starting with a :");
foreach (String s in a) Console.WriteLine(s);
ArrayList z = Show(r, new EndWithZFilter());
Console.WriteLine("Ending with z :");
foreach (String s in z) Console.WriteLine(s);
}
public static ArrayList Show(String[] s, IF f)
{
ArrayList l = new ArrayList();
foreach (String i in s) if (f.Filter(i)) l.Add(i);
return l;
}
}
Starting with a :
a very fair Lady
a beautiful mind for z
Ending with z :
the king and a z
a beautiful mind for z
the zzz
87
Events
A
B
events
- notification from A -> B
- WITHOUT calling directly method on B
use of intermediary
- event listeners + event handlers
- in C# : implemented through delegates
event
88
Events
A
B
event
Event Source
Event Sink
- delegate defined to fix handler signature
- source class declares ability to fire event
-> public (downcast) multicast delegate d
- delegates registered with d to get notified
- source class fires event by calling delegate d
d
Delegate
delegate
delegate
delegate
89
Events : Example
Customer arrives in business centre
-> generates event
-> interested parties are notified
Delegate conventions for eventing
- first argument : identifies source of event
- second argument : additional info
subclass of EventArgs
Example
- ID = object reference
- additional info :
- time of event
- urgency
90
Events : Example
Delegate signature
delegate void CustomerHandler(object s, CustomerArgs e)
public delegate void CustomerHandler(object o,CustomerArgs e);
enum Priority {LOW=0,NORMAL=1,HIGH=2};
class CustomerArgs : EventArgs
{
private DateTime d;
public Priority p;
public static Random r = new Random();
public DateTime Time
{
get { return d; }
}
public Priority Urgency
{
get {return p;}
}
public CustomerArgs()
{
d = DateTime.Now;
p=(Priority)(r.Next(3));
}
}
Preliminaries
• Delegate declaration
• Definition of event handler argument type
91
Events : Example
public class Customer
{
private string name;
public event CustomerHandler CustomerArrival;
public string Name
{
get { return name; }
}
public Customer(string n){name = n;}
public void arrive()
{
if (CustomerArrival != null)
{
CustomerArgs args = new CustomerArgs();
CustomerArrival(this, args); // fire the event;
}
}
public override string ToString(){return "<Customer : "+name+">";}
}
Event source class : Customer
• Declares event
• Listeners will register to event
• FIRES event when needed
92
Events : Example
class HotelService
{private string n;
public HotelService(string n) {this.n=n;}
public string Name{get{return n;}}
public void CustomerArrivalNotification(object o,CustomerArgs a) {
Console.WriteLine(this + " : guest " + (Customer)o +
" arrived at " + (a.Time)+"(Priority : "+a.Urgency+")");
}
public override string ToString()
{ return "Hotel service : "+n;
}
}
class HotelPersonnel
{private string n;
public HotelPersonnel(string n) {this.n=n;}
public string Name{get{return n;}}
public void CustomerArrivalNotification(object o,CustomerArgs a) {
Console.WriteLine(this + " : guest " + (Customer)o +
" arrived at" + (a.Time) + "(Priority : " + a.Urgency + ")");
}
public override string ToString()
{ return "Hotel personnel : "+n;
}
}
Event sink classes :
• HotelService
• HotelPersonnel
• declare a method conforming
to delegate signature
93
Events : Example
class CustomerApp {
public static void Main() {
Customer[] c=new Customer[] {new Customer("Bart De Poorter"),
new Customer("George Bush"),
new Customer("Condaleeza Rice"),
new Customer("Mahatma Ghandi")};
HotelService[] hs = new HotelService[] {
new HotelService("House keeping"),
new HotelService("Accounting"),
new HotelService("Reception") };
HotelPersonnel[] hp = new HotelPersonnel[] {
new HotelPersonnel("Manager"),
new HotelPersonnel("Mr. BigBoss (owner)") };
foreach(HotelService h in hs)
{
foreach(Customer cu in c)
cu.CustomerArrival+=
new CustomerHandler(h.CustomerArrivalNotification);
}
// ...
Main method
• instantiates simulation objects
• binds sinks to sources
94
Events : Example
// ...
foreach (HotelPersonnel h in hp)
{
c[1].CustomerArrival +=
new CustomerHandler(h.CustomerArrivalNotification);
c[2].CustomerArrival +=
new CustomerHandler(h.CustomerArrivalNotification);
}
Console.WriteLine("Starting simulation ----------------");
foreach (Customer cc in c)
{
cc.arrive();
try
{
System.Threading.Thread.Sleep(1000);
}
catch (System.Threading.ThreadInterruptedException e) { }
Console.WriteLine("---------------------");
}
}
}
95
Events : Example
Starting simulation ----------------
Hotel service : House keeping : guest <Customer : Bart De Poorter> arrived at 14/12/2005 9:57:06(Priority : NORMAL)
Hotel service : Accounting : guest <Customer : Bart De Poorter> arrived at 14/12/2005 9:57:06(Priority : NORMAL)
Hotel service : Reception : guest <Customer : Bart De Poorter> arrived at 14/12/2005 9:57:06(Priority : NORMAL)
---------------------
Hotel service : House keeping : guest <Customer : George Bush> arrived at 14/12/2005 9:57:07(Priority : LOW)
Hotel service : Accounting : guest <Customer : George Bush> arrived at 14/12/2005 9:57:07(Priority : LOW)
Hotel service : Reception : guest <Customer : George Bush> arrived at 14/12/2005 9:57:07(Priority : LOW)
Hotel personnel : Manager : guest <Customer : George Bush> arrived at14/12/2005 9:57:07(Priority : LOW)
Hotel personnel : Mr. BigBoss (owner) : guest <Customer : George Bush> arrived at 14/12/2005 9:57:07(Priority : LOW)
---------------------
Hotel service : House keeping : guest <Customer : Condaleeza Rice> arrived at 14/12/2005 9:57:08(Priority : NORMAL)
Hotel service : Accounting : guest <Customer : Condaleeza Rice> arrived at 14/12/2005 9:57:08(Priority : NORMAL)
Hotel service : Reception : guest <Customer : Condaleeza Rice> arrived at 14/12/2005 9:57:08(Priority : NORMAL)
Hotel personnel : Manager : guest <Customer : Condaleeza Rice> arrived at14/12/2005 9:57:08(Priority : NORMAL)
Hotel personnel : Mr. BigBoss (owner) : guest <Customer : Condaleeza Rice> arrived at14/12/2005 9:57:08(Priority : NORMAL)
---------------------
Hotel service : House keeping : guest <Customer : Mahatma Ghandi> arrived at 14/12/2005 9:57:09(Priority : HIGH)
Hotel service : Accounting : guest <Customer : Mahatma Ghandi> arrived at 14/12/2005 9:57:09(Priority : HIGH)
Hotel service : Reception : guest <Customer : Mahatma Ghandi> arrived at 14/12/2005 9:57:09(Priority : HIGH)
---------------------
96
C# and .NET
1. Introduction
2. C# versus Java : highlights
3. C# data types
4. Defining custom data types
5. Operator Overloading
6. Event driven programming
7. .NET Framework Class Library
8. A GUI in C#
9. A web service in C#
97
FCL
-CLS compliant set of managed type
- accessible from all .NET languages
- grouping (3542 types) :
- logically in namespaces (120)
- deployed as a set of assemblies (36) of .NET framework
System
- collection of core classes (Object, ValueType, Enum, Convert, Exception)
- core interfaces (ICloneable, IComparable, ...)
- time related classes (DateTime, TimeSpan)
- support for
- delegates
- mathematical operations
- custom attributes (Attribute)
- exception handling
- strings (String)
98
FCL
System.Text
- immutable string (System.String)
- mutable string (StringBuilder)
- regular expressions (System.Text.RegularExpressions)
C# string is alias for System.String
overloaded “==“ operator for equality check (NOT in Java !)
indexing strings : use normal indexing mechanism ([])
string a=“abcde”;
char c=a[2];
formatting strings (Format()-method)
format specifier string :
{ParamIndex[,MinWidth][:FormatString]}
e.g. “Value of account {0} is {1:C}” (C -> “Currency”)
99
FCL
System.Collections
- Java-like set of interfaces and classes, implementing popular
data structures (ArrayList, Queue, Stack, BitArray, ...)
- System.Array is base type for all array types
- generics as of .NET v 2.0 (System.Collections.Generics)
to iterate over Collection :
- Collection implements IEnumerable
public interface IEnumerable {
IEnumerator GetEnumerator();
}
- iterator implements IEnumerator
public interface IEnumerator {
bool MoveNext();
object Current {get;}
void Reset();
}
- also : foreach idiom can be used
100
FCL
iterator for Dictionary (Java Map)
public interface IDectionaryEnumerator : IEnumerator {
DictionaryEntry Entry {get;}
object Key {get;}
object Value {get;}
}
IEnumerable
ICollection
IList
IDictionary
get iterator
support for counting
converting to array
indexed collection
101
FCLclass Array : ICollection, IEnumerable, IList
fixed size indexed array
class ArrayList : IList
dynamically sized array
class Hashtable : IDictionary
standard dictionary key/value pairs
hash computed using GetHashCode() method
-> should be overridden
class Queue
FIFO data structure
methods to queue and dequeue
class Stack
LIFO data structure
key methods : push and pop
102
FCL
class Bitarray
compressed form of bool[] (one bit per boolean)
class SortedList : IDictionary
sorted to increase lookup efficiency
(binary search instead of linear search)
class StringCollection : ICollection
special purpose collection for storing strings
class StringDictionary : IEnumerable
idem for storing string maps
103
FCL : Examplespublic static void Print(ICollection c)
{
int j = 0;
foreach(object i in c)
Console.WriteLine("{0} -> {1}",j++,i);
Console.WriteLine("--------------------");
}
ArrayList al = new ArrayList();
al.Add("Wim");
al.Add("Ann");
al.Add("Bram");
al.Add("Bart");
al.Add("Greet");
Print(al);
al.Sort();
Print(al);
Console.WriteLine(al[1]);
al[1] = "BART";
Print(al);
0 -> Wim
1 -> Ann
2 -> Bram
3 -> Bart
4 -> Greet
--------------------
0 -> Ann
1 -> Bart
2 -> Bram
3 -> Greet
4 -> Wim
--------------------
Bart
0 -> Ann
1 -> BART
2 -> Bram
3 -> Greet
4 -> Wim
--------------------
104
FCL : ExamplesHashtable h = new Hashtable();
h["Wim"] = "onetwothree";
h["Bram"] = "123";
h["Greet"] = "Da Vinci";
h["Ann"] = "My fair lady";
Console.WriteLine(h["Bram"]); // 123
Queue q = new Queue();
Stack s = new Stack();
int[] a ={ 1, 2, 3, 4 };
foreach (int i in a) {q.Enqueue(i); s.Push(i);}
Print(q);
Print(s);
Console.WriteLine(q.Dequeue());
Console.WriteLine(s.Pop());
Print(q);
Print(s);
123
0 -> 1
1 -> 2
2 -> 3
3 -> 4
--------------------
0 -> 4
1 -> 3
2 -> 2
3 -> 1
--------------------
1
4
0 -> 2
1 -> 3
2 -> 4
--------------------
0 -> 3
1 -> 2
2 -> 1
--------------------
105
FCL : SortingTwo options :
- object ordering implemented in the class itself
public interface IComparable {
int CompareTo(object o);
}
- delegate ordering to special object
public interface IComparer {
int Compare(object o1,object o2);
}
comparing must follow special contract
1. if a comes before b -> a.CompareTo(b)<0
2. if a is equal to b -> a.CompareTo(b) == 0
3. if a comes after b -> a.CompareTo(b)>0
4. null first -> a.CompareTo(null)>0
5. a.CompareTo(b) -> a.GetType() == b.GetType()
106
FCL
System.IO
- standard in, out and error stream
- binary and text file I/O
- registering/notification of filesystem events
- access of user specific secure storage (“Isolated Storage”)
- System.Console
- System.IO.IsolatedStorage
System.Net
- classes for network communication
- raw socket access, TCP, UDP sockets
- HTTP support
- System.Net
- System.Net.Sockets
- System.IO.Stream
107
FCL
System.Security
- security policies, principals, permission sets, evidence
(authentication, key, ...)
- cryptographic library
System.Threading
- support for thread management and pool management
- synchronization mechanisms
- locks (monitor): serialized access
- pulse/wait : notify waiting threads
- System.Timers
- System.Thread
108
FCL
System.Reflection
- retrieve type information (methods, class names, signatures, ...)
at runtime
- retrieve (custom) attributes at runtime
-> for each custom attribute :
- CLR creates object
- retrieved using reflection interface
- retrieve metadata at runtime
- assembly info (version, target OS, ...)
- data to create custom attributes stored as metadata
109
FCL
System.Runtime.Serialization
- write object graph to/from stream (file or network)
- default serializers : XML and binary
- serializability : use non-custom attribute [Serializable]
- System.SerializableAttribute
- System.NonSerializableAttribute
System.Runtime.Remoting
- distributed object model of .NET
- calls can be : synchronous, asynchronous, one-way
- transport protocol : TCP, HTTP or SMTP
- format : binary or SOAP
- naming service, activation service, marshalling, messaging
110
FCL
System.Web.Services
- in fact part of ASP.NET (not part of CLR)
- describe, discover and publish web services
System.Data
- known as ADO.NET
- classes to support database access
System.Xml
- schemas, namespaces, parsing (DOM,SAX)
- implementation of XSLT, XPath, SOAP1.1
111
FCL
System.Drawing
- support for graphics
- known as GDI+
- brushes, fonts, bitmaps, rendering, drawing primitives, ...
System.Windows.Forms
- Rich client applications (“classic GUIs”)
- known as “Windows Forms”
- forms package, GUI components and RAD component model
System.Web
- Thin client applications
- known as “Web Forms”
- server side package creates HTML UI
- support for session management (state), security, deployment, ...
- part of ASP.NET
112
FCL
System.Globalization
- date/time conversions
- string adaptation to locale
- resource file to centralize locale data
System.Configuration
- per user, per application configuration management
System.EnterpriseServices
- advanced services
- distributed transaction, object pooling, queuing, event handling
- reliable asynchronous messaging
- access to directory service
113
C# and .NET
1. Introduction
2. C# versus Java : highlights
3. C# data types
4. Defining custom data types
5. Operator Overloading
6. Event driven programming
7. .NET Framework Class Library
8. A GUI in C#
9. A web service in C#
114
GUIs in .NET
- heavily uses delegates
- event subscription
- event notification
- Visual Studio .NET contains IDE to assist GUI development
- choose New Project -> “Windows Application”
(instead of “Console Application”)
- Add WinForms as needed
- Drop components from ToolBox on each form
- Change component state in IDE generated code
- Code event handlers
115
Example : incrementor
System.Windows.Forms.Button
declares properties : Name, Text
fires events :
System.EventHandler Click
System.Windows.Forms.TextBox
declares properties : Name, Text
System.Windows.Forms.Form
declares properties :
Name, Text
Controls (container)
fires events :
System.EventHandler Load
116
Example : incrementor
Main()-method
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace WindowsApplication1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
IDE-generated
[Program.cs]
117
Example : incrementor
Form1-class
namespace WindowsApplication1
{
partial class Form1 {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources
/// should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
IDE-generated
(edited)
[Form1.Designer.cs]
118
Example : incrementor
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(92, 150);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "Click here";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
IDE-generated
(edited)
[Form1.Designer.cs]
Form1-class
119
Example : incrementor
Form1-class
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(78, 103);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(100, 20);
this.textBox1.TabIndex = 1;
this.textBox1.TextChanged +=
new System.EventHandler(this.textBox1_TextChanged);
IDE-generated
(edited)
[Form1.Designer.cs]
120
Example : incrementor
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Incrementer";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox textBox1;
}
}
IDE-generated
(edited)
[Form1.Designer.cs]
Form1-class
121
Example : incrementor
namespace WindowsApplication1
{ public partial class Form1 : Form
{
int i = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e){}
private void button1_Click(object sender, EventArgs e)
{
i++;
textBox1.Text = ""+i;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
template IDE-generated
handler code to add !
[Form1.cs]
Form1-class
122
C# and .NET
1. Introduction
2. C# versus Java : highlights
3. C# data types
4. Defining custom data types
5. Operator Overloading
6. Event driven programming
7. .NET Framework Class Library
8. A GUI in C#
9. A web service in C#
123
.NET / C# web service
- actually part of ASP.NET
- uses .asmx file to bind server to code
- C# :
- web service derives from System.Web.Services.WebService
- class must be public, must have public constructor
- has [WebService] attribute
paramters :
- Description : info
- Name : default = class name
- Namespace : XML-namespace
- every exposed service method should have attribute
[WebMethod]
parameters include :
-Description : info
-EnableSession : default = false
- MessageName : default = method name
124
.NET / C# web service
web server
- runs .asmx -file
- locates class files referred
- loads, runs and manages code
client
- statically retrieves WSDL document
- generates and compiles proxy class
- instantiates service proxy
- call methods on the proxy
125
Hello Service
Server side
Create ASP.NET Web Service project
File -> New -> Web Site
ASP.NET Web Service template
Edit [WebService] attribute (if necessary)
Add class logic, give any WS method [WebMethod] attribute
Build project
Run Project
Check if service is running (WSDL-file)
http://localhost:1665/WebSite1/?.asmx ? WSDL
Invoke method from browser to check proper functioning
126
Hello Service
Service.asmx
<%@ WebService Language="C#"
CodeBehind="~/App_Code/Service.cs"
Class="Service" %>
127
Hello Service
Service.cs
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
public Service () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld(string e) {
return "Hello World there, "+e;
}
}
128
Hello Service
WSDL (http://localhost:1655/WebSite1/Service.asmx?WSDL)
129
Hello ServiceService invocation from browser
(http://localhost:1655/WebSite1/Service.asmx?op=HelloWorld)
Answer :
<string>Hello World there, MyName</string>
130
Hello Service
Client side
Create Windows Console project (or GUI project ...)
Open WS project and add to current solution
Add Web Reference
-> Browse local host
-> Select Web Reference (= namespace for proxy)
(Here : HelloService)
Add client code
-> instantiate proxy object
-> call WS methods on proxy
131
Hello Service
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
HelloService.Service s = new HelloService.Service();
Console.WriteLine(" -> " + s.HelloWorld("Georgie "));
}
}
}
-> Hello World there, Georgie
Press any key to continue . . .

Más contenido relacionado

La actualidad más candente

C# Language Overview Part I
C# Language Overview Part IC# Language Overview Part I
C# Language Overview Part IDoncho Minkov
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Chris Adamson
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling Intro C# Book
 
03. Operators Expressions and statements
03. Operators Expressions and statements03. Operators Expressions and statements
03. Operators Expressions and statementsIntro C# Book
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingRasan Samarasinghe
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm ComplexityIntro C# Book
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language Mohamed Loey
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Languagemspline
 
Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1Ali Aminian
 
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NETRasan Samarasinghe
 
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++Mihai Todor
 

La actualidad más candente (20)

C# Language Overview Part I
C# Language Overview Part IC# Language Overview Part I
C# Language Overview Part I
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
 
03. Operators Expressions and statements
03. Operators Expressions and statements03. Operators Expressions and statements
03. Operators Expressions and statements
 
Primitive Data Types and Variables Lesson 02
Primitive Data Types and Variables Lesson 02Primitive Data Types and Variables Lesson 02
Primitive Data Types and Variables Lesson 02
 
C# overview part 1
C# overview part 1C# overview part 1
C# overview part 1
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
Introduction To C#
Introduction To C#Introduction To C#
Introduction To C#
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Language
 
Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1
 
09. Methods
09. Methods09. Methods
09. Methods
 
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NET
 
Modern C++
Modern C++Modern C++
Modern C++
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++
 

Destacado

C#のすばらしさを語る会用
C#のすばらしさを語る会用C#のすばらしさを語る会用
C#のすばらしさを語る会用Hideaki Kazaoka
 
C# .net lecture 3 objects 3
C# .net lecture 3 objects 3C# .net lecture 3 objects 3
C# .net lecture 3 objects 3Doron Raifman
 
.NET Gadgeteerで組み込み開発の第一歩
.NET Gadgeteerで組み込み開発の第一歩.NET Gadgeteerで組み込み開発の第一歩
.NET Gadgeteerで組み込み開発の第一歩Yoshitaka Seo
 
กำหนดค่า Link label
กำหนดค่า Link labelกำหนดค่า Link label
กำหนดค่า Link labelNaruemon Soonthong
 
C# Basics Quick Reference Sheet
C# Basics Quick Reference SheetC# Basics Quick Reference Sheet
C# Basics Quick Reference SheetFrescatiStory
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingabhay singh
 
C# quick ref (bruce 2016)
C# quick ref (bruce 2016)C# quick ref (bruce 2016)
C# quick ref (bruce 2016)Bruce Hantover
 
Setup Project in Visual Studio C#
Setup Project in Visual Studio C#Setup Project in Visual Studio C#
Setup Project in Visual Studio C#Naruemon Soonthong
 
Windows Forms For Beginners Part - 4
Windows Forms For Beginners Part - 4Windows Forms For Beginners Part - 4
Windows Forms For Beginners Part - 4Bhushan Mulmule
 
Windows Forms For Beginners Part - 2
Windows Forms For Beginners Part - 2Windows Forms For Beginners Part - 2
Windows Forms For Beginners Part - 2Bhushan Mulmule
 
C# Cheat Sheet
C# Cheat SheetC# Cheat Sheet
C# Cheat SheetGlowTouch
 
06 win forms
06 win forms06 win forms
06 win formsmrjw
 
Visula C# Programming Lecture 1
Visula C# Programming Lecture 1Visula C# Programming Lecture 1
Visula C# Programming Lecture 1Abou Bakr Ashraf
 
Presentation on overloading
Presentation on overloading Presentation on overloading
Presentation on overloading Charndeep Sekhon
 

Destacado (17)

C#のすばらしさを語る会用
C#のすばらしさを語る会用C#のすばらしさを語る会用
C#のすばらしさを語る会用
 
C# .net lecture 3 objects 3
C# .net lecture 3 objects 3C# .net lecture 3 objects 3
C# .net lecture 3 objects 3
 
.NET Gadgeteerで組み込み開発の第一歩
.NET Gadgeteerで組み込み開発の第一歩.NET Gadgeteerで組み込み開発の第一歩
.NET Gadgeteerで組み込み開発の第一歩
 
กำหนดค่า Link label
กำหนดค่า Link labelกำหนดค่า Link label
กำหนดค่า Link label
 
C# Basics Quick Reference Sheet
C# Basics Quick Reference SheetC# Basics Quick Reference Sheet
C# Basics Quick Reference Sheet
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
C# quick ref (bruce 2016)
C# quick ref (bruce 2016)C# quick ref (bruce 2016)
C# quick ref (bruce 2016)
 
Setup Project in Visual Studio C#
Setup Project in Visual Studio C#Setup Project in Visual Studio C#
Setup Project in Visual Studio C#
 
Windows Forms For Beginners Part - 4
Windows Forms For Beginners Part - 4Windows Forms For Beginners Part - 4
Windows Forms For Beginners Part - 4
 
Windows Forms For Beginners Part - 2
Windows Forms For Beginners Part - 2Windows Forms For Beginners Part - 2
Windows Forms For Beginners Part - 2
 
C# Cheat Sheet
C# Cheat SheetC# Cheat Sheet
C# Cheat Sheet
 
06 win forms
06 win forms06 win forms
06 win forms
 
7.data types in c#
7.data types in c#7.data types in c#
7.data types in c#
 
Visula C# Programming Lecture 1
Visula C# Programming Lecture 1Visula C# Programming Lecture 1
Visula C# Programming Lecture 1
 
Windowforms controls c#
Windowforms controls c#Windowforms controls c#
Windowforms controls c#
 
C# basics
 C# basics C# basics
C# basics
 
Presentation on overloading
Presentation on overloading Presentation on overloading
Presentation on overloading
 

Similar a C# and .NET Framework Overview

Dr archana dhawan bajaj - csharp fundamentals slides
Dr archana dhawan bajaj - csharp fundamentals slidesDr archana dhawan bajaj - csharp fundamentals slides
Dr archana dhawan bajaj - csharp fundamentals slidesDr-archana-dhawan-bajaj
 
Introduction to c_plus_plus
Introduction to c_plus_plusIntroduction to c_plus_plus
Introduction to c_plus_plusSayed Ahmed
 
Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Sayed Ahmed
 
Introduction to-csharp
Introduction to-csharpIntroduction to-csharp
Introduction to-csharpSDFG5
 
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...NALESVPMEngg
 
Introduction-to-Csharp.ppt
Introduction-to-Csharp.pptIntroduction-to-Csharp.ppt
Introduction-to-Csharp.pptAlmamoon
 
Introduction-to-Csharp.ppt
Introduction-to-Csharp.pptIntroduction-to-Csharp.ppt
Introduction-to-Csharp.pptmothertheressa
 
The Ring programming language version 1.10 book - Part 102 of 212
The Ring programming language version 1.10 book - Part 102 of 212The Ring programming language version 1.10 book - Part 102 of 212
The Ring programming language version 1.10 book - Part 102 of 212Mahmoud Samir Fayed
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharpsarfarazali
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#singhadarsh
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojureAbbas Raza
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharpg_hemanth17
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Sachin Singh
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharpRaga Vahini
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharpSatish Verma
 

Similar a C# and .NET Framework Overview (20)

Dr archana dhawan bajaj - csharp fundamentals slides
Dr archana dhawan bajaj - csharp fundamentals slidesDr archana dhawan bajaj - csharp fundamentals slides
Dr archana dhawan bajaj - csharp fundamentals slides
 
C# for Java Developers
C# for Java DevelopersC# for Java Developers
C# for Java Developers
 
Apache Thrift
Apache ThriftApache Thrift
Apache Thrift
 
Next .NET and C#
Next .NET and C#Next .NET and C#
Next .NET and C#
 
Return of c++
Return of c++Return of c++
Return of c++
 
Introduction to c_plus_plus
Introduction to c_plus_plusIntroduction to c_plus_plus
Introduction to c_plus_plus
 
Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)
 
Introduction to-csharp
Introduction to-csharpIntroduction to-csharp
Introduction to-csharp
 
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
 
Introduction-to-Csharp.ppt
Introduction-to-Csharp.pptIntroduction-to-Csharp.ppt
Introduction-to-Csharp.ppt
 
Introduction-to-Csharp.ppt
Introduction-to-Csharp.pptIntroduction-to-Csharp.ppt
Introduction-to-Csharp.ppt
 
XAML/C# to HTML/JS
XAML/C# to HTML/JSXAML/C# to HTML/JS
XAML/C# to HTML/JS
 
The Ring programming language version 1.10 book - Part 102 of 212
The Ring programming language version 1.10 book - Part 102 of 212The Ring programming language version 1.10 book - Part 102 of 212
The Ring programming language version 1.10 book - Part 102 of 212
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 

Más de Dr-archana-dhawan-bajaj

Dr archana dhawan bajaj - member practice-2013 2015
Dr archana dhawan bajaj - member practice-2013 2015Dr archana dhawan bajaj - member practice-2013 2015
Dr archana dhawan bajaj - member practice-2013 2015Dr-archana-dhawan-bajaj
 
Dr archana dhawan bajaj - mba guide-list_2012
Dr archana dhawan bajaj - mba guide-list_2012Dr archana dhawan bajaj - mba guide-list_2012
Dr archana dhawan bajaj - mba guide-list_2012Dr-archana-dhawan-bajaj
 
Dr archana dhawan bajaj eol ir-deb_file_07a
Dr archana dhawan bajaj   eol ir-deb_file_07aDr archana dhawan bajaj   eol ir-deb_file_07a
Dr archana dhawan bajaj eol ir-deb_file_07aDr-archana-dhawan-bajaj
 
Dr archana dhawan bajaj - electoral roll
Dr archana dhawan bajaj - electoral rollDr archana dhawan bajaj - electoral roll
Dr archana dhawan bajaj - electoral rollDr-archana-dhawan-bajaj
 
Dr archana dhawan bajaj - cognizant combined campus - list of selected students
Dr archana dhawan bajaj - cognizant combined campus - list of selected studentsDr archana dhawan bajaj - cognizant combined campus - list of selected students
Dr archana dhawan bajaj - cognizant combined campus - list of selected studentsDr-archana-dhawan-bajaj
 
Dr archana dhawan bajaj - cause lifefile-jigj96f5
Dr archana dhawan bajaj - cause lifefile-jigj96f5Dr archana dhawan bajaj - cause lifefile-jigj96f5
Dr archana dhawan bajaj - cause lifefile-jigj96f5Dr-archana-dhawan-bajaj
 

Más de Dr-archana-dhawan-bajaj (8)

Dr archana dhawan bajaj - member practice-2013 2015
Dr archana dhawan bajaj - member practice-2013 2015Dr archana dhawan bajaj - member practice-2013 2015
Dr archana dhawan bajaj - member practice-2013 2015
 
Dr archana dhawan bajaj - mba guide-list_2012
Dr archana dhawan bajaj - mba guide-list_2012Dr archana dhawan bajaj - mba guide-list_2012
Dr archana dhawan bajaj - mba guide-list_2012
 
Dr archana dhawan bajaj - list1
Dr archana dhawan bajaj - list1Dr archana dhawan bajaj - list1
Dr archana dhawan bajaj - list1
 
Dr archana dhawan bajaj final45
Dr archana dhawan bajaj   final45Dr archana dhawan bajaj   final45
Dr archana dhawan bajaj final45
 
Dr archana dhawan bajaj eol ir-deb_file_07a
Dr archana dhawan bajaj   eol ir-deb_file_07aDr archana dhawan bajaj   eol ir-deb_file_07a
Dr archana dhawan bajaj eol ir-deb_file_07a
 
Dr archana dhawan bajaj - electoral roll
Dr archana dhawan bajaj - electoral rollDr archana dhawan bajaj - electoral roll
Dr archana dhawan bajaj - electoral roll
 
Dr archana dhawan bajaj - cognizant combined campus - list of selected students
Dr archana dhawan bajaj - cognizant combined campus - list of selected studentsDr archana dhawan bajaj - cognizant combined campus - list of selected students
Dr archana dhawan bajaj - cognizant combined campus - list of selected students
 
Dr archana dhawan bajaj - cause lifefile-jigj96f5
Dr archana dhawan bajaj - cause lifefile-jigj96f5Dr archana dhawan bajaj - cause lifefile-jigj96f5
Dr archana dhawan bajaj - cause lifefile-jigj96f5
 

Último

Call Girls Jp Nagar Just Call 7001305949 Top Class Call Girl Service Available
Call Girls Jp Nagar Just Call 7001305949 Top Class Call Girl Service AvailableCall Girls Jp Nagar Just Call 7001305949 Top Class Call Girl Service Available
Call Girls Jp Nagar Just Call 7001305949 Top Class Call Girl Service Availablenarwatsonia7
 
Call Girl Koramangala | 7001305949 At Low Cost Cash Payment Booking
Call Girl Koramangala | 7001305949 At Low Cost Cash Payment BookingCall Girl Koramangala | 7001305949 At Low Cost Cash Payment Booking
Call Girl Koramangala | 7001305949 At Low Cost Cash Payment Bookingnarwatsonia7
 
Aspirin presentation slides by Dr. Rewas Ali
Aspirin presentation slides by Dr. Rewas AliAspirin presentation slides by Dr. Rewas Ali
Aspirin presentation slides by Dr. Rewas AliRewAs ALI
 
Artifacts in Nuclear Medicine with Identifying and resolving artifacts.
Artifacts in Nuclear Medicine with Identifying and resolving artifacts.Artifacts in Nuclear Medicine with Identifying and resolving artifacts.
Artifacts in Nuclear Medicine with Identifying and resolving artifacts.MiadAlsulami
 
Call Girls Electronic City Just Call 7001305949 Top Class Call Girl Service A...
Call Girls Electronic City Just Call 7001305949 Top Class Call Girl Service A...Call Girls Electronic City Just Call 7001305949 Top Class Call Girl Service A...
Call Girls Electronic City Just Call 7001305949 Top Class Call Girl Service A...narwatsonia7
 
Book Call Girls in Kasavanahalli - 7001305949 with real photos and phone numbers
Book Call Girls in Kasavanahalli - 7001305949 with real photos and phone numbersBook Call Girls in Kasavanahalli - 7001305949 with real photos and phone numbers
Book Call Girls in Kasavanahalli - 7001305949 with real photos and phone numbersnarwatsonia7
 
Call Girls Frazer Town Just Call 7001305949 Top Class Call Girl Service Avail...
Call Girls Frazer Town Just Call 7001305949 Top Class Call Girl Service Avail...Call Girls Frazer Town Just Call 7001305949 Top Class Call Girl Service Avail...
Call Girls Frazer Town Just Call 7001305949 Top Class Call Girl Service Avail...narwatsonia7
 
High Profile Call Girls Jaipur Vani 8445551418 Independent Escort Service Jaipur
High Profile Call Girls Jaipur Vani 8445551418 Independent Escort Service JaipurHigh Profile Call Girls Jaipur Vani 8445551418 Independent Escort Service Jaipur
High Profile Call Girls Jaipur Vani 8445551418 Independent Escort Service Jaipurparulsinha
 
See the 2,456 pharmacies on the National E-Pharmacy Platform
See the 2,456 pharmacies on the National E-Pharmacy PlatformSee the 2,456 pharmacies on the National E-Pharmacy Platform
See the 2,456 pharmacies on the National E-Pharmacy PlatformKweku Zurek
 
Call Girls Kanakapura Road Just Call 7001305949 Top Class Call Girl Service A...
Call Girls Kanakapura Road Just Call 7001305949 Top Class Call Girl Service A...Call Girls Kanakapura Road Just Call 7001305949 Top Class Call Girl Service A...
Call Girls Kanakapura Road Just Call 7001305949 Top Class Call Girl Service A...narwatsonia7
 
call girls in Connaught Place DELHI 🔝 >༒9540349809 🔝 genuine Escort Service ...
call girls in Connaught Place  DELHI 🔝 >༒9540349809 🔝 genuine Escort Service ...call girls in Connaught Place  DELHI 🔝 >༒9540349809 🔝 genuine Escort Service ...
call girls in Connaught Place DELHI 🔝 >༒9540349809 🔝 genuine Escort Service ...saminamagar
 
Call Girls Hebbal Just Call 7001305949 Top Class Call Girl Service Available
Call Girls Hebbal Just Call 7001305949 Top Class Call Girl Service AvailableCall Girls Hebbal Just Call 7001305949 Top Class Call Girl Service Available
Call Girls Hebbal Just Call 7001305949 Top Class Call Girl Service Availablenarwatsonia7
 
Ahmedabad Call Girls CG Road 🔝9907093804 Short 1500 💋 Night 6000
Ahmedabad Call Girls CG Road 🔝9907093804  Short 1500  💋 Night 6000Ahmedabad Call Girls CG Road 🔝9907093804  Short 1500  💋 Night 6000
Ahmedabad Call Girls CG Road 🔝9907093804 Short 1500 💋 Night 6000aliya bhat
 
Asthma Review - GINA guidelines summary 2024
Asthma Review - GINA guidelines summary 2024Asthma Review - GINA guidelines summary 2024
Asthma Review - GINA guidelines summary 2024Gabriel Guevara MD
 
Call Girls Whitefield Just Call 7001305949 Top Class Call Girl Service Available
Call Girls Whitefield Just Call 7001305949 Top Class Call Girl Service AvailableCall Girls Whitefield Just Call 7001305949 Top Class Call Girl Service Available
Call Girls Whitefield Just Call 7001305949 Top Class Call Girl Service Availablenarwatsonia7
 
Low Rate Call Girls Mumbai Suman 9910780858 Independent Escort Service Mumbai
Low Rate Call Girls Mumbai Suman 9910780858 Independent Escort Service MumbaiLow Rate Call Girls Mumbai Suman 9910780858 Independent Escort Service Mumbai
Low Rate Call Girls Mumbai Suman 9910780858 Independent Escort Service Mumbaisonalikaur4
 
Russian Call Girls Chickpet - 7001305949 Booking and charges genuine rate for...
Russian Call Girls Chickpet - 7001305949 Booking and charges genuine rate for...Russian Call Girls Chickpet - 7001305949 Booking and charges genuine rate for...
Russian Call Girls Chickpet - 7001305949 Booking and charges genuine rate for...narwatsonia7
 
VIP Call Girls Lucknow Nandini 7001305949 Independent Escort Service Lucknow
VIP Call Girls Lucknow Nandini 7001305949 Independent Escort Service LucknowVIP Call Girls Lucknow Nandini 7001305949 Independent Escort Service Lucknow
VIP Call Girls Lucknow Nandini 7001305949 Independent Escort Service Lucknownarwatsonia7
 
Bangalore Call Girls Marathahalli 📞 9907093804 High Profile Service 100% Safe
Bangalore Call Girls Marathahalli 📞 9907093804 High Profile Service 100% SafeBangalore Call Girls Marathahalli 📞 9907093804 High Profile Service 100% Safe
Bangalore Call Girls Marathahalli 📞 9907093804 High Profile Service 100% Safenarwatsonia7
 
Call Girls Thane Just Call 9910780858 Get High Class Call Girls Service
Call Girls Thane Just Call 9910780858 Get High Class Call Girls ServiceCall Girls Thane Just Call 9910780858 Get High Class Call Girls Service
Call Girls Thane Just Call 9910780858 Get High Class Call Girls Servicesonalikaur4
 

Último (20)

Call Girls Jp Nagar Just Call 7001305949 Top Class Call Girl Service Available
Call Girls Jp Nagar Just Call 7001305949 Top Class Call Girl Service AvailableCall Girls Jp Nagar Just Call 7001305949 Top Class Call Girl Service Available
Call Girls Jp Nagar Just Call 7001305949 Top Class Call Girl Service Available
 
Call Girl Koramangala | 7001305949 At Low Cost Cash Payment Booking
Call Girl Koramangala | 7001305949 At Low Cost Cash Payment BookingCall Girl Koramangala | 7001305949 At Low Cost Cash Payment Booking
Call Girl Koramangala | 7001305949 At Low Cost Cash Payment Booking
 
Aspirin presentation slides by Dr. Rewas Ali
Aspirin presentation slides by Dr. Rewas AliAspirin presentation slides by Dr. Rewas Ali
Aspirin presentation slides by Dr. Rewas Ali
 
Artifacts in Nuclear Medicine with Identifying and resolving artifacts.
Artifacts in Nuclear Medicine with Identifying and resolving artifacts.Artifacts in Nuclear Medicine with Identifying and resolving artifacts.
Artifacts in Nuclear Medicine with Identifying and resolving artifacts.
 
Call Girls Electronic City Just Call 7001305949 Top Class Call Girl Service A...
Call Girls Electronic City Just Call 7001305949 Top Class Call Girl Service A...Call Girls Electronic City Just Call 7001305949 Top Class Call Girl Service A...
Call Girls Electronic City Just Call 7001305949 Top Class Call Girl Service A...
 
Book Call Girls in Kasavanahalli - 7001305949 with real photos and phone numbers
Book Call Girls in Kasavanahalli - 7001305949 with real photos and phone numbersBook Call Girls in Kasavanahalli - 7001305949 with real photos and phone numbers
Book Call Girls in Kasavanahalli - 7001305949 with real photos and phone numbers
 
Call Girls Frazer Town Just Call 7001305949 Top Class Call Girl Service Avail...
Call Girls Frazer Town Just Call 7001305949 Top Class Call Girl Service Avail...Call Girls Frazer Town Just Call 7001305949 Top Class Call Girl Service Avail...
Call Girls Frazer Town Just Call 7001305949 Top Class Call Girl Service Avail...
 
High Profile Call Girls Jaipur Vani 8445551418 Independent Escort Service Jaipur
High Profile Call Girls Jaipur Vani 8445551418 Independent Escort Service JaipurHigh Profile Call Girls Jaipur Vani 8445551418 Independent Escort Service Jaipur
High Profile Call Girls Jaipur Vani 8445551418 Independent Escort Service Jaipur
 
See the 2,456 pharmacies on the National E-Pharmacy Platform
See the 2,456 pharmacies on the National E-Pharmacy PlatformSee the 2,456 pharmacies on the National E-Pharmacy Platform
See the 2,456 pharmacies on the National E-Pharmacy Platform
 
Call Girls Kanakapura Road Just Call 7001305949 Top Class Call Girl Service A...
Call Girls Kanakapura Road Just Call 7001305949 Top Class Call Girl Service A...Call Girls Kanakapura Road Just Call 7001305949 Top Class Call Girl Service A...
Call Girls Kanakapura Road Just Call 7001305949 Top Class Call Girl Service A...
 
call girls in Connaught Place DELHI 🔝 >༒9540349809 🔝 genuine Escort Service ...
call girls in Connaught Place  DELHI 🔝 >༒9540349809 🔝 genuine Escort Service ...call girls in Connaught Place  DELHI 🔝 >༒9540349809 🔝 genuine Escort Service ...
call girls in Connaught Place DELHI 🔝 >༒9540349809 🔝 genuine Escort Service ...
 
Call Girls Hebbal Just Call 7001305949 Top Class Call Girl Service Available
Call Girls Hebbal Just Call 7001305949 Top Class Call Girl Service AvailableCall Girls Hebbal Just Call 7001305949 Top Class Call Girl Service Available
Call Girls Hebbal Just Call 7001305949 Top Class Call Girl Service Available
 
Ahmedabad Call Girls CG Road 🔝9907093804 Short 1500 💋 Night 6000
Ahmedabad Call Girls CG Road 🔝9907093804  Short 1500  💋 Night 6000Ahmedabad Call Girls CG Road 🔝9907093804  Short 1500  💋 Night 6000
Ahmedabad Call Girls CG Road 🔝9907093804 Short 1500 💋 Night 6000
 
Asthma Review - GINA guidelines summary 2024
Asthma Review - GINA guidelines summary 2024Asthma Review - GINA guidelines summary 2024
Asthma Review - GINA guidelines summary 2024
 
Call Girls Whitefield Just Call 7001305949 Top Class Call Girl Service Available
Call Girls Whitefield Just Call 7001305949 Top Class Call Girl Service AvailableCall Girls Whitefield Just Call 7001305949 Top Class Call Girl Service Available
Call Girls Whitefield Just Call 7001305949 Top Class Call Girl Service Available
 
Low Rate Call Girls Mumbai Suman 9910780858 Independent Escort Service Mumbai
Low Rate Call Girls Mumbai Suman 9910780858 Independent Escort Service MumbaiLow Rate Call Girls Mumbai Suman 9910780858 Independent Escort Service Mumbai
Low Rate Call Girls Mumbai Suman 9910780858 Independent Escort Service Mumbai
 
Russian Call Girls Chickpet - 7001305949 Booking and charges genuine rate for...
Russian Call Girls Chickpet - 7001305949 Booking and charges genuine rate for...Russian Call Girls Chickpet - 7001305949 Booking and charges genuine rate for...
Russian Call Girls Chickpet - 7001305949 Booking and charges genuine rate for...
 
VIP Call Girls Lucknow Nandini 7001305949 Independent Escort Service Lucknow
VIP Call Girls Lucknow Nandini 7001305949 Independent Escort Service LucknowVIP Call Girls Lucknow Nandini 7001305949 Independent Escort Service Lucknow
VIP Call Girls Lucknow Nandini 7001305949 Independent Escort Service Lucknow
 
Bangalore Call Girls Marathahalli 📞 9907093804 High Profile Service 100% Safe
Bangalore Call Girls Marathahalli 📞 9907093804 High Profile Service 100% SafeBangalore Call Girls Marathahalli 📞 9907093804 High Profile Service 100% Safe
Bangalore Call Girls Marathahalli 📞 9907093804 High Profile Service 100% Safe
 
Call Girls Thane Just Call 9910780858 Get High Class Call Girls Service
Call Girls Thane Just Call 9910780858 Get High Class Call Girls ServiceCall Girls Thane Just Call 9910780858 Get High Class Call Girls Service
Call Girls Thane Just Call 9910780858 Get High Class Call Girls Service
 

C# and .NET Framework Overview

  • 1. 1 1. Introduction 2. C# versus Java : highlights 3. C# data types 4. Defining custom data types 5. Operator Overloading 6. Event driven programming 7. .NET Framework Class Library 8. A GUI in C# 9. A web service in C#
  • 2. 2 C# and .NET 1. Introduction • History • C# features • .NET framework 2. C# versus Java : highlights 3. C# data types 4. Defining custom data types 5. ...
  • 3. 3 History Builds on legacy from • C/C++ tradition -> new programming language C# • Java tradition : many ideas borrowed • runtime environment : virtual machine • platform/language abstraction • guarded execution environment • garbage collection • single rooted hierarchy • ... Takes software development one step further towards component based design
  • 4. 4 History procedural/structured design/programming object oriented design/programming component based design/programming C/PASCAL C++ JAVA C#/.NET component support possible BUT NOT built into the language - templates - deployment descriptors COM/COM+ CORBA component model
  • 5. 5 C# features : component oriented Modern large-scale systems are component based Properties get/set event based communication support to annotate component for - deployment - configuration at design and/or runtime - component versioning - documentation
  • 6. 6 C# features : OO paradigm supports all typical OO mechanisms • encapsulation • inheritance • polymorphism • interface based programming C++ legacy (NOT supported in Java) • support for operator overloading • user defined type conversions • rectangular arrays • pass-by-reference
  • 7. 7 C# features : Excution model NO own runtime library - uses .NET library (redesign of MS-library) (implemented in C#) Compiles to intermediary language (CIL - Common Intermediate Language) Executed by virtual machine (CLR – Common Language Runtime) - memory management through garbage collection - guarded execution (e.g. array bounds guarding) - JIT compilation
  • 8. 8 .NET framework “.NET framework” CLR FCL Framework Class Library Application Code Version 1.0 released January 15, 2002
  • 9. 9 .NET execution model Platform AND language portability CLR can exploit processor/platform specific optimizations Supported languages : C#, J#, VB.NET, JScript, Microsoft IL, Managed Extensions for C++ Supplied by 3rd parties : COBOL, Eiffel, Haskell, Forth, Scheme, Smalltalk, Pascal, ... CLR Compiler Application Code in “A Language” CIL
  • 10. 10 .NET : Common Type System Cross language type system, allowing - type safety - cross language integration - execution services (garbage collection, JIT, exceptions, ...) Defines rules to define types, irrespective of source language All types eventually mapped to CTS-types e.g. cross language inheritance J# class inherits from C# class Minimum subset for language to be supported by .NET : CLS – Common Language Specification - CLS-compliant language = “CLS consumer” - if more than CLS : “CLS extender” C#= both CLS consumer and extender
  • 11. 11 .NET : FCL categories comprises - > 3500 classes - > 1 000 000 lines of code • core functions • basic datatypes, collections • IO (network, console, file) • calls to runtime services • database interaction • transactions • consuming/producing XML • manipulation of tables • web-based applications (thin clients) • desktop applications (thick clients) • SOAP-based XML web services
  • 12. 12 Hello namespace Project1 { using System; class Class1 { static void Main() { Console.WriteLine("Hello there !"); for (int i = 0; i < 10; i++) Console.WriteLine(i); } } } package project1; import java.lang.*; class Class1 { public static void main(String[] args) { System.out.println("Hello there !"); for (int i = 0; i < 10; i++) System.out.println(i); } } C# Java
  • 13. 13 C# and .NET 1. Introduction 2. C# versus Java : highlights 3. C# data types 4. Defining custom data types
  • 14. 14 C# - Java : common approaches Both intended as improvement to C++ • Compilation to machine independent language, managed execution • Garbage Collection, no pointers (C# allows pointer usage in special “unsafe” code sections) • Reflection API • No header files, no problems with circular (type) references • Single rooted hierarchy, objects allocated on the heap • Thread support by object-level lock • Multiple extension of interfaces, single inheritance for classes • Inner classes (closure instead of nested class) • Simple inheritance rules (no inheritance modifiers) • Everything is in a class (no global data, no global functions) • Arrays, strings : bounds checked at execution time • Systematic usage of “.” (instead of “->” and “::”) • Keywords for null pointer (null) and boolean type (boolean/bool) • Guaranteed initialization • if-statement controlled by boolean (instead of integer) • Finally-clause in try-catch blocks
  • 15. 15 Properties C# : special support for getters/setters Java : implied by coding convention (template or “design pattern”) Property int min Java style : public int getMin() {return min;} public void setMin(int m) {min=m;} C# style : public int Min { get {return min;} set {min=value;} } // value : implicit variable used when // calling setter method - getter/setter grouped together - encourages to think in terms of properties
  • 16. 16 IndexerMeans to index underlying datastructure Java style : public class Bookshop { private Book[] books; // ... public void setBooks(int i,Book b) { if(b!=null) books[i]=b; } public Book getBooks(int i) {return books[i];} } C# style : public class Bookshop { private Book[] books; // ... public Book this[int i]{ get {return books[i];} set {if(value!=null) books[i]=value;} } } // ... Bookshop standaard=new Bookshop(); standaard[10]=new Book(“Harry Potter”);
  • 17. 17 Event handling Delegates used to handle events - Java equivalent : inner class object - C/C++ equivalent : function pointer Direct support in C# for events public delegate void TempChangeHandler(double t,ref bool cancel); public class Thermometer { public event TempChangeHandler TempChange; double temp; public double Temperature{ get{return temp;} set{if(temp!=value) { bool cancel=false; TempChange(value,ref cancel); // fire event if(!cancel) temp=value; } } }
  • 18. 18 Event handling public class TempController { public TempController(Thermometer tm) { tm.TempChange+=new TempChangeHandler(tm_TempChange); } private void tm_TempChange(double t,ref bool cancel) { if(t>100) { cancel=true; System.Console.WriteLine( "Way too hot : WRONG VALUE"); } else { System.Console.WriteLine( "New temperature registered."); } } }
  • 19. 19 Event handling public class Test { public static void Main() { Thermometer term=new Thermometer(); TempController tc=new TempController(term); term.Temperature=30; Console.WriteLine("Temp = {0}",term.Temperature); term.Temperature=120; Console.WriteLine("Temp = {0}",term.Temperature); } }
  • 20. 20 Enummerations Standard Java approach public class Period { public final static int DAILY=1; public final static int WEEKLY=2; public final static int MONTHLY=3; public final static int YEARLY=4; } // ... int publicationPeriod=Period.DAILY; // PROBLEM : does not prevent int publicationPeriod=12; ??? C# approach public enum Period{DAILY=1,WEEKLY=2,MONTHLY=3,YEARLY=4}; Period publicationPeriod = Period.WEEKLY;
  • 21. 21 Enummerations Java 5 approach enum PeriodE{DAILY,WEEKLY,MONTHLY,YEARLY} //... int publicationPeriod=Period.DAILY; System.out.println(publicationPeriod); PeriodE pubPeriod=PeriodE.DAILY; System.out.println(pubPeriod); // OUTPUT : // 1 // DAILY
  • 22. 22 Iterating over a Collection Standard Java approach for(Iterator i=collection.iterator();i.hasNext();) { Object o=i.next(); // do something with o } for(int i=0;i<array.length;i++) { // do something with array[i] } C# approach foreach(object o in collection) { // do something with o } foreach(int i in array) { // do something with i } Java 5 approach for(Object o : collection) { // do something with o } for(int i : array) { // do something with i }
  • 23. 23 Extension on “primitive” typesC# struct datatype : - very similar to class (defines attributes and methods) - BUT : - allocated on the stack or in-line (instead of heap) - value type -> pass by value by default - efficient for small types - usage similar to usage of primitive types in Java struct CoupleV { private int x, y; public int X { set { x = value; } get { return x; } } public int Y { set { y = value; } get { return y; } } public string ToString() { return "(" + x + "," + y + ")"; }
  • 24. 24 Extension on “primitive” types public static void Main() { CoupleV p = new CoupleV(); p.X = 10; p.Y = 20; CoupleV q=new CoupleV(); q.X = 20; q.Y = 30; Console.WriteLine(p.ToString()); Console.WriteLine(q.ToString()); CoupleV[] r = new CoupleV[4]; for (int i = 0; i < r.Length; i++) r[i].X = r[i].Y=i; foreach(CoupleV i in r) Console.WriteLine(i.ToString()); }
  • 25. 25 Operator Overloading Allows to program type specific operator semantics More restrictive than C++ overloading mechanism - always static - NON virtual (static binding !) ! public static bool operator ==(CoupleV a, CoupleV b) { return ((a.x == b.x) && (a.y == b.y)); } public static Boolean operator !=(CoupleV a, CoupleV b) { return !(a == b); } // ... CoupleV p = new CoupleV();p.X = 10;p.Y = 20; CoupleV q = new CoupleV();q.X = 10;q.Y = 20; Console.WriteLine(p == q); // TRUE Console.WriteLine((object)p == (object)q); // FALSE non-virtual !
  • 26. 26 Polymorphism Java : all methods virtual (late binding) by default C# (like C++) : methods MUST be declared virtual if late binding applies class A { public virtual void f() {Console.WriteLine("A.f()");} } class B : A { public override void f() {Console.WriteLine("B.f()");} } - shows intention of programmer - more efficient - can prevent later extensions ... - explicit interface implementation (solving name conflicts in case of multiple interface implementation) - possibility to hide base class type/method in derived class
  • 27. 27 Assemblies Type boundaries - class - namespace (equivalent to Java package) - assembly (equivalent to Java archive) Assemby = exe/dll to deploy - meta-data (files contained, security settings, versioning info, dependencies) - modules (compiled source files) - resources Versioning - contained in assemby info - allows to run multiple versions of same types on same CLR
  • 28. 28 Visibility private same as Java = default for interface and enum members public same as Java =default for struct and class members protected visible in type itself or derived types internal visible in assembly = default for non-nested types internal protected visible from type itself, in same assembly and in derived types (= private or protected or internal) Type can not be more accessible then types used for its declaration
  • 29. 29 Parameter modifiers Passing references ref pass reference to method requires parameter is assigned definite value before method entry out requires definite parameter assignment before returning from method call Variable number of arguments params can be applied to last argument of method Parameter modifiers are part of method signature
  • 30. 30 Parameter modifiers static void swap(ref int a, ref int b) { int t = a; a = b; b = t; } static void OneMore(int i, out int j) { j = i + 1; } static int sum(params int[] x) { int r = 0; foreach (int i in x) r += i; return r; } // ... int x = 1, y = 2; swap(ref x, ref y); Console.WriteLine("{0} - {1}",x, y); // 2 - 1 OneMore(x, out y); Console.WriteLine("{0} - {1}", x, y); // 2 - 3 Console.WriteLine(sum(1, 2, 3)); // 6 Console.WriteLine(sum(3, 4, 5, 6)); // 18
  • 31. 31 Attributes Allow to extend language built-in declarative constructs - Pre-defined attributes (e.g. Serialized) - Custom attributes Can be applied to - class - method - field - parameter Attributes and values can be retrieved at runtime
  • 32. 32 Field modifiers const - value calculated at compile time - equivalent to Java final readonly - value calculated at runtime - can only be assigned once ! - allows to retrieve setting (“a not so constant constant ...”)
  • 33. 33 Pointer arithmetic allowed in sections marked as unsafe pointer type : <type>* dereferencing : *<pointer expression> address calculation : &<variable> Garbage collector should NOT move around objects used in unsafe regions MUST be declared fixed
  • 34. 34 Pointer arithmetic unsafe static void AdditionOne(int[] b) { int l=b.Length; fixed (int* a = b) { int* p = a; for (int i = 0; i < l; i++,p++) *p = (*p) + 1; } } //... int[] k ={ 1, 2, 3, 4 }; foreach (int a in k) Console.WriteLine("{0}", a); // 1 2 3 4 AdditionOne(k); foreach (int a in k) Console.WriteLine("{0}", a); // 2 3 4 5
  • 35. 35 Rectangular Arrays int[,,] a=new int[3,4,5]; // rectangular array // single reference variable a[1,2,3]=20; int[][][] b=new int[3][4][5]; // jagged array b[1][2][3]=30; ...
  • 36. 36 Constructors - Destructors Very similar to Java constructors – finalizers Constructor : can contain explicit constructor call specified outside constructor body - call to other constructor of same type : this(...) - call to base class constructor : base(...) Destructor NOT for value type NO explicit calls to destructor C++-like syntax (actually expands to calling Finalize) class A { public A():this(1){} public A(int i):base(i){} ~A() {/* Destructor */} }
  • 37. 37 C# and .NET 1. Introduction 2. C# versus Java : highlights 3. C# data types 4. Defining custom data types
  • 38. 38 C# type system Value types (struct, enum) Reference types (class, array, delegate, interface) Pointer type struct CoupleV { private int x, y; public CoupleV(int xx, int yy) { x = xx; y = yy; } public int X { set { x = value; } get { return x; } } public int Y { set { y = value; } get { return y; } } public override string ToString() { return "(" + x + "," + y + ")"; } }
  • 39. 39 C# type system class CoupleR { private int x=0, y=0; public CoupleR(int xx, int yy) { x = xx; y = yy; } public int X { set { x = value; } get { return x; } } public int Y { set { y = value; } get { return y; } } public override string ToString() { return "(" + x + "," + y + ")"; } }
  • 40. 40 C# type system // ... CoupleR a = new CoupleR(1, 2); CoupleR b = a; CoupleV c = new CoupleV(3, 4); CoupleV d = c; a.X = 7; c.X = 7; Console.WriteLine(a); // (7,2) Console.WriteLine(b); // (7,2) Console.WriteLine(c); // (7,4) Console.WriteLine(d); // (3,4)
  • 41. 41 Type unification all struct and class types derive from object (pointer types do not ...) “simple” (“primitive”) types are actually structs int : alias for System.Int32 long : alias for System.Int64 ... boxing – unboxing - value type -> reference type : copy made (automatic) - reference type -> value type : explicit cast necessary int x=12; object o=x; // box int y=(int)o; // unbox through downcast
  • 42. 42 Available types Value types signed integer : sbyte, short, int, long unsigned integer : byte, ushort, uint, ulong floating point : float, decimal, double logical : bool characters : char Reference types object string standard notations for constants apply (U : unsigned, L : long) standard rules for conversions apply
  • 43. 43 Checked Arithmetic checked(<expression>) checked {/* block */} checks for integral overflows generates runtime exception OverflowException unchecked(<expression>) unchecked{/* block */} turns off compile time bounds checking
  • 44. 44 Control flow statements Same as in Java, BUT switch : no “fall through” behaviour each case must end with jump (break, goto, ...) foreach goto label; // ... int x=0; loop : x++; if(x<5) goto loop;
  • 45. 45 Namespaces Similar to java packages w.r.t. avoiding name clashes BUT : no boundary for accessibility Can be nested namespace A { namespace B { class CL { } } } // ... A.B.CL x=new A.B.CL(); Alternative using A.B; CL x=new CL(); Global namespace = default surrounding namespace
  • 46. 46 C# and .NET 1. Introduction 2. C# versus Java : highlights 3. C# data types 4. Defining custom data types
  • 47. 47 Classes [<attributes>][unsafe][<access modifier>][new] [abstract | sealed] <class name> [: <base class> | : <interfaces> | : <base class>,<interfaces> ] { <class members> } Class members • Fields • Constants • Properties • Indexers • Methods • Events • Nested type (like Java static inner class, no outer object)
  • 48. 48 Modifiers Accessibility (visibility) : private, internal, protected, public Inheritable sealed : can not be overridden/inherited (Java equivalent : final) - sealed class - sealed method abstract : MUST be overridden/inherited - abstract class - abstract method class/method can not be sealed AND abstract Parameter modifiers : ref,out,params Class member/instance member : static Late binding/static binding : virtual, override, new Dangerous ? : unsafe - unsafe class - unsafe method - unsafe property
  • 49. 49 Inheritance class A {} class B : A {} class C : B {} class D : A {} Runtime type checking (RTTI) operator is if(a is A) {/* ... */} if(b is A) {/* ... */} // true if b is A or B Conversions : - widening conversions (upcast) : automatic B b = new B(); C c = new C(); D d = new D(); A ab = b; A ac = c; B bc = c; B bd = d; // compile time error A ad = d; - narrowing (cntd.)
  • 50. 50 Inheritance - narrowing conversions : cast necessary - simple downcast : B ba=(B)ab; // OK C ca=(C)ac; // OK D da=(D)ad; //OK D dc=(D)ac; // runtime error - safe downcast (evaluates to null if unsuccesful) B ba = ab as B; C ca = ac as C; D dc = ac as D; // null
  • 51. 51 Polymorphism Key idea : late binding, based on dynamic object type C# : use virtual methods, override in derived class class A { public virtual void f() {Console.WriteLine("A.f()");} } class B : A { public override void f() {Console.WriteLine("B.f()");} } class C : B { public override void f() { Console.WriteLine("C.f()"); } } class D : A { public override void f() {Console.WriteLine("D.f()");} }
  • 52. 52 Polymorphism A a = new A(); B b = new B(); C c = new C(); D d = new D(); a.f(); // A.f() b.f(); // B.f() c.f(); // C.f() d.f(); // D.f() A[] a = new A[] { new A(), new B(), new C(), new D() }; foreach(A aa in a) aa.f(); // A.f() // B.f() // C.f() // D.f()
  • 53. 53 Polymorphism Sealing class A { public virtual void f() {Console.WriteLine("A.f()");} } class B : A { public sealed override void f() {Console.WriteLine("B.f()");} } class C : B { public override void f() { Console.WriteLine("C.f()"); } } NOT allowed
  • 54. 54 Polymorphism Hiding base class member : new class A {public virtual void f() {Console.WriteLine("A.f()");}} class B : A {public override void f() {Console.WriteLine("B.f()");}} class C : B {public new void f() { Console.WriteLine("C.f()"); }} class D : A {public override void f() {Console.WriteLine("D.f()");}} A aa = new A(); aa.f(); // A.f() B bb = new B(); bb.f(); // B.f() C cc = new C(); cc.f(); // C.f() D dd = new D(); dd.f(); // D.f() A ab = new B(); ab.f(); // B.f() A ac = new C(); ac.f(); // B.f() A ad = new D(); ad.f(); // D.f(); B bc = new C(); bc.f(); // B.f(); A[] a = new A[] { new A(), new B(), new C(), new D() }; foreach(A o in a) o.f(); // A.f() B.f() B.f() D.f()
  • 55. 55 Polymorphism Hiding base class member : new class A {public virtual void f() {Console.WriteLine("A.f()");}} class B : A {public override void f() {Console.WriteLine("B.f()");}} class C : B {public new void f() { Console.WriteLine("C.f()"); }} class D : A {public new void f() {Console.WriteLine("D.f()");}} A aa = new A(); aa.f(); // A.f() B bb = new B(); bb.f(); // B.f() C cc = new C(); cc.f(); // C.f() D dd = new D(); dd.f(); // D.f() A ab = new B(); ab.f(); // B.f() A ac = new C(); ac.f(); // B.f() A ad = new D(); ad.f(); // A.f(); B bc = new C(); bc.f(); // B.f(); A[] a = new A[] { new A(), new B(), new C(), new D() }; foreach(A o in a) o.f(); // A.f() B.f() B.f() A.f()
  • 56. 56 Polymorphism new - define method as new (even if method with same signature, possibly sealed, exists in base class) - define new property - define new field class A {protected double i; public double I {set{i = value;} get{return i;} } public sealed void f() {Console.WriteLine("A.f()");} } class B : A {private new int i; public new int I {set{i = value;} get{return i;} } public new void f() {Console.WriteLine(“B.f()");} }
  • 57. 57 Structs Struct = class except for • value type, allocated on the stack • is implicitely sealed (inherit from single type, System.ValueType), can implement several interfaces • can NOT have destructor • NO field initializers (initialization to 0) • NO constructor that leaves fields uninitialized struct CoupleV : A // not allowed unless A is interface { private int x=1, y=1; // NOT allowed : field initializer public CoupleV(int xx) { x = xx; } // NOT allowed : partial initialization public CoupleV(int xx, int yy) { x = xx; y = yy; } // allowed }
  • 58. 58 Interfaces Interface = class except for • no implementation, (pure abstract class) • can be supertype of struct (class can not !) Interface members : - methods - properties - indexers - events always : implicitly public, abstract, virtual and non static
  • 59. 59 Interfaces interface IP{void f();} interface IQ{void g();} class A : IP{ public virtual void f() {Console.WriteLine("A.f()");} } class B : A,IQ { public override void f() {Console.WriteLine("B.f()");} public virtual void g() {Console.WriteLine("B.g()");} } class C : B { public override void f() { Console.WriteLine("C.f()"); } public override void g() { Console.WriteLine("C.g()"); } } class D : A{ public override void f(){Console.WriteLine("D.f()");} } class E : D,IQ { public override void f() { Console.WriteLine("E.f()"); } public virtual void g() { Console.WriteLine("E.g()"); } }
  • 60. 60 Interfaces IP[] p = new IP[] { new A(), new B(), new C(), new D(), new E() }; IQ[] q = new IQ[] { new B(), new C(), new E() }; foreach (IP pp in p) pp.f(); foreach (IQ qq in q) qq.g(); // A.f() // B.f() // C.f() // D.f() // E.f() // B.g() // C.g() // E.g() Extending an interface interface IPP : IP { void ff(); }
  • 61. 61 Explicit interface implementation PROBLEM : implement two interfaces with name collision -> explicit (instead of implicit) interface implementation interface U { void a(); } interface V { void a(); } class O : U, V { void U.a() { Console.WriteLine("A.ua()"); } void V.a() { Console.WriteLine("A.va()"); } } // ... O o = new O(); // o.a(); // NOT allowed ((U)o).a(); // A.ua() ((V)o).a(); // A.va()
  • 62. 62 Explicit interface implementation LIMITATIONS (compared to implicit implementations) • NO late binding no polymorphism related modifiers (no abstract, virtual, override, new) • NO access modifier usage requires cast to interface access modifier mentioned there is used implicitely Same rules (as with classes) to • convert between types • to convert to structs
  • 63. 63 C# and .NET 1. Introduction 2. C# versus Java : highlights 3. C# data types 4. Defining custom data types 5. Operator Overloading 6. Event driven programming 7. .NET Framework Class Library 8. A GUI in C# 9. A web service in C#
  • 64. 64 Operator overloading Idea • treat operators (+,-,*,/,%,...) as special functions (keyword operator) • give special meaning to operator according to class semantics • allows elegant programming for math-oriented software • important issue : what happens in case of mixed type expressions ? -> need to overload also type conversion -> quite complex to keep consistent -> not available in Java (but proposals are on the way ...)
  • 65. 65 C# Operator overloading Operators to overload + - ! ~ ++ -- (unary) (binary) + - * / % arithmetic & | ^ bit logic << >> bit shift == != > < >= <= relational CAN NOT BE OVERLOADED : - address related operators (unary *, &) - assignment ! (cf. C++ ...) ONLY static operators allowed LOGIC pairs (MUST be overloaded together) == and != < and > <= and >=
  • 66. 66 Indirect overloading To keep things consistent (developer might forget to overload ...) - && and || are evaluated using & and | - [] operator overloaded through indexers - combined assignment operators (+=, -=, *=, /=, ...) evaluated using non-combined counterparts
  • 67. 67 Value equality Operators == and != default to reference equality If other behavior is needed : - override Equals method (cf. Java) - redirect Equals to “==“ and “!=“ -> allows compatibility with .NET languages NOT supporting operator overloading -> allows polymorphism
  • 68. 68 Value equality class Point { protected int x, y; public Point(int xx, int yy) { x = xx; y = yy; } public Point(int xx) : this(xx, xx) { } public Point() : this(0) { } public override string ToString() { return "<"+x+","+y+">"; } public static bool operator ==(Point a, Point b) { return (a.x == b.x) && (a.y == b.y); } public static bool operator !=(Point a, Point b) { return !(a == b); } }
  • 69. 69 Value equalityProblem Collections framework heavily uses Equals()-method (implementation of no-duplicate collections such as Sets) -> whenever == and != overloaded -> Equals() should be overridden public override bool Equals(object o) { if (o is Point) { Point p = (Point)o; return this == p; } else return false; } DO NOT call Equals() from within == and != ...
  • 70. 70 Value equality : inheritance class Point3D : Point { protected int z; public Point3D(int xx,int yy,int zz):base(xx,yy){z=zz;} public override string ToString() { return "<"+x+","+y+","+z+">"; } } // ... Point a=new Point(1,1); Point b=new Point(2,2); Point c = new Point(2, 2); Point3D d=new Point3D(3,3,3); Point3D e = new Point3D(3, 3, 3); Point3D f = new Point3D(3, 3, 4); Console.WriteLine(a); // <1,1> Console.WriteLine(b); // <2,2> Console.WriteLine(e); // <3,3,3> Console.WriteLine(f); // <3,3,4>
  • 71. 71 Value equality : inheritance Console.WriteLine(a == b); // False Console.WriteLine(a == c); // False Console.WriteLine(a == d); // False Console.WriteLine(b == c); // True -> value ! Console.WriteLine(b == d); // False Console.WriteLine(c == d); // False Console.WriteLine(d == e); // True Console.WriteLine(e == f); // True Operators == and != should be overloaded in Point3D public static bool operator ==(Point3D a, Point3D b) { return (a.x == b.x) && (a.y == b.y)&&(a.z==b.z); } public static bool operator !=(Point3D a, Point3D b) { return !(a == b); } // ... Console.WriteLine(e == f); // False
  • 72. 72 Value equality : polymorphismPoint[] p ={ new Point(1, 1), new Point(2, 2), new Point3D(1, 1, 1), new Point3D(2, 2, 2) }; Point s1 = new Point(2, 2) Point s2 = new Point3D(2, 2, 2); foreach (Point pp in p) Console.WriteLine(pp == s1); foreach (Point pp in p) Console.WriteLine(pp == s2); // False True False True // False True False True CHANGE operator in base class (!) public static bool operator ==(Point a, Point b) { if(((a is Point3D)&&!(b is Point3D))|| (!(a is Point3D)&&(b is Point3D))) return false; else return (a.x == b.x) && (a.y == b.y); } public static bool operator !=(Point a, Point b) { return !(a == b); } // False True False False // False False False True
  • 73. 73 Overloading arithmetic operators Operator + Point p: translate over p Operator + int i: translate over Point(i,i) public static Point operator +(Point a, Point b){ return new Point(a.x + b.x,a.y + b.y); } public static Point operator +(Point a,int i){ return new Point(a.x + i, a.y + i); } public static Point operator +(int i, Point a){ return a + i; } //... Point a = new Point(10, 20); Point b = new Point(20, 30); Console.WriteLine(a + b); //<30,50> Console.WriteLine(a + 100); //<110,120> Console.WriteLine(100 + a + b); //<130,150>
  • 74. 74 Type Conversion Two versions implicit not dangerous, can be invoked by compiler whenever needed explicit dangerous, only done if explicitely asked e.g. conversion to and from int Point-to-int : max value of x and y (looses info !) int-to-Point : Point on diagonal (no info lost !)
  • 75. 75 Type Conversion public static Point operator +(Point a,int i) { Console.WriteLine("+(P,i)"); return new Point(a.x + i, a.y + i); } public static Point operator +(int i, Point a) { Console.WriteLine("+(i,P)"); return a + i; } public static implicit operator Point(int i) { Console.WriteLine("(P)i"); return new Point(i, i); } public static explicit operator int(Point p) { Console.WriteLine("(i)P"); return (p.x > p.y) ? p.x : p.y; }
  • 76. 76 Type Conversion Point a = new Point(10,20); Console.WriteLine((Point)5); // (P)i <5,5> Console.WriteLine(a + 5); // +(P,i) <15,25> Console.WriteLine((int)a + 5); //(i)P 25 In case NO +(Point,int) and +(int,Point) operators : Console.WriteLine((Point)5); // (P)i <5,5> Console.WriteLine(a + 5); // (P)i <15,25> Console.WriteLine((int)a + 5); // (i)P 25
  • 77. 77 C# and .NET 1. Introduction 2. C# versus Java : highlights 3. C# data types 4. Defining custom data types 5. Operator Overloading 6. Event driven programming • delegates • events 7. .NET Framework Class Library 8. A GUI in C# 9. A web service in C
  • 78. 78 Delegates[<attributes>][unsafe][<access modifiers>] [new]delegate <return type> <delegate name> (<parameter list>); = type defining method signature - instance can hold (list of) method(s) with matching signature public delegate bool Filter(string s); class Del{ public static void Main(){ String[] r = new String[] { "a fair Lady", "the king and I", "hye buzz", "a beautiful mind", "the zzz" }; Filter f=new Filter(StartWithA); ArrayList a=Show(r,f); Console.WriteLine("Starting with a :"); foreach (String s in a) Console.WriteLine(s); f=new Filter(EndWithZ); ArrayList z = Show(r, f); Console.WriteLine("Ending with z :"); foreach (String s in z) Console.WriteLine(s); } //... }
  • 79. 79 Delegatesclass Del { // ... public static bool StartWithA(String s) { return s[0] == 'a'; } public static bool EndWithZ(String s) { return s[s.Length-1] == 'z'; } public static ArrayList Show(String[] s, Filter f) { ArrayList l = new ArrayList(); foreach(String i in s) if(f(i)) l.Add(i); return l; } } Starting with a : a fair Lady a beautiful mind Ending with z : hye buzz the zzz
  • 80. 80 Multicast Delegates Use operators += and -= to add/remove delegates to other delegate if non-void : return value of last invocation is returned public delegate void M(int i); class Multi { // ... public static void Print(int i) { Console.WriteLine("i = {0}",i); } public static void Sqrt(int i) { Console.WriteLine(Math.Sqrt(i)); } public static void EndMessage(int i) { Console.WriteLine("Ending ..."); } }
  • 81. 81 Multicast Delegates// public delegate void M(int i); class Multi { // ... public static void Main() { M m = null; Console.WriteLine("----------------------------"); m += new M(Print); m += new M(Sqrt); m += new M(EndMessage); m(12); Console.WriteLine("----------------------------"); m += new M(Print); m(16); Console.WriteLine("----------------------------"); m -= new M(Sqrt); m(25); Console.WriteLine("----------------------------"); m -= new M(Print); m(36); Console.WriteLine("----------------------------"); } } ----------------- i = 12 3,46410161513775 Ending ... ----------------- i = 16 4 Ending ... i = 16 ----------------- i = 25 Ending ... i = 25 ----------------- i = 36 Ending ... -----------------
  • 82. 82 Multicast Delegates From within object -> invoked on this-object public delegate void F(); public class A { public F f; private int i = 0; public A(int i) { this.i = i; f=null; f+=new F(Print); f+=new F(Inc); f+=new F(Print); f+=new F(Dec); f+=new F(Dec); f+=new F(Print); } public void Inc() { i++; } public void Dec() { i--; } public void Print() {Console.WriteLine(this);} public override string ToString(){return "<"+i+">";} public void IncAndDec() {f();}
  • 83. 83 Multicast Delegates From within object -> invoked on this-object // ... public static void Test() { A a=new A(10); a.IncAndDec(); a.f(); } } class MultiObj { public static void Main() { A.Test(); A a = new A(20); a.f(); } } <10> <11> <9> <9> <10> <8> <20> <21> <19>
  • 84. 84 Delegate versus ... Delegate vs. C function pointer - type safe (unless in unsafe regions ...) - can hold multiple methods to invoke - can hold instance to invoke method upon Delegate vs. Interface - multiple methods to invoke (could be implemented through list of interface objects) - any problem solved with delegates can be solved using interface types - “more elegant”
  • 85. 85 Delegate versus Inteface interface IF { bool Filter(string s); } class StartWithAFilter : IF { public bool Filter(string s) { return s[0] == 'a'; } } class EndWithZFilter : IF { public bool Filter(string s) { return s[s.Length - 1] == 'z'; } }
  • 86. 86 Delegate versus Inteface class Test { public static void Main() { String[] r = new String[] { "a very fair Lady", "the king and a z", "hye buzzy", "a beautiful mind for z", "the zzz" }; ArrayList a = Show(r, new StartWithAFilter()); Console.WriteLine("Starting with a :"); foreach (String s in a) Console.WriteLine(s); ArrayList z = Show(r, new EndWithZFilter()); Console.WriteLine("Ending with z :"); foreach (String s in z) Console.WriteLine(s); } public static ArrayList Show(String[] s, IF f) { ArrayList l = new ArrayList(); foreach (String i in s) if (f.Filter(i)) l.Add(i); return l; } } Starting with a : a very fair Lady a beautiful mind for z Ending with z : the king and a z a beautiful mind for z the zzz
  • 87. 87 Events A B events - notification from A -> B - WITHOUT calling directly method on B use of intermediary - event listeners + event handlers - in C# : implemented through delegates event
  • 88. 88 Events A B event Event Source Event Sink - delegate defined to fix handler signature - source class declares ability to fire event -> public (downcast) multicast delegate d - delegates registered with d to get notified - source class fires event by calling delegate d d Delegate delegate delegate delegate
  • 89. 89 Events : Example Customer arrives in business centre -> generates event -> interested parties are notified Delegate conventions for eventing - first argument : identifies source of event - second argument : additional info subclass of EventArgs Example - ID = object reference - additional info : - time of event - urgency
  • 90. 90 Events : Example Delegate signature delegate void CustomerHandler(object s, CustomerArgs e) public delegate void CustomerHandler(object o,CustomerArgs e); enum Priority {LOW=0,NORMAL=1,HIGH=2}; class CustomerArgs : EventArgs { private DateTime d; public Priority p; public static Random r = new Random(); public DateTime Time { get { return d; } } public Priority Urgency { get {return p;} } public CustomerArgs() { d = DateTime.Now; p=(Priority)(r.Next(3)); } } Preliminaries • Delegate declaration • Definition of event handler argument type
  • 91. 91 Events : Example public class Customer { private string name; public event CustomerHandler CustomerArrival; public string Name { get { return name; } } public Customer(string n){name = n;} public void arrive() { if (CustomerArrival != null) { CustomerArgs args = new CustomerArgs(); CustomerArrival(this, args); // fire the event; } } public override string ToString(){return "<Customer : "+name+">";} } Event source class : Customer • Declares event • Listeners will register to event • FIRES event when needed
  • 92. 92 Events : Example class HotelService {private string n; public HotelService(string n) {this.n=n;} public string Name{get{return n;}} public void CustomerArrivalNotification(object o,CustomerArgs a) { Console.WriteLine(this + " : guest " + (Customer)o + " arrived at " + (a.Time)+"(Priority : "+a.Urgency+")"); } public override string ToString() { return "Hotel service : "+n; } } class HotelPersonnel {private string n; public HotelPersonnel(string n) {this.n=n;} public string Name{get{return n;}} public void CustomerArrivalNotification(object o,CustomerArgs a) { Console.WriteLine(this + " : guest " + (Customer)o + " arrived at" + (a.Time) + "(Priority : " + a.Urgency + ")"); } public override string ToString() { return "Hotel personnel : "+n; } } Event sink classes : • HotelService • HotelPersonnel • declare a method conforming to delegate signature
  • 93. 93 Events : Example class CustomerApp { public static void Main() { Customer[] c=new Customer[] {new Customer("Bart De Poorter"), new Customer("George Bush"), new Customer("Condaleeza Rice"), new Customer("Mahatma Ghandi")}; HotelService[] hs = new HotelService[] { new HotelService("House keeping"), new HotelService("Accounting"), new HotelService("Reception") }; HotelPersonnel[] hp = new HotelPersonnel[] { new HotelPersonnel("Manager"), new HotelPersonnel("Mr. BigBoss (owner)") }; foreach(HotelService h in hs) { foreach(Customer cu in c) cu.CustomerArrival+= new CustomerHandler(h.CustomerArrivalNotification); } // ... Main method • instantiates simulation objects • binds sinks to sources
  • 94. 94 Events : Example // ... foreach (HotelPersonnel h in hp) { c[1].CustomerArrival += new CustomerHandler(h.CustomerArrivalNotification); c[2].CustomerArrival += new CustomerHandler(h.CustomerArrivalNotification); } Console.WriteLine("Starting simulation ----------------"); foreach (Customer cc in c) { cc.arrive(); try { System.Threading.Thread.Sleep(1000); } catch (System.Threading.ThreadInterruptedException e) { } Console.WriteLine("---------------------"); } } }
  • 95. 95 Events : Example Starting simulation ---------------- Hotel service : House keeping : guest <Customer : Bart De Poorter> arrived at 14/12/2005 9:57:06(Priority : NORMAL) Hotel service : Accounting : guest <Customer : Bart De Poorter> arrived at 14/12/2005 9:57:06(Priority : NORMAL) Hotel service : Reception : guest <Customer : Bart De Poorter> arrived at 14/12/2005 9:57:06(Priority : NORMAL) --------------------- Hotel service : House keeping : guest <Customer : George Bush> arrived at 14/12/2005 9:57:07(Priority : LOW) Hotel service : Accounting : guest <Customer : George Bush> arrived at 14/12/2005 9:57:07(Priority : LOW) Hotel service : Reception : guest <Customer : George Bush> arrived at 14/12/2005 9:57:07(Priority : LOW) Hotel personnel : Manager : guest <Customer : George Bush> arrived at14/12/2005 9:57:07(Priority : LOW) Hotel personnel : Mr. BigBoss (owner) : guest <Customer : George Bush> arrived at 14/12/2005 9:57:07(Priority : LOW) --------------------- Hotel service : House keeping : guest <Customer : Condaleeza Rice> arrived at 14/12/2005 9:57:08(Priority : NORMAL) Hotel service : Accounting : guest <Customer : Condaleeza Rice> arrived at 14/12/2005 9:57:08(Priority : NORMAL) Hotel service : Reception : guest <Customer : Condaleeza Rice> arrived at 14/12/2005 9:57:08(Priority : NORMAL) Hotel personnel : Manager : guest <Customer : Condaleeza Rice> arrived at14/12/2005 9:57:08(Priority : NORMAL) Hotel personnel : Mr. BigBoss (owner) : guest <Customer : Condaleeza Rice> arrived at14/12/2005 9:57:08(Priority : NORMAL) --------------------- Hotel service : House keeping : guest <Customer : Mahatma Ghandi> arrived at 14/12/2005 9:57:09(Priority : HIGH) Hotel service : Accounting : guest <Customer : Mahatma Ghandi> arrived at 14/12/2005 9:57:09(Priority : HIGH) Hotel service : Reception : guest <Customer : Mahatma Ghandi> arrived at 14/12/2005 9:57:09(Priority : HIGH) ---------------------
  • 96. 96 C# and .NET 1. Introduction 2. C# versus Java : highlights 3. C# data types 4. Defining custom data types 5. Operator Overloading 6. Event driven programming 7. .NET Framework Class Library 8. A GUI in C# 9. A web service in C#
  • 97. 97 FCL -CLS compliant set of managed type - accessible from all .NET languages - grouping (3542 types) : - logically in namespaces (120) - deployed as a set of assemblies (36) of .NET framework System - collection of core classes (Object, ValueType, Enum, Convert, Exception) - core interfaces (ICloneable, IComparable, ...) - time related classes (DateTime, TimeSpan) - support for - delegates - mathematical operations - custom attributes (Attribute) - exception handling - strings (String)
  • 98. 98 FCL System.Text - immutable string (System.String) - mutable string (StringBuilder) - regular expressions (System.Text.RegularExpressions) C# string is alias for System.String overloaded “==“ operator for equality check (NOT in Java !) indexing strings : use normal indexing mechanism ([]) string a=“abcde”; char c=a[2]; formatting strings (Format()-method) format specifier string : {ParamIndex[,MinWidth][:FormatString]} e.g. “Value of account {0} is {1:C}” (C -> “Currency”)
  • 99. 99 FCL System.Collections - Java-like set of interfaces and classes, implementing popular data structures (ArrayList, Queue, Stack, BitArray, ...) - System.Array is base type for all array types - generics as of .NET v 2.0 (System.Collections.Generics) to iterate over Collection : - Collection implements IEnumerable public interface IEnumerable { IEnumerator GetEnumerator(); } - iterator implements IEnumerator public interface IEnumerator { bool MoveNext(); object Current {get;} void Reset(); } - also : foreach idiom can be used
  • 100. 100 FCL iterator for Dictionary (Java Map) public interface IDectionaryEnumerator : IEnumerator { DictionaryEntry Entry {get;} object Key {get;} object Value {get;} } IEnumerable ICollection IList IDictionary get iterator support for counting converting to array indexed collection
  • 101. 101 FCLclass Array : ICollection, IEnumerable, IList fixed size indexed array class ArrayList : IList dynamically sized array class Hashtable : IDictionary standard dictionary key/value pairs hash computed using GetHashCode() method -> should be overridden class Queue FIFO data structure methods to queue and dequeue class Stack LIFO data structure key methods : push and pop
  • 102. 102 FCL class Bitarray compressed form of bool[] (one bit per boolean) class SortedList : IDictionary sorted to increase lookup efficiency (binary search instead of linear search) class StringCollection : ICollection special purpose collection for storing strings class StringDictionary : IEnumerable idem for storing string maps
  • 103. 103 FCL : Examplespublic static void Print(ICollection c) { int j = 0; foreach(object i in c) Console.WriteLine("{0} -> {1}",j++,i); Console.WriteLine("--------------------"); } ArrayList al = new ArrayList(); al.Add("Wim"); al.Add("Ann"); al.Add("Bram"); al.Add("Bart"); al.Add("Greet"); Print(al); al.Sort(); Print(al); Console.WriteLine(al[1]); al[1] = "BART"; Print(al); 0 -> Wim 1 -> Ann 2 -> Bram 3 -> Bart 4 -> Greet -------------------- 0 -> Ann 1 -> Bart 2 -> Bram 3 -> Greet 4 -> Wim -------------------- Bart 0 -> Ann 1 -> BART 2 -> Bram 3 -> Greet 4 -> Wim --------------------
  • 104. 104 FCL : ExamplesHashtable h = new Hashtable(); h["Wim"] = "onetwothree"; h["Bram"] = "123"; h["Greet"] = "Da Vinci"; h["Ann"] = "My fair lady"; Console.WriteLine(h["Bram"]); // 123 Queue q = new Queue(); Stack s = new Stack(); int[] a ={ 1, 2, 3, 4 }; foreach (int i in a) {q.Enqueue(i); s.Push(i);} Print(q); Print(s); Console.WriteLine(q.Dequeue()); Console.WriteLine(s.Pop()); Print(q); Print(s); 123 0 -> 1 1 -> 2 2 -> 3 3 -> 4 -------------------- 0 -> 4 1 -> 3 2 -> 2 3 -> 1 -------------------- 1 4 0 -> 2 1 -> 3 2 -> 4 -------------------- 0 -> 3 1 -> 2 2 -> 1 --------------------
  • 105. 105 FCL : SortingTwo options : - object ordering implemented in the class itself public interface IComparable { int CompareTo(object o); } - delegate ordering to special object public interface IComparer { int Compare(object o1,object o2); } comparing must follow special contract 1. if a comes before b -> a.CompareTo(b)<0 2. if a is equal to b -> a.CompareTo(b) == 0 3. if a comes after b -> a.CompareTo(b)>0 4. null first -> a.CompareTo(null)>0 5. a.CompareTo(b) -> a.GetType() == b.GetType()
  • 106. 106 FCL System.IO - standard in, out and error stream - binary and text file I/O - registering/notification of filesystem events - access of user specific secure storage (“Isolated Storage”) - System.Console - System.IO.IsolatedStorage System.Net - classes for network communication - raw socket access, TCP, UDP sockets - HTTP support - System.Net - System.Net.Sockets - System.IO.Stream
  • 107. 107 FCL System.Security - security policies, principals, permission sets, evidence (authentication, key, ...) - cryptographic library System.Threading - support for thread management and pool management - synchronization mechanisms - locks (monitor): serialized access - pulse/wait : notify waiting threads - System.Timers - System.Thread
  • 108. 108 FCL System.Reflection - retrieve type information (methods, class names, signatures, ...) at runtime - retrieve (custom) attributes at runtime -> for each custom attribute : - CLR creates object - retrieved using reflection interface - retrieve metadata at runtime - assembly info (version, target OS, ...) - data to create custom attributes stored as metadata
  • 109. 109 FCL System.Runtime.Serialization - write object graph to/from stream (file or network) - default serializers : XML and binary - serializability : use non-custom attribute [Serializable] - System.SerializableAttribute - System.NonSerializableAttribute System.Runtime.Remoting - distributed object model of .NET - calls can be : synchronous, asynchronous, one-way - transport protocol : TCP, HTTP or SMTP - format : binary or SOAP - naming service, activation service, marshalling, messaging
  • 110. 110 FCL System.Web.Services - in fact part of ASP.NET (not part of CLR) - describe, discover and publish web services System.Data - known as ADO.NET - classes to support database access System.Xml - schemas, namespaces, parsing (DOM,SAX) - implementation of XSLT, XPath, SOAP1.1
  • 111. 111 FCL System.Drawing - support for graphics - known as GDI+ - brushes, fonts, bitmaps, rendering, drawing primitives, ... System.Windows.Forms - Rich client applications (“classic GUIs”) - known as “Windows Forms” - forms package, GUI components and RAD component model System.Web - Thin client applications - known as “Web Forms” - server side package creates HTML UI - support for session management (state), security, deployment, ... - part of ASP.NET
  • 112. 112 FCL System.Globalization - date/time conversions - string adaptation to locale - resource file to centralize locale data System.Configuration - per user, per application configuration management System.EnterpriseServices - advanced services - distributed transaction, object pooling, queuing, event handling - reliable asynchronous messaging - access to directory service
  • 113. 113 C# and .NET 1. Introduction 2. C# versus Java : highlights 3. C# data types 4. Defining custom data types 5. Operator Overloading 6. Event driven programming 7. .NET Framework Class Library 8. A GUI in C# 9. A web service in C#
  • 114. 114 GUIs in .NET - heavily uses delegates - event subscription - event notification - Visual Studio .NET contains IDE to assist GUI development - choose New Project -> “Windows Application” (instead of “Console Application”) - Add WinForms as needed - Drop components from ToolBox on each form - Change component state in IDE generated code - Code event handlers
  • 115. 115 Example : incrementor System.Windows.Forms.Button declares properties : Name, Text fires events : System.EventHandler Click System.Windows.Forms.TextBox declares properties : Name, Text System.Windows.Forms.Form declares properties : Name, Text Controls (container) fires events : System.EventHandler Load
  • 116. 116 Example : incrementor Main()-method using System; using System.Collections.Generic; using System.Windows.Forms; namespace WindowsApplication1 { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } } IDE-generated [Program.cs]
  • 117. 117 Example : incrementor Form1-class namespace WindowsApplication1 { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources /// should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } IDE-generated (edited) [Form1.Designer.cs]
  • 118. 118 Example : incrementor #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.button1 = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // button1 // this.button1.Location = new System.Drawing.Point(92, 150); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 0; this.button1.Text = "Click here"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); IDE-generated (edited) [Form1.Designer.cs] Form1-class
  • 119. 119 Example : incrementor Form1-class // // textBox1 // this.textBox1.Location = new System.Drawing.Point(78, 103); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(100, 20); this.textBox1.TabIndex = 1; this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged); IDE-generated (edited) [Form1.Designer.cs]
  • 120. 120 Example : incrementor // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(292, 266); this.Controls.Add(this.textBox1); this.Controls.Add(this.button1); this.Name = "Form1"; this.Text = "Incrementer"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox textBox1; } } IDE-generated (edited) [Form1.Designer.cs] Form1-class
  • 121. 121 Example : incrementor namespace WindowsApplication1 { public partial class Form1 : Form { int i = 0; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e){} private void button1_Click(object sender, EventArgs e) { i++; textBox1.Text = ""+i; } private void textBox1_TextChanged(object sender, EventArgs e) { } } } template IDE-generated handler code to add ! [Form1.cs] Form1-class
  • 122. 122 C# and .NET 1. Introduction 2. C# versus Java : highlights 3. C# data types 4. Defining custom data types 5. Operator Overloading 6. Event driven programming 7. .NET Framework Class Library 8. A GUI in C# 9. A web service in C#
  • 123. 123 .NET / C# web service - actually part of ASP.NET - uses .asmx file to bind server to code - C# : - web service derives from System.Web.Services.WebService - class must be public, must have public constructor - has [WebService] attribute paramters : - Description : info - Name : default = class name - Namespace : XML-namespace - every exposed service method should have attribute [WebMethod] parameters include : -Description : info -EnableSession : default = false - MessageName : default = method name
  • 124. 124 .NET / C# web service web server - runs .asmx -file - locates class files referred - loads, runs and manages code client - statically retrieves WSDL document - generates and compiles proxy class - instantiates service proxy - call methods on the proxy
  • 125. 125 Hello Service Server side Create ASP.NET Web Service project File -> New -> Web Site ASP.NET Web Service template Edit [WebService] attribute (if necessary) Add class logic, give any WS method [WebMethod] attribute Build project Run Project Check if service is running (WSDL-file) http://localhost:1665/WebSite1/?.asmx ? WSDL Invoke method from browser to check proper functioning
  • 126. 126 Hello Service Service.asmx <%@ WebService Language="C#" CodeBehind="~/App_Code/Service.cs" Class="Service" %>
  • 127. 127 Hello Service Service.cs using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class Service : System.Web.Services.WebService { public Service () { //Uncomment the following line if using designed components //InitializeComponent(); } [WebMethod] public string HelloWorld(string e) { return "Hello World there, "+e; } }
  • 129. 129 Hello ServiceService invocation from browser (http://localhost:1655/WebSite1/Service.asmx?op=HelloWorld) Answer : <string>Hello World there, MyName</string>
  • 130. 130 Hello Service Client side Create Windows Console project (or GUI project ...) Open WS project and add to current solution Add Web Reference -> Browse local host -> Select Web Reference (= namespace for proxy) (Here : HelloService) Add client code -> instantiate proxy object -> call WS methods on proxy
  • 131. 131 Hello Service using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication3 { class Program { static void Main(string[] args) { HelloService.Service s = new HelloService.Service(); Console.WriteLine(" -> " + s.HelloWorld("Georgie ")); } } } -> Hello World there, Georgie Press any key to continue . . .