.NET et C #

motiontachyphagiaΛογισμικό & κατασκευή λογ/κού

5 Ιουλ 2012 (πριν από 4 χρόνια και 9 μήνες)

586 εμφανίσεις

2
Page 2
Daniel HERLEMONT 5
chien
MSIL
chat
.cs
souris
MSIL
chien
.vb
chat
MSIL
souris
c++
déploiement
Windows
JIT
Linux (?)
JIT
CLR : moteur exécution
en langage commun
CLR : Common Language Runtime
JIT : Just in Time (2eme compilateur)
Mécanisme de fonctionnement de MS.NET
Les applications c#, VB, c++ peuvent communiquer via le CLR
En réalité le même programme peut etre écrit dans un lagag e et décompilé dans un autre
On retrouve les memes classes/packages dans les differentes environnements, CS, VB, C++
Daniel HERLEMONT 6
VS.NET
VS.NET
Common Language Runtime
Common Language Runtime
System
System
System.Data (ADO.NET)
System.Xml
Design
ADO
Adapters
SQL
Globalization
Diagnostics
Configuration
Collections
Resources
Reflection
Net
IO
Threading
Text
ServiceProcess
Security
Runtime
InteropServices
Remoting
Serialization
XPath
XSLT
Serialization
System.Drawing
JIT
GC
MSIL
App Domain Loader
Common Type System
Class Loader
System.Web
Configuration
SessionState
Caching
Security
System.Web.Services
Description
Protocols
UI
HtmlControls
WebControls
Discovery
C#
VC/MC++
Imaging
Drawing2D
Text
Printing
JScript
VB
Platform Abstraction Layer
Platform Abstraction Layer
Boot Loader
Sync
Threads
Networking
Timers
Filesystem
System.WinForms
Design
ComponentModel
Debugger
Designers
SDK Tools
SDK Tools
CorDBG
ILAsm
ILDbDump
SN
ILDAsm
MetaInfo
PEVerify
ECMA
-
335
ECMA-334
CLI Standards
Daniel HERLEMONT
7
System.Data
Design
OLEDB
SQLTypes
SQL
System
Globalization
Diagnostics
Configuration
Collections
Resources
Reflection
Net
IO
Threading
Text
ServiceProcess
Security
Runtime
InteropServices
Remoting
Serialization
System.Xml
XPath
XSLT
Serialization
System.Web
Configuration
SessionState
Caching
Security
Services
Description
Discovery
Protocols
UI
HtmlControls
WebControls
System.Drawing
Imaging
Drawing2D
Text
Printing
Le framework.NET Les classes du framework
System.Windows.Forms
Form
Button
MessageBox
ListControl
Tous les langages de l’environnement.NET ont acceès au mêmes classes, notamment, les classes fondementales
Daniel HERLEMONT
8
Qu’est-ce c’est C# ?
￿
Langage proposé par Microsoft, standardisé par ECMA, ressemble la syntaxe de
Java
￿
Langage orienté objet
￿
Une partie évolue vers langage orienté et langage de programmation de component
￿
Dérivé de C++
￿
MFC est remplacée par librairie .NET Framework
￿
Combinaison entre la force de C++ et la simplicité de Visual Basic
￿
Cross Plate-forme
￿
Cross Langage
3
Page 3
Daniel HERLEMONT 9
C# : comment ça marche ?
Code
natif
(selon OS)
JIT
.cs
Code source
‘.exe’
‘.dll’
Microsoft
Intermediate
Language
(MSIL)
CLS
‘Règle de
tranformation
en .NET’
Just in Time
Compiler
CLR Common Runtime Language
Daniel HERLEMONT 10
Avantages C#
Avantages C#
Plus ouvert, plus de productivit
Plus ouvert, plus de productivit
é
é
, programmes
, programmes
plus fiables et moins difficile a mettre au point
plus fiables et moins difficile a mettre au point
Interop
Interop
é
é
rabilit
rabilit
é
é
dans le futur avec Framework
dans le futur avec Framework
.Net (Windows,
.Net (Windows,
»
»
Linux,Unix
Linux,Unix
»
»
)
)
De plus en plus utilis
De plus en plus utilis
é
é
dans les applications
dans les applications
financi
financi
è
è
res (front & middle) au d
res (front & middle) au d
é
é
triment du
triment du
C++
C++
Inconv
Inconv
é
é
nients C#
nients C#
Apprendre nouveau concept de base (.Net)
Apprendre nouveau concept de base (.Net)
Apprendre nouveau langage
Apprendre nouveau langage
(temps d
(temps d


estimation
estimation
environ 4 semaines)
environ 4 semaines)
C# vs C++
Daniel HERLEMONT
11
￿
Peu de pointeur
￿
Conversion automatique (boxing)
￿
list.Add(1);
￿
list.Add(13.12);
￿
Versioning
￿
C# demande le développer de clarifier la création de la version librairie
créée.
￿
Utilise le keyword ‘new’ et ‘override
￿
Utiliser la librairie de framework.NET
￿
Threading, Collection, XML, ADO+, ASP+, GDI+ & WinForms libraries
￿
C# élimine header .h
￿
C# non pointeur (très limité).
￿
C# est un langage objet orienté pur avec tous les objets et types dérivés de
la classe Object.
￿
Codé géré (pas besoin de ‘’free’’ et ‘’delete’’ – garbage collector)
￿
Possibilité d’intégrer du code source natif C ou C++
Plus détails :
￿
http://msdn.microsoft.com/library/default.asp?url=/library/enus/cscon/html/vclrfcompa
risonbetweenccsharp.asp
Avantages C#
Daniel HERLEMONT
12
Inconvénients de C#
￿
Technologie Windows 100%, porter Framework sur Linux “à voir” (projet
Mono)
￿
.NET et C# sont des "standards ouverts" ne signifie pas nécessairement des
"environnements ouverts".
￿
La première fois est lente (à cause de compilateur 2-time)
￿
Relativement nouveau (bibliotheques spécialisées, …)
4
Page 4
Daniel HERLEMONT 13
Opérateurs
.NET Framework, C# et .NET Remoting 13
C#
￿
Unaires :+ -! ~ ++x --x (T)x
￿
Arithmétiques :* / % + -
￿
Décalage :<< >>
￿
Relationnels :< > <= >= == !=
￿
Logiques :& ^ |
￿
Conditionnels :&& || ?:
￿
Assignation := *= /= %= += -=
<<= >>= &= ^= |=
Daniel HERLEMONT 14
Instructions
.NET Framework, C# et .NET Remoting 14
C#
￿
Blocs
{ ... };
￿
Libellés
x: instruction;
￿
Selections
if(x == 1) switch(i){ {
if(y == 2) case 0:{ case 1:
F();Choix();
} break;
else{ default:
G();ChoixAutre();
} break;
} }
Daniel HERLEMONT
15
Instructions
.NET Framework, C# et .NET Remoting 15
C#
￿
Itérations
while(x!= 0) { ... } for(int i = 0; i < n; i++) { ... }
do { ... } while(x == 0);foreach(object o in collecti on) {
... }
￿
Sauts
break;continue;
goto libelle;return value;
￿
Gestion des exceptions
try throw new Exception();
{ ... }
catch(ArgumentException e)
{ ... }
catch(Exception e)
{ ... }
finally
{ ... }
Daniel HERLEMONT
16
Types
.NET Framework, C# et .NET Remoting 16
C#
￿
Valeurs
￿
Types prédéfinis
￿
Enumérations
￿
Structures
￿
Allocation dans la pile (stack)
￿
Ne peut être null
￿
Références
￿
Tableaux
￿
Délégués
￿
Classes
￿
Interfaces
￿
Allocation dans le tas (heap)
￿
Peut être null
5
Page 5
Daniel HERLEMONT 17
Types prédéfinis
.NET Framework, C# et .NET Remoting 17
C#
char val = 'h';Caractère Unicodechar
decimal val = 1.23M;Décimal (28 chiffres significatifs)decimal
bool val1 = true;
bool val2 = false;
Booléenbool
double val1 = 1.23;
double val2 = 4.56D;
Flottant double précision (64 bits, 3.4E +/- 38, 7 chiffres significatifs)double
float val = 1.23F;
Flottant simple précision (32 bits, 1.7E +/- 308 15 chiffres significatifs)
float
ulong val1 = 12;
ulong val2 = 34U;
ulong val3 = 56L;
ulong val4 = 78UL;
Entier non signé de 64 bitsulong
uint val1 = 12;
uint val2 = 34U;
Entier non signé de 32 bitsuint
ushort val = 12;Entier non signé de 16 bitsushort
byte val = 12;Entier non signé de 8 bitsbyte
long val1 = 12;
long val2 = 34L;
Entier signé de 64 bitslong
int val = 12;
Entier signé de 32 bits
int
short val = 12;Entier signé de 16 bitsshort
sbyte val = 12;Entier signé de 8 bitssbyte
string s = "Hello";Séquence de caractères Unicodestring
object o = null;Type de base de tous les autres typesobject
ExempleDescriptionType
Daniel HERLEMONT 18
Enumerations
.NET Framework, C# et .NET Remoting 18
C#
enum Color : long Color color;{ switch(color)
Red,{
Green,case Color.Red:
Blue...
} break;
case Color.Blue:
...
break;
case Color.Green:
...
break;
default:
break;
}
Daniel HERLEMONT
19
Structures
.NET Framework, C# et .NET Remoting 19
C#
struct Point{
public int x,y;
}
struct Point{
public int x,y;
public Point(int x, int y) { this.x = x; this.y = y; }
}
Daniel HERLEMONT
20
Tableaux
.NET Framework, C# et .NET Remoting 20
C#
￿
Une dimension
int[] myArray = new int[] {1, 3, 5, 7, 9};
string[] weekDays = {"Sun","Sat","Mon","Tue","Wed","Thu","Fri"};
￿
Plusieurs dimensions
int[,,] myArray = new int [4,2,3];
int[,] myArray = new int[,] {{1,2}, {3,4}, {5,6}, {7,8}};
￿
Jagged (tableau de tableaux)
int[][,] myJaggedArray = new int [3][,]
{
new int[,] { {1,3}, {5,7} },
new int[,] { {0,2}, {4,6}, {8,10} },
new int[,] { {11,22}, {99,88}, {0,9} }
};
6
Page 6
Daniel HERLEMONT 21
Orientation Objet
￿
programmation procédurale : P.P. (Pascal, C, etc.)
￿
programmation orientée objet : P.O.O. (C++, Java, C#)
￿
Principaux concepts de la programmation objet
￿
Encapsulation, abstraction, interfaces, …
￿
Héritage (simple, multiple)
￿
Polymorphisme
Daniel HERLEMONT 22
Class basics
class myClass
{
private string myVar;
public myClass() {}
protected void myMethod(int parameter) {
//do stuff here
}
}
Daniel HERLEMONT
23
Classes
.NET Framework, C# et .NET Remoting 23
C#
￿
Nom
￿
Attribut d’accessibilité
￿
public non limité
￿
protected limité à la classe et aux classes dérivées
￿
private limité à la classe
￿
internal limité à l’assemblage
￿
protected internal limité à l’assemblage et aux classes dérivées
￿
Attribut abstract (abstrait)
￿
Attribut sealed (sellé)
￿
Classe de base (héritage simple de classe)
￿
Interfaces implémentées (héritage multiple d’interfaces)
￿
Membres
Daniel HERLEMONT
24
Inheritance
￿
C# only supports single inheritance
￿
Specify inheritance like so:
class myClass: myBaseClass
7
Page 7
Daniel HERLEMONT 25
Method example
class myClass{
private string myVar;
public myClass() {}
public void myMethod(int parameter) {
//do stuff here
}
public static void PrintStuff() {}
}
class myCallerClass{
public myCallerClass() {
myClass.PrintStuff();
myClass myInstance= new myClass();
myInstance.myMethod(5);
}
}
Daniel HERLEMONT 26
Membres
.NET Framework, C# et .NET Remoting 26
C#
￿
Constantes
￿
Champs
￿
Méthodes
￿
Constructeurs
￿
Destructeurs
￿
Types
￿
Propriétés
￿
Indexeurs
￿
Opérateurs
￿
Événements
Daniel HERLEMONT
27
Constantes
.NET Framework, C# et .NET Remoting 27
C#
class A{
public const double X = 1.0;
public const double Y = 2.0;
public const double Z = 3.0;
}
class B{
public const int X = C.Z + 1;
public const int Y = 10;
}
class C{
public const int Z = B.Y + 1;
}
Daniel HERLEMONT
28
Champs
.NET Framework, C# et .NET Remoting 28
C#
public class Color{
public static readonly Color Black = new Color(0, 0, 0);
public static readonly Color White = new Color(255, 255, 255);
private byte red, green, blue;
public Color(byte r, byte g, byte b) {
red = r;
green = g;
blue = b;
}
}
￿
Attributs d’accessibilité
￿
public non limité
￿
protected limité à la classe et aux classes dérivées
￿
private limité à la classe
￿
internal limité à l’assemblage
￿
Attributs
￿
new champ cachant (classe dérivé)
￿
static champ de classe
￿
readonly champ en lecture seule (initialisé par le constructeur)
￿
volatile champ volatile
8
Page 8
Daniel HERLEMONT 29
Méthodes
.NET Framework, C# et .NET Remoting 29
C#
￿
Nom
￿
Attribut d’accessibilité
￿
public non limité
￿
protected limité à la classe et aux classes dérivées
￿
private limité à la classe
￿
internal limité à l’assemblage
￿
Attributs new, static, virtual (virtuel), abstract, sealed, override
(surcharge), extern
￿
Type de retour
￿
Paramètres
Daniel HERLEMONT 30
Méthodes abstraites
.NET Framework, C# et .NET Remoting 30
C#
public abstract class Shape{
public abstract void Paint(Graphics g, Rectangle
r);
}
public class Ellipse: Shape{
public override void Paint(Graphics g, Rectangle
r) {
g.DrawEllipse(r);
}
}
public class Box: Shape{
public override void Paint(Graphics g, Rectangle
r) {
g.DrawRect(r);
}
}
Daniel HERLEMONT
31
Properties
￿
Properties are NOT fields
￿
Fields are variables declared in the class
￿
Properties are “wrappers” for fields
￿
Get/Set:
private string mystring;
public string MyString {
get { return mystring; }
set {mystring = value; }
}
Daniel HERLEMONT
32
Méthodes virtuelles
.NET Framework, C# et .NET Remoting 32
C#
class A{
public virtual void F() {
Console.WriteLine("A.F"); }
}
class B: A{
public override void F() {
Console.WriteLine("B.F"); }
}
class Test
class Test
{
{
static void Main() {
static void Main() {
B b = new B();
B b = new B();
A a = b;
A a = b;
a.F
a.F
();
();
}
}
}
}
> B.F
> B.F
9
Page 9
Daniel HERLEMONT 33
Constructeurs (instance)
.NET Framework, C# et .NET Remoting 33
C#
class Point{
public double x, y;
public Point(){
this.x = 0;
this.y = 0;
}
public Point(double x, double y){
this.x = x;
this.y = y;
}
}
￿
Initialiser l’instance d’une classe
￿
En cas d’absence de constructeur, un constructeur sans paramètre est implicitement créé
Daniel HERLEMONT 34
Constructeur (classe)
.NET Framework, C# et .NET Remoting 34
C#
class A{
public static int X;
static A() {
X = B.Y + 1;
}
}
class B{
public static int Y = A.X + 1;
static B() {}
static void Main() {
Console.WriteLine("X = {0}, Y = {1}", A.X, B.Y);
}
}
￿
Initialiser une classe
￿
Ne peut être appelé explicitement
￿
Appelé automatiquement
￿
Pas d’attribut d’accessibilité, pas de paramètre
Daniel HERLEMONT
35
Destructeur
.NET Framework, C# et .NET Remoting 35
C#
class A{
public static int X;
static A() {
X = B.Y + 1;
}
}
class B{
public static int Y = A.X + 1;
static B() {}
static void Main() {
Console.WriteLine("X = {0}, Y = {1}", A.X, B.Y);
}
}
￿
Appelé automatiquement lors du processus de garbage collection
￿
Ne peut être appelé explicitement
￿
Pas d’attribut d’accessibilité, pas de paramètre
Daniel HERLEMONT
36
Types
.NET Framework, C# et .NET Remoting 36
C#
public class List{
// Private data structure
private class Node
{
public object Data;
public Node Next;
public Node(object data, Node next)
{
this.Data = data;
this.Next = next;
}
}
private Node first = null;
private Node last = null;
// Public interface
public void AddToFront(object o) {...}
public void AddToBack(object o) {...}
public object RemoveFromFront() {...}
public object RemoveFromBack() {...}
public int Count { get {...} }
}
￿
Déclaration d’un type à l’intérieur d’une classe
10
Page 10
Daniel HERLEMONT 37
Propriétés
.NET Framework, C# et .NET Remoting 37
C#
￿
Accéder aux caractéristiques d’un objet ou d’une classe
￿
longueur d’une chaîne de caractères
￿
taille d’un tableau
￿
titre d’une fenêtre
￿
dimensions d’une image
￿

￿
Deux comportements
￿
Lecture (get)
￿
Écriture (set)
￿
Mêmes attributs que les méthodes
Daniel HERLEMONT 38
Propriétés
.NET Framework, C# et .NET Remoting 38
C#
abstract class A{
int y;
public virtual int X {
get { return 0; }
}
public virtual int Y {
get { return y; }
set { y = value; }
}
public abstract int Z { get; set; }
}
class B: A{
int z;
public override int X {
get { return base.X + 1; }
}
public override int Y {
set { base.Y = value < 0? 0: value; }
}
public override int Z {
get { return z; }
set { z = value; }
}
}
Daniel HERLEMONT
39
Indexeurs
.NET Framework, C# et .NET Remoting 39
C#
￿
Indexer une classe à la manière d’un tableau
public class Stack{
private Node GetNode(int index) {
Node temp = first;
while (index > 0 && temp!= null) {
temp = temp.Next;
index--;
}
if (index < 0 || temp == null)
throw new Exception("Index out of range.");
return temp;
}
public object this[int index] {
get {
return GetNode(index).Value;
}
set {
GetNode(index).Value = value;
}
}
}
Daniel HERLEMONT
40
Opérateurs
.NET Framework, C# et .NET Remoting 40
C#
public struct Digit{
byte value;
public Digit(byte value) {
if (value < 0 || value > 9) throw new ArgumentException();
this.value = value;
}
public Digit(int value): this((byte) value) {}
public static implicit operator byte(Digit d) {
return d.value;
}
public static explicit operator Digit(byte b) {
return new Digit(b);
}
}
11
Page 11
Daniel HERLEMONT 41
Opérateurs
.NET Framework, C# et .NET Remoting 41
C#
public struct Digit{
byte value;
public Digit(byte value) {
if (value < 0 || value > 9) throw new ArgumentException();
this.value = value;
}
public Digit(int value): this((byte) value) {}
public static Digit operator+(Digit a, Digit b) {
return new Digit(a.value + b.value);
}
public static Digit operator-(Digit a, Digit b) {
return new Digit(a.value - b.value);
}
}
Daniel HERLEMONT 42
Opérateurs
.NET Framework, C# et .NET Remoting 42
C#
public struct Digit{
byte value;
public Digit(byte value) {
if (value < 0 || value > 9) throw new ArgumentException();
this.value = value;
}
public Digit(int value): this((byte) value) {}
public static bool operator==(Digit a, Digit b) {
return a.value == b.value;
}
public static bool operator!=(Digit a, Digit b) {
return a.value!= b.value;
}
public override bool Equals(object value) {
if (value == null) return false;
if (GetType() == value.GetType()) return this == (Digit)value;
return false;
}
}
Daniel HERLEMONT
43
Délégués
.NET Framework, C# et .NET Remoting 43
C#
￿
Pointeurs de méthodes (vulgarisation)
￿
Encapsule à la fois un objet et une méthode
￿
Peut « pointer » vers plusieurs méthodes
delegate void D(int x);
class C{
public static void M1(int i) {...}
public static void M2(int i) {...}
}
class Test{
static void Main() {
D cd1 = new D(C.M1); // M1
D cd2 = new D(C.M2); // M2
D cd3 = cd1 + cd2; // M1 + M2
D cd4 = cd3 + cd1; // M1 + M2 + M1
D cd5 = cd4 + cd3; // M1 + M2 + M1 + M1 + M2
}
}
Daniel HERLEMONT
44
Événements
.NET Framework, C# et .NET Remoting 44
C#
￿
Mécanisme de notification
￿
Basé sur les délégués
12
Page 12
Daniel HERLEMONT 45
Événements
.NET Framework, C# et .NET Remoting 45
C#
public delegate void EventHandler(object sender, EventArgs e);
public class Button: Control{
public event EventHandler Click;
protected void OnClick(EventArgs e) {
if (Click != null) Click(this, e);
}
}
public class Form{
Button Button1 = new Button();
public Form() {
Button1.Click += new EventHandler(Button1_Click);
}
~Form() {
Button1.Click -= new EventHandler(Button1_Click);
}
void Button1_Click(object sender, EventArgs e) {
Console.WriteLine("Button1 was clicked!");
}
}
Daniel HERLEMONT 46
Espaces de noms
.NET Framework, C# et .NET Remoting 46
C#
￿
Conteneur de classes ou d’espaces de nom
￿
Organiser des classes hiérarchiquement
￿
Structurer les assemblages
class A {} // A
namespace X // X{
class B // X.B{
class C {} // X.B.C
}
namespace Y // X.Y{
class D {} // X.Y.D
}
}
Using tells the compiler what prefixes to try on stuff it
can’t figure out:
using System.Collections;
ArrayList myList=new ArrayList()
Daniel HERLEMONT
47
Interfaces
.NET Framework, C# et .NET Remoting 47
C#
￿
Nom
￿
Attribut d’accessibilité
￿
public non limité
￿
protected limité à la classe et aux classes dérivées
￿
private limité à la classe
￿
internal limité à l’assemblage
￿
Interfaces de base (héritage multiple d’interfaces)
￿
Membres
￿
Méthodes
￿
Propriétés
￿
Indexeurs
￿
Événements
Daniel HERLEMONT
48
Productivity features
￿
parameter arrays
￿
ref and out parameters
￿
overflow checking
￿
foreach statement
￿
lock statement
￿
switch on string
13
Page 13
Daniel HERLEMONT 49
ref and out parameters
￿
Use “ref” for in/out parameter passing
￿
Use “out” to return multiple values
￿
Must repeat ref/out at call site
￿
Equivalent to &
static void Swap(
static void Swap(
ref
ref
int a,
int a,
ref
ref
int b) {...}
int b) {...}
static void
static void
Divide(int
Divide(int
dividend, int divisor,
dividend, int divisor,
out
out
int result,
int result,
out
out
int remainder) {...}
int remainder) {...}
static void Main() {
static void Main() {
int x = 1, y = 2;
int x = 1, y = 2;
Swap(
Swap(
ref
ref
x,
x,
ref
ref
y);
y);
}
}
Daniel HERLEMONT 50
foreach statement
￿
Iteration of arrays
￿
Iteration of IEnumerable collections
ArrayList
ArrayList
accounts =
accounts =
Bank.GetAccounts
Bank.GetAccounts
(...);
(...);
foreach
foreach
(Account a in accounts) {
(Account a in accounts) {
if (a.Balance < 0)
if (a.Balance < 0)
Console.WriteLine(a.CustName
Console.WriteLine(a.CustName
);
);
}
}
public static void Main(string[]
public static void Main(string[]
args
args
) {
) {
foreach
foreach
(string s in
(string s in
args
args
)
)
Console.WriteLine(s
Console.WriteLine(s
);
);
}
}
Daniel HERLEMONT
51
Overflow checking
￿
Integer arithmetic operations
￿
C, C++, Java silently overflow
￿
checked vs. unchecked contexts
￿
Default is unchecked, except for constants
￿
Change with “/checked” compiler switch
int i =
int i =
checked
checked
(x * y);
(x * y);
checked
checked
{
{
int i = x * y;
int i = x * y;
}
}
Daniel HERLEMONT
52
Switch on string
Color
Color
ColorFromFruit(string
ColorFromFruit(string
s) {
s) {
switch(s.ToLower
switch(s.ToLower
()) {
()) {
case "apple":
case "apple":
return Color.Red;
return Color.Red;
case "banana":
case "banana":
return Color.Yellow;
return Color.Yellow;
case "carrot":
case "carrot":
return Color.Orange;
return Color.Orange;
default:
default:
throw new
throw new
InvalidArgumentException
InvalidArgumentException
();
();
}
}
}
}
14
Page 14
Daniel HERLEMONT 53
Polymorphism in C#
public class Orange : Fruit {
public class Orange : Fruit {
public
public new
new
string Colour() {return "Orange";}
string Colour() {return "Orange";}
public
public override
override
string Shape() {return "Round";}
string Shape() {return "Round";}
}
}
public class Fruit {
public class Fruit {
public
public
virtual
virtual
string Shape() {return "Not sure";}
string Shape() {return "Not sure";}
public string Colour() {return "You tell me";}
public string Colour() {return "You tell me";}
}
}
Fruit someFruit = new Orange();
Fruit someFruit = new Orange();
string a = someFruit.Shape(); // "Round"
string a = someFruit.Shape(); // "Round"
string b = someFruit.Colour(); // "You tell me"
string b = someFruit.Colour(); // "You tell me"
Orange anOrange = (Orange)someFruit;
Orange anOrange = (Orange)someFruit;
string c = anOrange.Shape(); // "Round"
string c = anOrange.Shape(); // "Round"
string d = anOrange.Colour(); // "Orange"
string d = anOrange.Colour(); // "Orange"
Daniel HERLEMONT 54
Error handling
￿
System.Exception
￿
Gets code information like:
￿
Stack trace
￿
Line and file info
￿
Detailed error message
￿
Use in try…catch block

ArrayList myList;
try {
myList.Clear();
} catch (System.NullReferenceException e) {
Console.WriteLine(“variable not initialized”);
}
To throw an error say:
To throw an error say:
throw <exception object>
throw <exception object>
Or:
Or:
throw new <exception class>
throw new <exception class>
Exceptions are very costly, don
Exceptions are very costly, don


t throw them unless there is
t throw them unless there is
an error
an error
Daniel HERLEMONT
55
public class List
public class List
{
{
private object[] elements;
private object[] elements;
private int count;
private int count;
public void
public void
Add(object
Add(object
element) {
element) {
if (count == elements.Length) Resize(count * 2);
if (count == elements.Length) Resize(count * 2);
elements[count++] = element;
elements[count++] = element;
}
}
public object
public object
this[int
this[int
index] {
index] {
get { return elements[index]; }
get { return elements[index]; }
set { elements[index] = value; }
set { elements[index] = value; }
}
}
public int Count {
public int Count {
get { return count; }
get { return count; }
}
}
}
}
Generics
public class List
public class List
<
<
ItemType
ItemType
>
>
{
{
private
private
ItemType
ItemType
[] elements;
[] elements;
private int count;
private int count;
public void
public void
Add(
Add(
ItemType
ItemType
element) {
element) {
if (count == elements.Length) Resize(count * 2);
if (count == elements.Length) Resize(count * 2);
elements[count++] = element;
elements[count++] = element;
}
}
public
public
ItemType
ItemType
this[int
this[int
index] {
index] {
get { return elements[index]; }
get { return elements[index]; }
set { elements[index] = value; }
set { elements[index] = value; }
}
}
public int Count {
public int Count {
get { return count; }
get { return count; }
}
}
}
}
List
List
intList
intList
= new List();
= new List();
intList.Add(1);
intList.Add(1);
intList.Add(2);
intList.Add(2);
intList.Add("Three
intList.Add("Three
");
");
int i = (int)intList[0];
int i = (int)intList[0];
List
List
intList
intList
= new List();
= new List();
intList.Add(1); // Argument is boxed
intList.Add(1); // Argument is boxed
intList.Add(2); // Argument is boxed
intList.Add(2); // Argument is boxed
intList.Add("Three
intList.Add("Three
"); // Should be an error
"); // Should be an error
int i = (int)intList[0]; // Cast required
int i = (int)intList[0]; // Cast required
List
List<int>
<int>
intList
intList
= new List
= new List<int>
<int>
();
();
intList.Add(1); // No boxing
intList.Add(1); // No boxing
intList.Add(2); // No boxing
intList.Add(2); // No boxing
intList.Add("Three
intList.Add("Three
"); // Compile
"); // Compile
-
-
time error
time error
int i = intList[0]; // No cast required
int i = intList[0]; // No cast required
Daniel HERLEMONT
56
Generics
￿
Why generics?
￿
Compile-time type checking
￿
Performance (no boxing, no downcasts)
￿
Reduced code bloat (typed collections)
￿
C# generics vs. C++ templates
￿
C# generics are checked at declaration
￿
C# generics are instantiated at run-time
￿
C# generics vs. proposed Java generics
￿
C# generics work over entire type system
￿
C# generics preserve types at run-time
15
Page 15
Daniel HERLEMONT 57
Generics In VB
Public Class List(
Of T
)
Private elements() As
T
Private elementcount As Integer
Public Sub Add(ByVal element As
T
)
If elementcount = elements.Length Then
Resize(elementcount * 2)
elements(elementcount) = element
count += 1
End Sub
Public Default Property Item(ByVal index As Integer) As
T
Get
Return elements(index)
End Get
Set (ByVal Value As
T
)
elements(index) = Value
End Set
End Property
Dim intList As New List(Of Integer)
intList.Add(1)// No boxing
intList.Add(2)// No boxing
intList.Add("Three")// Compile-time error
Dim i As Integer = intList(0)// No cast required
Daniel HERLEMONT 58
Generics In C++
generic<typename T>
public ref class List {
array<T>^ elements;
int count;
public:
void Add(T element) {
if (count == elements->Length) Resize(count * 2);
elements[count++] = element;
}
property T default [int index] {
T get() { return elements[index]; }
void set(T value) { elements[index] = value; }
}
property int Count {
int get() { return count; }
}
};
List<int>^ intList = gcnew List<int>();
intList->Add(1);// No boxing
intList->Add(2);// No boxing
intList->Add("Three");// Compile-time error
int i = intList[0];// No cast required
Daniel HERLEMONT
59
Throwing an Exception
By an invalid operation (implicit exception)
Division by 0
Index overflow
Acess via a null reference
...
By a throw statement (explicit exception)
throw new FunnyException(10);
class FunnyException: ApplicationException {
public int errorCode;
public FunnyException(int x) { errorCode = x; }
}
(By calling a method that throws an exception but does not catch it)
s = new FileStream(...);
Daniel HERLEMONT
60
Exception Hierarchy (excerpt)
Exception
SystemException
ArithmeticException
DivideByZeroException
OverflowException
...
NullReferenceException
IndexOutOfRangeException
InvalidCastException
...
ApplicationException
...
user-defined exceptions
...
IOException
FileNotFoundException
DirectoryNotFoundException
...
WebException
...
16
Page 16
Daniel HERLEMONT 61
FileStreams = null;
try {
s = new FileStream(curName, FileMode.Open);
...
} catch (FileNotFoundException e) {
Console.WriteLine("file {0} not found", e.FileName);
} catch (IOException) {
Console.WriteLine("some IO exception occurred");
} catch {
Console.WriteLine("some unknown error occurred");
} finally {
if (s != null) s.Close();
}
catch clauses are checked in sequential order.
finally clause is always executed (if present).
Exception parameter name can be omitted in a catch clause.
Exception type must be derived from System.Exception.
If exception parameter is missing, System.Exception is assumed.
Daniel HERLEMONT 62
Traditional Collections
￿
System.Collection namespace introduced in 1.0 version of .NET
Framework
￿
Useful container types
￿
Lists
￿
Dictionaries
￿
Hashtables
￿
CollectionBase
Daniel HERLEMONT
63
Sample Class Definition
class Book{
private int bookNumber = 0;
public int BookNumber{
get { return this.bookNumber; }
set { this. bookNumber = value; }
}
public Book( int _bookNumber ){
this.bookNumber = _bookNumber;
}
}
Daniel HERLEMONT
64
Sample ArrayList Use
ArrayList bookList = new ArrayList();
for( int i = 0; i < 20; i++){
bookList.Add( new Book(i) );
}
IEnumerator listEnum= bookList.GetEnumerator();
while( listEnum.MoveNext() ){
Console.WriteLine(“{0}”,
((Book)(listEnum.Current)).BookNumber);
}
17
Page 17
Daniel HERLEMONT 65
Drawbacks
￿
No type checking enforcement at compile time
￿
Doesn’t prevent adding unwanted types
￿
Can lead to difficult to troubleshoot issues
￿
Runtime errors!
￿
All items are stored as objects
￿
Must be cast going in and coming out
￿
Performance overhead of boxing and unboxing specific types
Daniel HERLEMONT 66
VB.NET Generics Sample 1
Dim testCol As New List(Of int32)()
For i as int32 = 0 To 19
testCol.Add(i)
Next
For each someInt As int32 in testCol
Console.WriteLine(“{0}”, someInt)
Next
Daniel HERLEMONT
67
C# Generics Sample 1
ArrayList<int> testCol = new ArrayList<int>();
for (int i = 0; i < 20; i++){
testCol.Add(i);
}
foreach (int someInt in testCol){
Console.WriteLine(“{0}”, someInt);
}
Daniel HERLEMONT
68
VB.NET Generics Sample 2
Dim bookList As New List(Of Book)()
For i as int32 = 0 To 19
bookList.Add(New Book(i))
Next
For each book As Book in bookList
Console.WriteLine(“{0}”, book.BookNumber)
Next
18
Page 18
Daniel HERLEMONT 69
C# Generics Sample 2
ArrayList<Book> bookList = new ArrayList<Book>();
for (int i = 0; i < 20; i++){
bookList.Add( new Book(i) );
}
foreach (Book book in bookList){
Console.WriteLine(“{0}”, book.BookNumber);
}
Daniel HERLEMONT 70
C++ Templates?
￿
Generics are NOT equal to Templates
￿
Compile-Time vs. Run-Time
￿
Templates = Compile-Time
￿
Generics = Run-Time
￿
Code Bloat?
￿
Pros and Cons for each
Daniel HERLEMONT
71
Streaming Framework
￿
System.IOcontains types for input and output
￿
Base class Stream defines an abstract protocol for byte-oriented input and output
￿
Specialization for different media
￿
Streams support synchronous and asynchronous protocol
￿
Readers and Writers for formatting
FileStream
MemoryStream
NetworkStream
CryptoStream
BufferedStream
Stream
DeflateStream
GZipStream
Daniel HERLEMONT
72
Class Stream
public abstract class
Stream: MarshalByRefObject, IDisposable {
public abstract bool
CanRead {
get
; }
public abstract bool
CanSeek {
get
; }
public abstract bool
CanWrite {
get
; }
public abstract int
Read(
out byte
[] buff,
int
offset,
int
count);
public abstract void
Write(
byte
[] buff,
int
offset,
int
count);
public virtual int
ReadByte();
public virtual void
WriteByte(
byte
value);
public virtual
IAsyncResult BeginRead(…);
public virtual
IAsyncResult BeginWrite(…);
public virtual int
EndRead(…);
public virtual int
EndWrite(…);
public abstract long
Length {
get
; }
public abstract long
Position {
get
;
set
; }
public abstract long
Seek(
long
offset, SeekOrigin origin);
public abstract void
Flush();
public virtual void
Close();
...
}
• Elementary properties of
stream
• Synchronous reading and
writing
• Asynchronous reading and
writing
• Length
and actual position
• Positioning
• Flush and close
19
Page 19
Daniel HERLEMONT 73
Stream Classes
(Stream)
long
Length
long
Position
bool
CanRead
bool
CanWrite
bool
CanSeek
int
Read
(byte[] buf, int pos, int len)
int
ReadByte
()
Write
(byte[] buf, int pos, int len)
WriteByte
(byte x)
long
Seek
(long pos, SeekOrigin org)
SetLength
(long len)
Flush
()
Close
()
FileStream
string
Name
Lock
(int pos, int len)
Unlock
(int pos, int len)
MemoryStream
MemoryStream
(
byte[]
)
int
Capacity
byte[]
GetBuffer
()
WriteTo
(Streams)
NetworkStream
bool
DataAvailable
BufferedStream
CryptoStream
Decoratorsis buffered!
no Seek
Sequential
byte streams on
various media
namespace
System.IO
GZipStream
DeflateStream
Daniel HERLEMONT 74
Readers and Writers
￿
Readers and Writers overtake formatting tasks
￿
BinaryReader and BinaryWriter for binary data
￿
TextReader and TextWriter for character data
FileStream
MemoryStream
NetworkStream
Stream
BinaryReader
BinaryWriter

TextReader
StreamReader
StringReader
TextWriter
StreamWriter
StringWriter
Daniel HERLEMONT
75
Reader Classes
(TextReader)
int
Read
()
int
ReadBlock
(char[] buf, int pos, int len)
int
Peek
()
string
ReadLine
()
string
ReadToEnd
()
Close
()
StreamReader
Stream
BaseStream
StreamReader
(Streams)
StringReader
StringReader
(string s)
TextReader reads characters
BinaryReader reads primitive types in binary form
Unfortunately, it is not possible to set multiple readers to a stream at the same time.
There is no formatted input of numbers, words, etc.
BinaryReader
BinaryReader
(Streams)
BinaryReader
(Streams, Encoding e)
byte
ReadByte
()
bool
ReadBoolean
()
char
ReadChar
()
short
ReadInt16
()
int
ReadInt32
()
...
Close
()
Daniel HERLEMONT
76
Writer Classes
(TextWriter)
string
NewLine
Write
(bool b)
Write
(char c)
Write
(int i)
...
Write
(string format, params object[] arg)
WriteLine
()
WriteLine
(bool b)
WriteLine
(char c)
WriteLine
(int i)
...
WriteLine
(string format, params object[] arg)
Flush
()
Close
()
StreamWriter
Stream
BaseStream
StreamWriter
(Streams)
StringWriter
StringWriter
()
string
ToString
()
BinaryWriter
Stream
BaseStream
BinaryWriter
(Streams)
BinaryWriter
(Streams, Encoding e)
Write
(bool b)
Write
(char c)
Write
(int i)
...
long
Seek
(int pos, SeekOrigin org)
Flush
()
Close
()
Formatted text output
(only sequentially; no Seek)
Output of data of primitive types
in binary form
20
Page 20
Daniel HERLEMONT 77
Files and Directories
Namespaces System.IO.File and System.IO.Directory
for working with files and directories
Directory:
￿
static methods for manipulating directories
File:
￿
static methods for manipulating files
DirectoryInfo:
￿
represents a directory
FileInfo:
￿
represents a file
Daniel HERLEMONT 78
Class File
public sealed class
File {
public static
FileStreamOpen(
string
path, FileMode mode);
public static
FileStreamOpen(
string
path, FileMode m, FileAccess a);
public static
FileStreamOpen(
string
p, FileMode m, FileAccess a, FileShare s);
public static
FileStreamOpenRead(
string
path);
public static
FileStreamOpenWrite(
string
path);
public static
StreamReader OpenText(
string
path);
// returns Reader for reading text
public static
StreamWriter AppendText
(string
path);
// returns Writer for appending text
public static
FileStreamCreate(
string
path);
// create a new file
public static
FileStreamCreate(
string
path,
int
bufferSize);
public static
StreamWriter CreateText(
string
path);
public static void
Move(
string
src,
string
dest);
public static void
Copy(
string
src,
string
dest);
//copies file src to dest
public static void
Copy(
string
src,
string
dest,
bool
overwrite);
public static void
Delete(
string
path);
public static bool
Exists(
string
path);
public static
FileAttributes GetAttributes(
string
path);
public static
DateTime GetCreationTime(
string
path);
public static
DateTime GetLastAccessTime(
string
path);
public static
DateTime GetLastWriteTime(
string
path);
public static void
SetAttributes(
string
path, FileAttributes fileAttributes);
public static void
SetCreationTime(
string
path, DateTime creationTime);
public static void
SetLastAccessTime(
string
path, DateTime lastAccessTime);
public static void
SetLastWriteTime(
string
path, DateTime lastWriteTime);
}
Daniel HERLEMONT
79
Fonctionnalités avancées
.NET Framework, C# et .NET Remoting 79
C#
￿
Section critique, exclusion mutuelle
class Account {
int balance;
public Account(int initial) {
balance = initial;
}
int Withdraw(int amount) {
if (balance < 0) throw new Exception("Negative Balance");
lock (this) {
if (balance >= amount) {
balance = balance - amount;
return amount;
}
else {
return 0;
}
}
}
}
Daniel HERLEMONT
80
Parameter arrays
￿
Can write “printf” style methods
￿
Type-safe, unlike C++
static void
static void
printf(string
printf(string
fmt
fmt
,
,
params
params
object[]
object[]
args
args
) {
) {
foreach
foreach
(object x in
(object x in
args
args
) {
) {
...
...
}
}
}
}
printf("%s
printf("%s
%i", s, i);
%i", s, i);
object[]
object[]
args
args
= new object[2];
= new object[2];
args[0] = s;
args[0] = s;
args[1] = i;
args[1] = i;
printf("%s
printf("%s
%i",
%i",
args
args
);
);
21
Page 21
Daniel HERLEMONT 81
Fonctionnalités avancées
.NET Framework, C# et .NET Remoting 81
C#
￿
Contrôle de débordement lors d’opérations arithmétiques sur les entiers
class OverFlowTest {
static short x = 32767, y = 32767;
public static int myMethodCheck() {
int z = 0;
try {
z = checked((short)(x + y));
}
catch (System.OverflowException e) {
System.Console.WriteLine(e.ToString());
}
return z;
}
public static int myMethodUncheck() {
int z = unchecked((short)(x + y));
return z;
}
}
Daniel HERLEMONT 82
￿
boxing:type valeur ￿￿￿￿type référence
Fonctionnalités avancées
.NET Framework, C# et .NET Remoting 82
C#
￿
Boxing/ Unboxing
￿
Mécanisme de conversion entre un type valeur et un type référence
int i = 123;
object o = i;
int j = (int)o;
￿
unboxing:type référence ￿￿￿￿type valeur
Daniel HERLEMONT
83
Fonctionnalités avancées – Code Unsafe
.NET Framework, C# et .NET Remoting 83
C#
￿
Code unsafe
￿
Manipulation de bas niveau (pointeurs)
￿
Autorise les conversions de types
￿
Autorise les opérations arithmétiques sur les pointeurs
￿
Semblable à du code C inline – permet de proter du code écrit en C
￿
Allocation sur la pile (stackalloc)
class Test {
class Test {
unsafe void Method() {
unsafe void Method() {
char*
char*
buf
buf
=
=
stackalloc
stackalloc
char[256];
char[256];
for(char
for(char
* p =
* p =
buf
buf
; p <
; p <
buf
buf
+ 256; p++) *p = 0;
+ 256; p++) *p = 0;
...
...
}
}
}
}
Daniel HERLEMONT
84
Fonctionnalités avancées - Unsafe
.NET Framework, C# et .NET Remoting 84
C#
￿
Code unsafe
￿
Fixer l’adresse mémoire d’une variable à l’exécution (fixed)
class Test {
class Test {
static int x;
static int x;
int y;
int y;
unsafe static void
unsafe static void
F(int
F(int
* p) {
* p) {
*p = 1;
*p = 1;
}
}
static void Main() {
static void Main() {
Test t = new Test();
Test t = new Test();
int[] a = new int[10];
int[] a = new int[10];
unsafe {
unsafe {
fixed (int* p = &x)
fixed (int* p = &x)
F(p
F(p
);
);
fixed (int* p = &
fixed (int* p = &
t.y
t.y
)
)
F(p
F(p
);
);
fixed (int* p = &a[0])
fixed (int* p = &a[0])
F(p
F(p
);
);
fixed (int* p = a)
fixed (int* p = a)
F(p
F(p
);
);
}
}
}
}
}
}
22
Page 22
Daniel HERLEMONT 85
Comparaison C# et VB.NET
￿
C#
￿
Object oriented and strong typing
￿
Described as a “...simple, modern, object-oriented, and type-safe programming
language derived from C and C++”.
￿
Bears many syntactic similarities to C++ and Java.
￿
C# is a better programming language because it forces variables to be defined.
C# code runs faster
￿
for large applications where maintenance and performance are required
￿
VB.Net
￿
is the latest release of Microsoft’s Visual Basic language.
￿
VB is an event driven programming language.
￿
Derived heavily from BASIC.
￿
VB enables Rapid Application Development (RAD) of graphical user interface
(GUI) applications.
Daniel HERLEMONT 86
C# Example (Syntax)
/* C Style comment */
// C++ Style comment
///Enhanced comment for Documentation Feature
Void SampleProc()
{
int intCounter1=0;
MessageBox.show(“Counter1=” + intCounter1.ToString());
} //end of SampleProc
Daniel HERLEMONT
87
VB.Net Example (Syntax)
‘Style of comments for VB.Net
Sub SampleProc()
Dim intCounter1 as Integer, intCounter2 as Integer
MessageBox.show(“Counter1=” & intCounter1)
End Sub ‘end of SampleProc
Daniel HERLEMONT
88
C# Example (Object Oriented)
class App{
static void Main(string [ ] args)
{
int intCounter=0;
foreach (string arg in args)
{
System.Console.WriteLine(“Counter:” + intCounter.ToString() + “=“ + arg);
} //end of foreach
} //end of Main()
} //end of App{}
23
Page 23
Daniel HERLEMONT 89
VB.Net Example (Object Oriented)
Class App
Shared Sub Main(ByVal args as String( ) )
Dim arg as String
Dim intCounter as Integer
For Each arg in args
System.Console.Writeline(“Counter: ” & intCounter & “=“ & arg)
Next ‘For Each loop
End Sub ‘end of Main()
End Class ‘end of App{}
Daniel HERLEMONT 90
Language Converters
C# to VB.NET
￿
http://www.aspalliance.com/aldotnet/examples/translate.aspx
￿
http://www.kamalpatel.net/ConvertCSharp2VB.aspx
VB.Net to C#
￿
http://www.e-iceblue.com
￿
http://www.vbconversions.com
C# & VB.NET Conversion Pocket Reference by
Jose Mojica
C# in a Nutshell By
Peter Drayton
,
Ben Albahari
,
Ted Neward
http://en.wikipedia.org/wiki/Visual_Basic_programming_language
Daniel HERLEMONT
91
Quelques références
http://
http://
msdn.microsoft.com
msdn.microsoft.com
http://windows.oreilly.com/news/hejlsberg_0800.html
http://windows.oreilly.com/news/hejlsberg_0800.html
http://
http://
www.csharphelp.com
www.csharphelp.com
/
/
http://www.csharp
http://www.csharp
-
-
station.com
station.com
/
/
http://
http://
www.csharpindex.com
www.csharpindex.com
/
/
http://
http://
www.hitmill.com/programming/dotNET/csharp.html
www.hitmill.com/programming/dotNET/csharp.html
http://www.c
http://www.c
-
-
sharpcorner.com
sharpcorner.com
/
/
http://
http://
msdn.microsoft.com/library/default.asp?URL
msdn.microsoft.com/library/default.asp?URL
=/library/
=/library/
dotnet/csspec/vclrfcsharpspec_Start.htm
dotnet/csspec/vclrfcsharpspec_Start.htm
http://en.wikipedia.org/wiki/C_Sharp_(programming_language)
http://fr.wikipedia.org/wiki/C_sharp
Tutoriel en francais
http://tahe.ftp-developpez.com/fichiers-archive/csharp2008.pdf
http://tahe.developpez.com/dotnet/csharp/
Comparaisons entre langages
http://en.wikipedia.org/wiki/Comparison_of_Java_and_C_Sharp
http://www.25hoursaday.com/CsharpVsJava.html
http://en.wikipedia.org/wiki/Comparison_of_C_Sharp_and_Visual_Basic_.NET