Page 1 .NET et C #
Transcription
Page 1 .NET et C #
The .NET Framework Richness .NET et C # s API 1 COM Win32 Win16 1980 Daniel HERLEMONT s ent pon m o C Windows 3.0 Daniel HERLEMONT 1990 s vice S er MFC 2000 2 .NET & CLR Common Language Runtime Présentation .NET & .NET Framework Microsoft propose 4 langages C#, C++,VB.NET,ASP.NET dont C# est le premier recommandé par Microsoft Autres langages supportés Perl, Cobol, Eiffel, J#, Oberon,Component Pascal, Python, Smalltalk Daniel HERLEMONT 3 Daniel HERLEMONT 4 Page 1 1 Mécanisme de fonctionnement de MS.NET CLI Standards chien .vb chat .cs VS.NET C# ECMA-334 Les applications c#, VB, c++ peuvent communiquer via le CLR En réalité le même programme peut etre écrit dans un lagage et décompilé dans un autre On retrouve les memes classes/packages dans les differentes environnements, CS, VB, C++ souris c++ JScript VB VC/MC++ System.Web UI SessionState HtmlControls Caching Security WebControls Configuration Debugger System.Web.Services Protocols Discovery Description Designers System.Data (ADO.NET) ADO chien MSIL SDK Tools souris MSIL ILDbDump CLR : moteur exécution SN en langage commun ILDAsm déploiement MetaInfo PEVerify Windows Linux (?) JIT JIT Boot Loader Threads 5 Daniel HERLEMONT Printing Imaging Text System.Xml XSLT Adapters CorDBG ILAsm chat MSIL System.Drawing Drawing2D SQL Design ComponentModel Serialization XPath System Collections IO Security Configuration Net ServiceProcess Diagnostics Reflection Text Remoting Globalization Resources Threading Serialization ECMA-335 CLR : Common Language Runtime JIT : Just in Time (2eme compilateur) System.WinForms Design Runtime InteropServices Common Language Runtime GC App Domain Loader JIT MSIL Common Type System Class Loader Platform Abstraction Layer Sync Timers Networking Filesystem 6 Daniel HERLEMONT Qu’est-ce c’est C# ? Le framework .NET Les classes du framework Tous les langages de l’environnement .NET ont acceès au mêmes classes, notamment, les classes fondementales System.Web Services Description Discovery Protocols UI HtmlControls Caching Configuration Security SessionState Button MessageBox ListControl WebControls SQL SQLTypes Collections Configuration Diagnostics Globalization IO Net Reflection Resources System.Drawing Drawing2D Imaging System.Data OLEDB Design Langage proposé par Microsoft, standardisé par ECMA, ressemble la syntaxe de Java System.Windows.Forms Form Printing Text Combinaison entre la force de C++ et la simplicité de Visual Basic Cross Plate-forme Cross Langage System.Xml XSLT XPath 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 Serialization System Daniel HERLEMONT Security ServiceProcess Text Threading Runtime InteropServices Remoting Serialization 7 Daniel HERLEMONT 8 Page 2 2 C# : comment ça marche ? ‘.exe’ ‘.dll’ .cs Code source CLS ‘Règle de tranformation en .NET’ Just in Time Compiler JIT Microsoft Intermediate Language (MSIL) C# vs C++ Avantages C# Code natif (selon OS) Plus ouvert, plus de productivité productivité, programmes plus fiables et moins difficile a mettre au point Interopé Interopérabilité rabilité dans le futur avec Framework .Net (Windows, »Linux,Unix ») De plus en plus utilisé utilisé dans les applications financiè financières (front & middle) au dé détriment du C++ Inconvé Inconvénients C# Apprendre nouveau concept de base (.Net) Apprendre nouveau langage (temps d’ d’estimation CLR Common Runtime Language environ 4 semaines) 9 Daniel HERLEMONT 10 Daniel HERLEMONT Avantages C# Inconvénients de C# 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. Technologie Windows 100%, porter Framework sur Linux “à voir” (projet Mono) Utilise le keyword ‘new’ et ‘override Utiliser la librairie de framework .NET .NET et C# sont des "standards ouverts" ne signifie pas nécessairement des "environnements ouverts". 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++ La première fois est lente (à cause de compilateur 2-time) Relativement nouveau (bibliotheques spécialisées, …) Plus détails : http://msdn.microsoft.com/library/default.asp?url=/library/enus/cscon/html/vclrfcompa risonbetweenccsharp.asp Daniel HERLEMONT 11 Daniel HERLEMONT 12 Page 3 3 Opérateurs Instructions Blocs Libellés Selections { ... } Unaires : Arithmétiques : Décalage : Relationnels : Logiques : Conditionnels : Assignation : + ! ~ ++x --x * / % + << >> < > <= >= == != & ^ | && || ?: = *= /= %= += -= <<= >>= &= ^= |= .NET Framework, C# et .NET Remoting (T)x C# Daniel HERLEMONT ; x: instruction; if(x == 1) { if(y == 2) { F(); } else { G(); } } 13 13 .NET Framework, C# et .NET Remoting switch(i) { case 0: case 1: Choix(); break; default: ChoixAutre(); break; } C# Daniel HERLEMONT Instructions for(int i = 0; i < n; i++) { ... } foreach(object o in collection) { break; goto libelle; continue; return value; ... } Sauts Gestion des exceptions try { ... } catch(ArgumentException e) { ... } catch(Exception e) { ... } finally { ... } .NET Framework, C# et .NET Remoting Daniel HERLEMONT throw new Exception(); C# 15 14 Types Itérations while(x != 0) { ... } do { ... } while(x == 0); 14 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 15 .NET Framework, C# et .NET Remoting Daniel HERLEMONT C# 16 16 Page 4 4 Types prédéfinis Type Description Exemple object Type de base de tous les autres types object o = null; string Séquence de caractères Unicode string s = "Hello"; sbyte Entier signé de 8 bits sbyte val = 12; short Entier signé de 16 bits short val = 12; int Entier signé de 32 bits int val = 12; long Entier signé de 64 bits long val1 = 12; long val2 = 34L; byte Entier non signé de 8 bits byte val = 12; ushort Entier non signé de 16 bits ushort val = 12; uint Entier non signé de 32 bits uint val1 = 12; uint val2 = 34U; ulong Entier non signé de 64 bits ulong ulong ulong ulong float Flottant simple précision (32 bits, 1.7E +/- 308 15 chiffres significatifs) float val = 1.23F; double Flottant double précision (64 bits, 3.4E +/- 38, 7 chiffres significatifs) double val1 = 1.23; double val2 = 4.56D; bool Booléen bool val1 = true; bool val2 = false; char Caractère Unicode char val = 'h'; decimal Décimal (28 chiffres significatifs) decimal val = 1.23M; .NET Framework, C# et .NET Remoting val1 val2 val3 val4 C# Daniel HERLEMONT = = = = Enumerations enum Color : long { Red, Green, Blue } Color color; switch(color) { case Color.Red: ... break; case Color.Blue: ... break; 12; 34U; 56L; 78UL; case Color.Green: ... break; default: break; 17 } 17 .NET Framework, C# et .NET Remoting C# Structures struct Point { public int x,y; public Point(int x, int y) { this.x = x; this.y = y; } } .NET Framework, C# et .NET Remoting C# 19 18 Tableaux struct Point { public int x,y; } Daniel HERLEMONT 18 Daniel HERLEMONT 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} } }; 19 .NET Framework, C# et .NET Remoting Daniel HERLEMONT C# 20 20 Page 5 5 Orientation Objet Class basics class myClass { programmation procédurale : P.P. (Pascal, C, etc.) private string myVar; public myClass() { } programmation orientée objet : P.O.O. (C++, Java, C#) protected void myMethod(int parameter) { //do stuff here } Principaux concepts de la programmation objet Encapsulation, abstraction, interfaces, … Héritage (simple, multiple) Polymorphisme } 21 Daniel HERLEMONT 22 Daniel HERLEMONT Inheritance Classes C# only supports single inheritance Specify inheritance like so: Nom Attribut d’accessibilité public protected private internal protected internal Attribut abstract (abstrait) Attribut sealed (sellé) Classe de base (héritage simple de classe) Interfaces implémentées (héritage multiple d’interfaces) Membres .NET Framework, C# et .NET Remoting Daniel HERLEMONT class myClass : myBaseClass non limité limité à la classe et aux classes dérivées limité à la classe limité à l’assemblage limité à l’assemblage et aux classes dérivées C# 23 23 Daniel HERLEMONT 24 Page 6 6 Method example Membres class myClass { private string myVar; public myClass() { } public void myMethod(int parameter) { //do stuff here } public static void PrintStuff() { } Constantes Champs Méthodes Constructeurs Destructeurs Types Propriétés Indexeurs Opérateurs Événements } class myCallerClass { public myCallerClass() { myClass.PrintStuff(); myClass myInstance= new myClass(); myInstance.myMethod(5); } } .NET Framework, C# et .NET Remoting 25 Daniel HERLEMONT C# Daniel HERLEMONT Constantes 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; } } class B { public const int X = C.Z + 1; public const int Y = 10; } class C { public const int Z = B.Y + 1; } .NET Framework, C# et .NET Remoting 26 Champs class A { public const double X = 1.0; public const double Y = 2.0; public const double Z = 3.0; } Daniel HERLEMONT 26 C# 27 Attributs d’accessibilité public protected private internal non limité limité à la classe et aux classes dérivées limité à la classe limité à l’assemblage Attributs new static readonly volatile champ cachant (classe dérivé) champ de classe champ en lecture seule (initialisé par le constructeur) champ volatile 27 .NET Framework, C# et .NET Remoting Daniel HERLEMONT C# 28 28 Page 7 7 Méthodes 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 Méthodes abstraites 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); } } Type de retour Paramètres .NET Framework, C# et .NET Remoting Daniel HERLEMONT public class Box: Shape { public override void Paint(Graphics g, Rectangle r) { g.DrawRect(r); } } C# 29 29 .NET Framework, C# et .NET Remoting C# 30 Daniel HERLEMONT Properties Méthodes virtuelles Properties are NOT fields Fields are variables declared in the class Properties are “wrappers” for fields Get/Set: class A { public virtual void F() { Console.WriteLine("A.F"); } } class B: A { public override void F() { Console.WriteLine("B.F"); } } private string mystring; public string MyString { get { return mystring; } set {mystring = value; } } Daniel HERLEMONT 30 .NET Framework, C# et .NET Remoting 31 Daniel HERLEMONT class Test { static void Main() { B b = new B(); A a = b; a.F(); a.F(); } } > B.F C# 32 32 Page 8 8 Constructeurs (instance) Constructeur (classe) Initialiser l’instance d’une classe En cas d’absence de constructeur, un constructeur sans paramètre est implicitement créé Initialiser une classe Ne peut être appelé explicitement Appelé automatiquement Pas d’attribut d’accessibilité, pas de paramètre 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; } } .NET Framework, C# et .NET Remoting 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); } } C# 33 Daniel HERLEMONT 33 .NET Framework, C# et .NET Remoting C# Daniel HERLEMONT Destructeur Déclaration d’un type à l’intérieur d’une classe 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 {...} } } 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); } } .NET Framework, C# et .NET Remoting C# 34 Types Appelé automatiquement lors du processus de garbage collection Ne peut être appelé explicitement Pas d’attribut d’accessibilité, pas de paramètre Daniel HERLEMONT 34 35 35 .NET Framework, C# et .NET Remoting Daniel HERLEMONT C# 36 36 Page 9 9 Propriétés Propriétés 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; } } 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 .NET Framework, C# et .NET Remoting 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; } } } C# Daniel HERLEMONT 37 37 .NET Framework, C# et .NET Remoting C# Indexeurs 38 Daniel HERLEMONT 38 Opérateurs Indexer une classe à la manière d’un tableau 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 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; } } } .NET Framework, C# et .NET Remoting Daniel HERLEMONT C# public static implicit operator byte(Digit d) { return d.value; } public static explicit operator Digit(byte b) { return new Digit(b); } } 39 39 .NET Framework, C# et .NET Remoting Daniel HERLEMONT C# 40 40 Page 10 10 Opérateurs Opérateurs 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 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 bool operator==(Digit a, Digit b) { return a.value == b.value; } public static Digit operator-(Digit a, Digit b) { return new Digit(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; } } .NET Framework, C# et .NET Remoting C# Daniel HERLEMONT 41 41 .NET Framework, C# et .NET Remoting C# 42 Daniel HERLEMONT Délégués Événements Pointeurs de méthodes (vulgarisation) Encapsule à la fois un objet et une méthode Peut « pointer » vers plusieurs méthodes .NET Framework, C# et .NET Remoting Mécanisme de notification Basé sur les délégués Consommateur d’événements 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 42 C# Traitant d’événements Générateur d’événements Événement registration callback Consommateur d’événements Traitant d’événements 43 43 .NET Framework, C# et .NET Remoting Daniel HERLEMONT C# 44 44 Page 11 11 Événements Espaces de noms public delegate void EventHandler(object sender, EventArgs e); Conteneur de classes ou d’espaces de nom public class Button: Control { public event EventHandler Click; protected void OnClick(EventArgs e) { if (Click != null) Click(this, e); } } Organiser des classes hiérarchiquement Structurer les assemblages public class Form { Button Button1 = new Button(); public Form() { Button1.Click += new EventHandler(Button1_Click); } ~Form() { Button1.Click -= new EventHandler(Button1_Click); } class A {} namespace X { class B { class C {} } namespace Y { class D {} } } // A // X // X.B // X.B.C // X.Y // 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() void Button1_Click(object sender, EventArgs e) { Console.WriteLine("Button1 was clicked!"); } } .NET Framework, C# et .NET Remoting C# Daniel HERLEMONT 45 45 .NET Framework, C# et .NET Remoting Daniel HERLEMONT Nom Attribut d’accessibilité public protected private internal Interfaces de base (héritage multiple d’interfaces) Membres 46 parameter arrays ref and out parameters overflow checking foreach statement lock statement switch on string Méthodes Propriétés Indexeurs Événements .NET Framework, C# et .NET Remoting Daniel HERLEMONT non limité limité à la classe et aux classes dérivées limité à la classe limité à l’assemblage 46 Productivity features Interfaces C# C# 47 47 Daniel HERLEMONT 48 Page 12 12 ref and out parameters foreach statement Use “ref” for in/out parameter passing Use “out” to return multiple values Must repeat ref/out at call site Iteration of arrays Equivalent to & public static void Main(string[] args) args) { foreach (string s in args) args) Console.WriteLine(s); Console.WriteLine(s); } Iteration of IEnumerable collections static void Swap(ref Swap(ref int a, ref int b) {...} static void Divide(int dividend, int divisor, out int result, out int remainder) {...} ArrayList accounts = Bank.GetAccounts(...); Bank.GetAccounts(...); foreach (Account a in accounts) { if (a.Balance < 0) Console.WriteLine(a.CustName); Console.WriteLine(a.CustName); } static void Main() { int x = 1, y = 2; Swap(ref Swap(ref x, ref y); } Daniel HERLEMONT 49 50 Daniel HERLEMONT Overflow checking Switch on string Integer arithmetic operations Color ColorFromFruit(string s) { switch(s.ToLower()) switch(s.ToLower()) { case "apple": return Color.Red; case "banana": return Color.Yellow; case "carrot": return Color.Orange; default: throw new InvalidArgumentException(); InvalidArgumentException(); } } C, C++, Java silently overflow checked vs. unchecked contexts Default is unchecked, except for constants Change with “/checked” compiler switch int i = checked(x checked(x * y); checked { int i = x * y; } Daniel HERLEMONT 51 Daniel HERLEMONT 52 Page 13 13 Polymorphism in C# Error handling System.Exception Gets code information like: public class Fruit { public virtual string Shape() {return "Not sure";} public string Colour() {return "You tell me";} } Stack trace Line and file info Detailed error message Use in try…catch block public class Orange : Fruit { public new string Colour() {return "Orange";} public override string Shape() {return "Round";} } Fruit string string Orange string string someFruit = new Orange(); a = someFruit.Shape(); // b = someFruit.Colour(); // anOrange = (Orange)someFruit; c = anOrange.Shape(); // d = anOrange.Colour(); // … ArrayList myList; try { myList.Clear(); } catch (System.NullReferenceException e) { Console.WriteLine(“variable not initialized”); } "Round" "You tell me" To throw an error say: throw <exception object> Or: throw new <exception class> "Round" "Orange" Exceptions are very costly, don’ don’t throw them unless there is an error 53 Daniel HERLEMONT Daniel HERLEMONT Generics Generics public class List< List<ItemType> ItemType> { private ItemType[] object[] elements; elements; ItemType[] private int count; Why generics? Compile-time type checking Performance (no boxing, no downcasts) Reduced code bloat (typed collections) public void Add(ItemType Add(object element) element) { { Add(ItemType if (count == elements.Length) Resize(count * 2); elements[count++] = element; } C# generics vs. C++ templates C# generics are checked at declaration C# generics are instantiated at run-time C# generics vs. proposed Java generics public ItemType object this[int this[int index] index] { { get { return elements[index]; } set { elements[index] = value; } } List<int> List<int> intList intList = new=List(); new List<int> (); List<int>(); } public int Count { getintList.Add(1); { return count; } intList.Add(2); } intList.Add("Three"); intList.Add("Three"); int i = intList[0]; (int)intList[0]; Daniel HERLEMONT 54 // // // C# generics work over entire type system C# generics preserve types at run-time Argument No boxingis boxed Argument No boxingis boxed CompileShould be time an error Compile- // No Cast cast required required 55 Daniel HERLEMONT 56 Page 14 14 Generics In VB Generics In C++ 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) Dim intList elements(index) As New List(Of = Value Integer) End Set intList.Add(1) // No boxing intList.Add(2) // No boxing End Property intList.Add("Three") // Compile-time error Dim i As Integer = intList(0) // No cast required Daniel HERLEMONT 57 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 { intList = gcnew List<int>(); intList<int>^ get() { return count; } intList->Add(1); // No boxing } intList->Add(2); // No boxing }; intList->Add("Three"); // Compile-time error Daniel HERLEMONT int i = intList[0]; Throwing an Exception // No cast required 58 Exception Hierarchy (excerpt) By an invalid operation (implicit exception) Exception SystemException ArithmeticException DivideByZeroException OverflowException ... NullReferenceException IndexOutOfRangeException InvalidCastException ... ApplicationException ... user-defined exceptions ... IOException FileNotFoundException DirectoryNotFoundException ... WebException ... 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 59 Daniel HERLEMONT 60 Page 15 15 Traditional Collections System.Collection namespace introduced in 1.0 version of .NET Framework Useful container types FileStream s = null; try { s = new FileStream(curName, FileMode.Open); ... } catch (FileNotFoundException e) { Console.WriteLine("file {0} not found", e.FileName); } catch (IOException) { Console.WriteLine("some IO exception occurred"); } catch { Console.WriteLine("some unknown error occurred"); } finally { if (s != null) s.Close(); } Lists Dictionaries Hashtables CollectionBase 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. 61 Daniel HERLEMONT Daniel HERLEMONT Sample Class Definition Sample ArrayList Use ArrayList bookList = new ArrayList(); class Book { private int bookNumber = 0; public int BookNumber { get { return this.bookNumber ; } set { this. bookNumber = value; } } 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); } public Book( int _bookNumber ) { this.bookNumber = _bookNumber; } } Daniel HERLEMONT 62 63 Daniel HERLEMONT 64 Page 16 16 Drawbacks VB.NET Generics Sample 1 Dim testCol As New List(Of int32)() No type checking enforcement at compile time For i as int32 = 0 To 19 testCol.Add(i) Next Doesn’t prevent adding unwanted types Can lead to difficult to troubleshoot issues Runtime errors! All items are stored as objects For each someInt As int32 in testCol Console.WriteLine(“{0}”, someInt) Next Must be cast going in and coming out Performance overhead of boxing and unboxing specific types Daniel HERLEMONT 65 Daniel HERLEMONT C# Generics Sample 1 VB.NET Generics Sample 2 Dim bookList As New List(Of Book)() ArrayList<int> testCol = new ArrayList<int>(); for (int i = 0; i < 20; i++) { testCol.Add(i); } For i as int32 = 0 To 19 bookList.Add(New Book(i)) Next foreach (int someInt in testCol) { Console.WriteLine(“{0}”, someInt); } Daniel HERLEMONT 66 For each book As Book in bookList Console.WriteLine(“{0}”, book.BookNumber) Next 67 Daniel HERLEMONT 68 Page 17 17 C# Generics Sample 2 C++ Templates? ArrayList<Book> bookList = new ArrayList<Book>(); for (int i = 0; i < 20; i++) { bookList.Add( new Book(i) ); } Generics are NOT equal to Templates Compile-Time vs. Run-Time foreach (Book book in bookList) { Console.WriteLine(“{0}”, book.BookNumber); } Code Bloat? Pros and Cons for each Templates = Compile-Time Generics = Run-Time 69 Daniel HERLEMONT 70 Daniel HERLEMONT Streaming Framework System.IO contains 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 Class Stream public abstract class Stream : MarshalByRefObject, IDisposable { public abstract bool CanRead { get; } public abstract bool CanSeek { get; } public abstract bool CanWrite { get; } Stream FileStream NetworkStream MemoryStream BufferedStream CryptoStream DeflateStream GZipStream • Elementary properties of stream public public public public abstract int Read(out byte[] buff, int offset, int count); abstract void Write(byte[] buff, int offset, int count); virtual int ReadByte(); virtual void WriteByte(byte value); • Synchronous reading and writing public public public public virtual IAsyncResult BeginRead(…); virtual IAsyncResult BeginWrite(…); virtual int EndRead(…); virtual int EndWrite(…); • Asynchronous reading and writing public abstract long Length { get; } public abstract long Position { get; set; } public abstract long Seek(long offset, SeekOrigin origin); • Length and actual position • Positioning public abstract void Flush(); public virtual void Close(); ... • Flush and close } Daniel HERLEMONT 71 Daniel HERLEMONT 72 Page 18 18 Stream Classes Readers and Writers (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() Sequential byte streams on various media TextReader StreamReader NetworkStream BufferedStream CryptoStream string Name Lock(int pos, int len) MemoryStream( byte[] ) bool DataAvailable DeflateStream GZipStream StringReader TextWriter BinaryReader MemoryStream is buffered! Readers and Writers overtake formatting tasks namespace System.IO FileStream Unlock(int pos, int len) BinaryReader and BinaryWriter for binary data TextReader and TextWriter for character data Stream BinaryWriter StreamWriter StringWriter … no Seek FileStream int Capacity MemoryStream NetworkStream Decorators byte[] GetBuffer() WriteTo(Stream s) 73 Daniel HERLEMONT 74 Daniel HERLEMONT Reader Classes Writer Classes (TextReader) BinaryReader (TextWriter) BinaryWriter int Read() int ReadBlock(char[] buf, int pos, int len) int Peek() string ReadLine() string ReadToEnd() Close() BinaryReader(Stream s) BinaryReader(Stream s, Encoding e) byte ReadByte() bool ReadBoolean() char ReadChar() short ReadInt16() int ReadInt32() ... Close() 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() Stream BaseStream BinaryWriter(Stream s) BinaryWriter(Stream s, Encoding e) Write(bool b) Write(char c) Write(int i) ... long Seek(int pos, SeekOrigin org) Flush() Close() StreamReader StringReader Stream BaseStream StreamReader(Stream s) StringReader(string s) TextReader BinaryReader reads characters 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. Daniel HERLEMONT StreamWriter StringWriter Stream BaseStream StreamWriter(Stream s) StringWriter() string ToString() Output of data of primitive types in binary form Formatted text output (only sequentially; no Seek) 75 Daniel HERLEMONT 76 Page 19 19 Files and Directories Class File Namespaces System.IO.File and System.IO.Directory for working with files and directories public sealed class File { public static FileStream Open(string path, FileMode mode); public static FileStream Open(string path, FileMode m, FileAccess a); public static FileStream Open(string p, FileMode m, FileAccess a, FileShare s); public static FileStream OpenRead(string path); public static FileStream OpenWrite(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 FileStream Create(string path); // create a new file public static FileStream Create(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 78 Directory: static methods for manipulating directories File: static methods for manipulating files DirectoryInfo: represents a directory FileInfo: represents a file 77 Daniel HERLEMONT Parameter arrays Fonctionnalités avancées Can write “printf” style methods Type-safe, unlike 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; } } } } .NET Framework, C# et .NET Remoting Daniel HERLEMONT C# static void printf(string fmt, fmt, params object[] args) args) { foreach (object x in args) args) { ... } } printf("%s %i", s, i); object[] args = new object[2]; args[0] = s; args[1] = i; printf("%s %i", args); args); 79 79 Daniel HERLEMONT 80 Page 20 20 Fonctionnalités avancées Fonctionnalités avancées Contrôle de débordement lors d’opérations arithmétiques sur les entiers Boxing / Unboxing Mécanisme de conversion entre un type valeur et un type référence 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; } } .NET Framework, C# et .NET Remoting C# Daniel HERLEMONT boxing : type valeur type référence unboxing : type référence type valeur int i = 123; object o = i; int j = (int)o; 81 81 .NET Framework, C# et .NET Remoting Fonctionnalités avancées – Code Unsafe 82 82 Fonctionnalités avancées - Unsafe Code unsafe C# Daniel HERLEMONT 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) Code unsafe Fixer l’adresse mémoire d’une variable à l’exécution (fixed) class Test { static int x; int y; unsafe static void F(int* F(int* p) { *p = 1; } class Test { unsafe void Method() { char* buf = stackalloc char[256]; for(char* for(char* p = buf; buf; p < buf + 256; p++) *p = 0; ... } } static void Main() { Test t = new Test(); int[] a = new int[10]; unsafe { fixed (int* p = &x) F(p); F(p); fixed (int* p = &t.y ) F(p); &t.y) F(p); fixed (int* p = &a[0]) F(p); F(p); fixed (int* p = a) F(p); F(p); } } } .NET Framework, C# et .NET Remoting Daniel HERLEMONT C# 83 83 .NET Framework, C# et .NET Remoting Daniel HERLEMONT C# 84 84 Page 21 21 Comparaison C# et VB.NET C# Example (Syntax) C# /* C Style comment */ // C++ Style comment 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 ///Enhanced comment for Documentation Feature Void SampleProc() { int intCounter1=0; MessageBox.show(“Counter1=” + intCounter1.ToString()); } //end of SampleProc 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 85 Daniel HERLEMONT VB.Net Example (Syntax) 86 C# Example (Object Oriented) class App { static void Main(string [ ] args) { int intCounter=0; ‘Style of comments for VB.Net Sub SampleProc() Dim intCounter1 as Integer, intCounter2 as Integer MessageBox.show(“Counter1=” & intCounter1) End Sub ‘end of SampleProc foreach (string arg in args) { System.Console.WriteLine(“Counter:” + intCounter.ToString() + “=“ + arg); } //end of foreach } //end of Main() } //end of App{} Daniel HERLEMONT 87 Daniel HERLEMONT 88 Page 22 22 VB.Net Example (Object Oriented) Language Converters Class App Shared Sub Main(ByVal args as String( ) ) Dim arg as String Dim intCounter as Integer C# to VB.NET For Each arg in args System.Console.Writeline(“Counter: ” & intCounter & “=“ & arg) http://www.aspalliance.com/aldotnet/examples/translate.aspx http://www.kamalpatel.net/ConvertCSharp2VB.aspx Next ‘For Each loop VB.Net to C# End Sub ‘end of Main() End Class ‘end of App{} 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 89 Daniel HERLEMONT Daniel HERLEMONT 90 Quelques références http://msdn.microsoft.com http://msdn.microsoft.com http://windows.oreilly.com/news/hejlsberg_0800.html http://www.csharphelp.com http://www.csharphelp.com// http://www.csharphttp://www.csharp-station.com/ station.com/ http://www.csharpindex.com http://www.csharpindex.com// http://www.hitmill.com/programming/dotNET/csharp.html http://www.hitmill.com/programming/dotNET/csharp.html http://www.chttp://www.c-sharpcorner.com/ sharpcorner.com/ http://msdn.microsoft.com/library/default.asp?URL =/library/dotnet/csspec/vclrfcsharpspec_Start.htm dotnet/csspec/vclrfcsharpspec_Start.htm http://msdn.microsoft.com/library/default.asp?URL=/library/ 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 Daniel HERLEMONT 91 Page 23 23