How To Code in C#


Published on

How To Code in C# The Complete Course. From data types to object orientation. Includes code samples and exercises.

Getting Started with C#
C# Language Fundamentals
Object-Orientated Programming
Classes and Objects
Inside Methods
Inheritance and Polymorphism
Operator Overloading
Collection Interfaces and Types
Throwing and Catching Exceptions
Delegates and EventsGenerics
New Language Features

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

How To Code in C#

  1. 1. Programming in C# David Ringsell MCPD MCT MCAD David Ringsell MCSD 1
  2. 2. Free .Net & SQL Server Web Tutorials web and windows development programming in VB and C# database development object orientation
  3. 3. Course ContentUnit Topic1. Getting Started with C#2. C# Language Fundamentals3. Branching4. Operators5. Object-Orientated Programming6. Classes and Objects7. Inside Methods8. Debugging9. Inheritance and Polymorphism 3
  4. 4. Course Content 2Unit Topic10. Operator Overloading11. Structs12. Interfaces13. Arrays14. Collection Interfaces and Types15. Strings16. Throwing and Catching Exceptions17. Delegates and Events18. Generics19. New Language Features 4
  5. 5. Your Consultant David Ringsell MCPD MCPD MCT Trainer, developer, consultant Develops in C#.Net, VB.Net, ASP.Net and Sequel Server More courses and tutorials: 5
  6. 6. References Learning C# by J. Liberty from O‟Reilly C# 2010 Professional from Wrox 6
  7. 7. 1. Getting Started with C# Why C# and not VB The C# Programming Language C# Goals How C# Fits with .Net Overview of the .NET Framework 7
  8. 8. Why C# and not VB Syntax more like C++ and Java Syntax very concise Designed for object orientation  Started with a clean slate  Everything is an object Microsoft are evolving language 8
  9. 9. C# Supports …. Structured  Procedural, blocked Object-orientated  Classes, methods, properties Event driven  Event handlers, delegates … programming 9
  10. 10. C# Goals Safe  Find bugs early in development process Simple  Few keywords Internet Centric  Designed for developing web programs Hi Performance  Designed for industrial strength programming 10
  11. 11. How C# Fits with .Net Languages  VB.Net, C#, C++ … Visual Studio Integrated Development Environment (IDE) Framework Class Libraries (FCL)  ADO, ASP, XML, … Common Language Runtime (CLR) Windows Operating System 11
  12. 12. Overview of .NetVisualBasic C++ C# Perl J# … XML Web Services User Interface ASP.NET ADO.NET: Data and XML .NET Framework Class Library Common Language Runtime COM+ Message (Transactions, Partitions, IIS WMI Queuing Object Pooling) Win32 12
  13. 13. 2. C# Language Fundamentals Data Types Numeric Types Non-Numeric Types: char and bool Variables Definite Assignment Constants Strings Statements 13
  14. 14. Data Types Common C# intrinsic Type Size in Bytes data types byte 1 bool 2 int 4 long 8 float 4 double 8 decimal 12 14
  15. 15. Typing in C# C# is a strongly typed language Types come in two flavours  Value (intrinsic)  Reference (classes …) Each type has a name (int) and size (4b) The .Net equivalents for int is Int32 15
  16. 16. Numeric Data Types Unsigned (positive)  byte, ushort, uint, ulong Signed (positive or negative)  short, int, long, float, decimal, double Select the smallest type that will hold the required range of numbers 16
  17. 17. Non-Numeric Types: char and bool char  Holdsjust a single character  Can hold:  Simple character („A‟)  Unicode character (u0041)  Escape character („n‟) bool  Holds true or false in one byte 17
  18. 18. Declaring Local Variablesint myInt;System.Console.WriteLine("Uninitialized, myInt: {0}",myInt);myInt = 5;int mySecondInt = 10; // declare and initialiseint myInt4,myInt5; // declare multiple variables What is the value on an integer before it is initialised? 18
  19. 19. Declaring Constantsconst int FreezingPoint = 32; // degrees Farenheitconst int BoilingPoint = 212; Why would you create constants? 19
  20. 20. Declaring EnumerationsAn enumeration is a set of named constants // declare the enumeration The data type defaults enum Temperatures:int to int { WickedCold = 0, FreezingPoint = 32, LightJacketWeather = 60, SwimmingWeather = 72, Why would you create BoilingPoint = 212, enumerations? } 20
  21. 21. Using EnumerationsSystem.Console.WriteLine("Freezing point of water: {0}", (int) Temperatures.FreezingPoint ); System.Console.WriteLine("Boiling point of water: {0}", (int) Temperatures.BoilingPoint ); 21
  22. 22. Declaring Strings A string is an objectstring myString = “Hello World” ;// declare and initialise string Where would you use strings in your code? 22
  23. 23. Statements, Expressions & WhiteSpace A statement ends in a semicolon int myInt = 23; An expression can be part of an assignment myInt = myInt * 23; White spaces are ignored myInt = myInt * 100; 23
  24. 24. Unit 2 LabTo write statements that prompt and greet the user1. Open Visual Studio.Net and create a new C# Console Applicationproject2. In the Main method insert the following line: string myName;3. Write a statement that prompts users for their name.4. Write another statement that reads the user‟s response from thekeyboard and assigns it to the myName string.5. Add one more statement that prints “Hello myName” to the screen(where myName is the name the user typed in).6. Save your work. 24
  25. 25. Unit 2 Lab …When completed, the Main method should contain the following:static void Main( ){ string myName; Console.WriteLine("Please enter your name"); myName = Console.ReadLine( ); Console.WriteLine("Hello {0}", myName);} 25
  26. 26. 3. Branching A method is a mini program The statements in it executed from top to bottom Branching temporarily halts this execution to call another method or statement There are 2 types of branching  Conditional  Unconditional 26
  27. 27. Ways of Branching Call a method  Temporally transfer control to the called method Looping  Repeat statements (conditionally or unconditionally) If Statements  Execute statements only if condition true Switch Statements  Execute statements depending on value of variable 27
  28. 28. Calling MethodsMainStatement1 Method AStatement2 Call Statement1MethodA() Statement2Statement3 MethodB()Statement4 Call Statement3 Method BEnd method Statement4 Statement1 Return End method Statement2 Statement3 Statement4 Return End method 28
  29. 29. Branching to a Methodstatic void Main() { Console.WriteLine("In Main! Calling SomeMethod()..."); SomeMethod(); Console.WriteLine("Back in Main()."); } static void SomeMethod() { Console.WriteLine("Greetings from SomeMethod!"); } 29
  30. 30. If Statements Condition (always in brackets)int valueOne = 10;int valueTwo = 20;if ( valueOne > valueTwo ){ Console.WriteLine("ValueOne: {0} larger than ValueTwo: {1}",valueOne, valueTwo);} Statement 30
  31. 31. Multiple Statement Blockif ( valueOne >= valueThree ) // true?{ Console.WriteLine( "valueOne: {0} larger or equal to valueThree: {1}", valueOne, valueThree); Console.WriteLine("Good thing you tested again!");} Braces create block 31
  32. 32. If … else Statements Execute if condition trueif ( valueOne > valueTwo ) { Console.WriteLine( "ValueOne: {0} larger than ValueTwo: {1}", valueOne, valueTwo); } // end if else { Console.WriteLine( "Nope, ValueOne: {0} is NOT larger than valueTwo: {1}",valueOne, valueTwo); } // end else Execute if condition false 32
  33. 33. Nested if Statements Outer ifif (temp <= 32) statement { Console.WriteLine("Warning! Ice on road!"); if (temp == 32) Nested if statement Console.WriteLine( "Temp exactly freezing, beware of water."); } else { Console.WriteLine("Watch for black ice! Temp: {0}", temp); } Quiz: Are there a missing braces? 33
  34. 34. Switch Statements switch on the value of myChoice switch (myChoice) { case Democrat: Console.WriteLine("You voted Democratic."); break; case Republican: Console.WriteLine("You voted Republican."); break; case Progressive: Break out! Console.WriteLine("You voted Progressive."); break; }Execute case statementsdepending on value 34
  35. 35. The Default Case switch (myChoice) { case Democrat: Console.WriteLine("You voted Democratic.n"); break; case Republican: Console.WriteLine("You voted Republican.n"); break; case Progressive: Console.WriteLine("You voted Progressive.n"); break; default: Console.WriteLine("You did not make a valid choice."); break; }When will the defaultstatements be executed? 35
  36. 36. Falling Through and Jumping Cases case "NewLeft": Console.WriteLine( "The NewLeft members are voting Democratic."); goto case "Democrat"; Jump Case case "Democrat": Console.WriteLine("You voted Democratic.n"); break; case "CompassionateRepublican": case "Republican": Console.WriteLine("You voted Republican.n"); Console.WriteLine("Dont you feel compassionate?"); break;Fall through case 36
  37. 37. Looping Statements Execute statements repeatedly The number of time can depend on condition Types of loop  Use goto statement  Use while loop  Use for loop 37
  38. 38. Creating Loops with gotoint counterVariable = -10; The label repeat: Console.WriteLine("counterVariable: {0}",counterVariable); ++counterVariable; Increment the counter if (counterVariable < 30) goto repeat; Branch to label Why is this type of loop not a good idea? 38
  39. 39. The while Loop While the condition is true …while (counterVariable < 10) { Console.WriteLine("counterVariable: 0}",counterVariable); counterVariable++; } … execute the statements 39
  40. 40. The do … while Loopdo { Console.WriteLine("counterVariable:{0}",counterVariable); counterVariable--; } The condition is now after the statementswhile (counterVariable >0); What is the minimum number of times the statements will run? 40
  41. 41. The for Loop The counter variable changes on each iteration for (int counter=100; counter>80; counter--) { Console.WriteLine( "counter: {0} ", counter); } What numbers will be output? 41
  42. 42. Break Out! for (int counter=0; counter<10; counter++) { Console.WriteLine("counter: {0} ", counter); if (counter == 5) { Console.WriteLine("Breaking out of the loop"); break; } } If condition is What is the next met, break out statement executed after a break out? 42
  43. 43. Continue a Loop from the Top if (signal == "0") {continue;} Start loop from top at next iteration Can you think of an example where this be used? 43
  44. 44. Other Loopsfor ( ; counter<10; counter++) No initialisationfor (int counter = 0; counter<10; ) No incrementfor ( ;; ) No anything!while (true) Always true (loop forever?) 44
  45. 45. Unit 3 Lab1. To write statements to input two numbers and display the result2. To write if …else statements to input three numbers and display the largest3. To write switch statements to input a country and display its capital4. To write looping statements that to display the list 10, 20, 30, 40 … 100 45
  46. 46. 4. Operators A symbol that takes an action  Assignment (=)  Mathematical ( +, -, *, / )  Increment and Decrement ( +=, -= )  Relational ( >, >=, <, <=)  Logical ( &&, ||, ! ) 46
  47. 47. Assignment Operators (=) Declare and assign int smallInt = 5; smallInt = otherInt= 5; Multiple Assignments 47
  48. 48. Mathematical Operators + Add - Subtract * Multiply / Divide % Modulus What is the order of precedence of these operators? 48
  49. 49. The Modulus Operator (%)for (int counter=1; counter<=100; counter++) { Console.Write("{0} ", counter); If the remainder after if ( counter % 10 == 0 ) dividing by 10 is 0 { Console.WriteLine("t{0}", counter); } }What will beoutput? 49
  50. 50. Calculate and Reassign OperatorsMySalary += 5000 Add 5000 to MySalaryMySalary -= 5000 Subtract 5000 from MySalaryMySalary *= 5000 Multiply MySalary by 5000MySalary /= 5000 Divide MySalary by 5000 50
  51. 51. Increment and Decrement by 1++ intB; Increment-- intB; DecrementintA = ++ intB; Increment then assign - prefixintA = -- intB; Decrement then assign - prefixintA = intB ++; Assign then increment - postfixintA = intB --; Assign then decrement - postfix 51
  52. 52. Prefix and Postfix Operators Increment thenint original = 10; assignint result; result = ++original; Console.WriteLine("After prefix: {0}, {1}", original,result); result = original++; Console.WriteLine("After postfix: {0}, {1}",original,result); Assign then increment What numbers are output? 52
  53. 53. Relational Operators intA = 100; intB = 50;intA == 100 Equals trueintA != 100 Not equals falseintA > intB Greater than trueintA >= intB Greater than or equal to trueintA < intB Less than falseintA <= intB Less than or equal to false 53
  54. 54. Logical Operators x = 5; y = 7;Name Operator Statement ResultAnd && (x==3) && (y == 7) FalseOr || (x==3) || (y == 7) TrueNot ! !(x==3) True 54
  55. 55. The Conditional Operator (?) Conditionint maxValue = valueOne > valueTwo ? valueOne : valueTwo; Assign valueOne if true Assign valueTwo if false 55
  56. 56. Operator PrecedenceintA = 5+7*3; What‟s theintA = (5+7)*3; results? Category Operators 1- Unary +-!() 2- Multiplicative */% 3- Additive +- 4- Relational < > <= <= 5- Logical && || 56
  57. 57. Unit 4 Lab1. To write statements using the multiplication operator to displaythe twelve-times table2. To write statements to input two numbers and use logicaloperators to output if the result of multiplying them will be positiveor negative 57
  58. 58. 5. Object-Orientated Programming What is OOP? Creating Models Classes and Objects Defining a Class Class Relationships The Three Pillars of OOP Analysis and Design 58
  59. 59. What is OOP? Windows and web programs are vastly complex  Richgraphical interfaces  Complex business relationships  Users interact with programs in many ways Programmers refer to information about the problem they are solving as the problem domain OOP is a technique for managing this complexity by defining objects from the problem domain 59
  60. 60. Characteristics of Objects State  The current conditions of an object, e.g. a customer object‟s state may include address & phone number. Capabilities  Whatthe object can do that is relevant to the problem domain, e.g. buy an item, return an item … Responsibilities  The customer object is responsible for managing its own address. No other object needs to know this. 60
  61. 61. Creating Models Humans are model builders Models are simplifications e.g. a road atlas Good models hold information that is relevant to the problem domain, no more & no less Programming models contain metaphors to represent concepts, E.g. a window, a folder A good OO design is an accurate model of the problem 61
  62. 62. Classes and Objects A class defines a new type of thing, e.g. a car class A class defines the common characteristics, e.g. every car has wheels, brakes … An object is an individual instance of a class, e.g. a specific car object An object is just a thing 62
  63. 63. Defining a Class A class definition contains members These describe the characteristics and behaviour of objects of the classes type These members can be  Fields & Properties  These hold the internal state of the object  Methods  These do the work for the object 63
  64. 64. Defining a Class Classpublic class Cat definition{ private int weight; Fields private String name; public Cat(String name, int weight) { = name; this.weight = weight; }// Class code … A method} 64
  65. 65. Class Relationships Good OO design depends on establishing relationships among classes Classes interact and relate in various ways The simplest form of interaction is when a method in one class calls a method in another Some complicated classes are composed of other classes, e.g. an automobile is composed of wheels, an engine … Car The automobile class is said to aggregate the simpler classes Engine Wheels Gear Box Piston 65
  66. 66. The Three Pillars of OOP Good OO design is built on three sturdy pillars  Each class is fully encapsulated to define its state  Inheritance allows the definition of a hierarchical relationship among classes  Polymorphism allows a group of objects to be treated in the same way 66
  67. 67. Encapsulation Each class is discreet and self-contained The implementation of one class can be changed without affecting other classes There is a clear separation between a classes:  Public interface (its contract with clients)  Private implementation (how it does what it has agreed) 67
  68. 68. Inheritance Inheritance allows a new class to be Stringed Instrument derived from an existing class The new (derived) class inherits characteristics from the existing (base) class Violin The inheritance relationship is Violin is derived from a base referred to as an is-a relationship class e.g. a violin is a stringed instrument Inheritance allow the creation of a family of objects, e.g. a button is a control, but also a list box is a control 68
  69. 69. Polymorphism Poly (many) – Morph (forms) Consider the controls class, that has derived classes; buttons & list boxes These subclasses inherit a shared ability; the draw method The draw method can be called for each subclass Each subclass knows how to implement the method for itself (draw a button, draw a list box) 69
  70. 70. Analysis and Design Analysis is researching the problem Design is actually planning the solution Analysis can take week or months for complex problems Analysis includes  Determining the success factors  Specifying the requirements (functional spec.) Design Includes  Imagining the classes and their inter-relationship  Creating class diagrams using UML 70
  71. 71. 6. Classes and Objects First ask what does the class model Can I inherit from an existing base class What members does the class expose An object is an instance of a class Classes are reference types held on the stack in memory 71
  72. 72. A Simple Class public class MyClass { public void SomeMethod(int firstParam, float secondParam) { Console.WriteLine( "Here are the parameters received: {0}, {1}", firstParam, secondParam); } } public class Tester { static void Main() { int howManyPeople = 6; float pi = 3.14f; MyClass mc = new MyClass(); mc.SomeMethod(howManyPeople, pi); } } 72
  73. 73. Creating a Constructor A constructor  Creates an instance of a class  Puts this in a valid state  The compiler will implicitly provide (if not declared)  Can provide with arguments  Can provide several overloaded versions of constructor  Has same name as class & no return type 73
  74. 74. Creating a Constructorpublic class Time { // private member variables int hour; int minute; int second; // public method public void DisplayCurrentTime() { System.Console.WriteLine("{0}/{1}/{2}", hour, minute, second); } // constructor public Time(int theHour, int theMinute, int theSecond) { hour = theHour; minute = theMinute; second = theSecond; }} 74
  75. 75. Others Clever Things with Objects Initializer  Initialize the value of a class member variable int second = 30 The this keyword  Refers to the current instance of an object Public void SomeMethod(int hour) { this.hour=hour } 75
  76. 76. Access Modifiers Determines availability of the class to clients public: visible to any client class protected: visible only to derived classes internal: visible only to classes in the same assembly[access-modifiers] class <identifier> [:base] { class body } 76
  77. 77. Instance and Static Members Instance Members  Associated with instance of class  btnUpdate = new Button();  btnUpdate.Draw(); Static Members  Associated with class itself  Button.GetButtonCount(); 77
  78. 78. Instance and Static Memberspublic class Cat{ private static int instances = 0; private int weight; private String name; public Cat(String name, int weight) { instances++; = name; this.weight = weight; } public static void HowManyCats() { Console.WriteLine("{0} cats adopted", instances); } public void TellWeight() { Console.WriteLine("{0} is {1} pounds", name, weight); } 78 }
  79. 79. Destroying Objects Objects are destroyed by Garbage Collector To free unmanaged resources declare a destructor (will be called by Garbage Collector)  ~MyClass(){} Or, provide a Dispose() method & ask clients to call  protected override void Dispose( bool disposing ) 79
  80. 80. Encapsulating Data with Properties Declare a property that can be read from or public int GetHour written to get { return Hour; } set { Hour =value; } 80
  81. 81. Unit 6 Lab1. To write statements to define a class called Date that has a constructor and fields for year, month, day. Also define a method called DisplayTime() in the class.2. To add an overloaded constructor to the Date class3. To add properties (get & set) for the year, month, day to the Date class 81
  82. 82. 7. Inside Methods Several methods can have the same name  Overload method signature Class data can be encapsulated with properties  Provide clients controlled access to class state Method can return multiple values by passing parameters by reference 82
  83. 83. Overloading Method Signatures Same method namepublic Time(System.DateTime dt) { … } but a different number & type of parameterspublic Time(int Year, int Month, int Date, int Hour, int Minute, int Second) { … }public Time(int Year, int Month, int Date, int Hour, int Minute) { … } 83
  84. 84. Passing Parameters by Reference Declare a method that takes parameters passed by referencepublic void GetTime(ref int h, ref int m, ref int s) { h = Hour; m = Minute; Now call the method s = Second; with reference } parameterst.GetTime(ref theHour, ref theMinute, ref theSecond); 84
  85. 85. Creating a Two Tier Application Create the business tier Create a new class library project Create a class to represent a business entity, say Date Add properties that expose attributes, say year, month, day Add methods for business rules Create the presentation tier Create a new console application project Add a reference to the above class library project Create an object from class Use the object‟s properties to access data items Use the object‟s methods to perform business processes 85
  86. 86. Unit 7 LabTo add a GetDate method to the Date class, using refparameters for year, month, day. Test the method. 86
  87. 87. 8. Debugging A powerful tool to understand and fix code at runtime Setting a breakpoint Stepping through code Using the debug windows view variables The call stack 87
  88. 88. Setting a BreakpointClick here to set Code is paused at runtimebreakpoint 88
  89. 89. Stepping through Code Step into (F11)  Execute the current line of code Step over (F10)  Execute the current line of code, but skip procedures Step out (Shift F11)  Resume execution from calling procedure The values of variables can be seen by hovering mouse pointer over them 89
  90. 90. Using the Debug Windows Immediate Window  Evaluates expressions, executes statements, print variable values Locals Window  View ( and modify) variables within local scope Watch window  Add variables to watch their values Call Stack  Show the calling methods of the current method 90
  91. 91. 9. Inheritance Derived classes are defined from a base class The derived class specialises the base class The derived class inherits all members The derived class can also implement its own version of the base class 91
  92. 92. Inheritance 92
  93. 93. Inheritance Hierarchy Window… inherits from … Button ListBox CheckBox Command RadioButton 93
  94. 94. Implementing Inheritance Define Base Classpublic class BaseForm : System.Windows.Forms.Form Define Derived Classpublic class AddressForm : BaseForm Use Derived Class in Client ClassAddressForm af = new AddressForm();af.Show(); 94
  95. 95. Inside Inheritance Calling the Base Class Constructor public AddressForm():base() Replacing Base Methods protected new void OnCustomerLocate() Calling Base Methods base.OnCustomerLocate 95
  96. 96. Polymorphism Powerful aspect of inheritance Poly (many) – Morph (forms) Example: T-Mobile supplies many handsets  Each handset “instance” knows how to ring  When the ring command is sent, the handset obeys in its own way 96
  97. 97. Creating a Polymorphic Method In Basepublic class Window public virtual void DrawWindow() In Derived Classpublic class ListBox : Window public override void DrawWindow() 97
  98. 98. Calling the Polymorphic Method In Client Class Window[] winArray = new Window[2]; winArray[0] = new Window(); winArray[1] = new ListBox(); //Loop thru array calling polymorphic method for (int i = 0;i < 2; i++) { winArray[i].DrawWindow(); } 98
  99. 99. Other Kinds of Methods The derived class must implement a base method abstract public virtual void DrawWindow() The derived class cannot override a base method sealed public virtual void DrawWindow() 99
  100. 100. Unit 9 LabTo define a class called Control, with a constructor and aDrawControl() method. Create a class called TextBoxthat inherits from Control and replaces the DrawControlmethod. Test the TextBox class 100
  101. 101. 10. Operator Overloading What is Operator Overloading Using the Operator Keyword Creating Useful Operators The Equals Operator Conversion Operators 101
  102. 102. What is Operator Overloading C# allows new classes to have the functionality of built-in types This includes the ability to define operators for a new class For example: + and = operators may be defined for a Fraction class This is a better alternative to creating a Fraction.Add() method 102
  103. 103. Using the operator Keyword  C# operators are static methods  To create a new operator combine the operator keyword with the symbol  This operator (+) will take two parameters of type Fraction & return a Fractionpublic static Fraction operator+(Fraction lhs, Fraction rhs) 103
  104. 104. Defining an Operator Create thepublic Fraction(int numerator, int denominator) Fraction class { this.numerator=numerator; this.denominator=denominator; } Create the +public static Fraction operator+(Fraction lhs, Fraction rhs) operator { if (lhs.denominator == rhs.denominator) { return new Fraction(lhs.numerator+rhs.numerator, lhs.denominator); } int firstProduct = lhs.numerator * rhs.denominator; int secondProduct = rhs.numerator * lhs.denominator; return new Fraction( firstProduct + secondProduct,lhs.denominator * rhs.denominator ); } 104
  105. 105. Creating Useful Operators Operator overloading can make code more intuitive when new classes behave like built in types But, resist the temptation to overuse For example: the incremental operator (++) could cause a pay increase to an Employee class This may be confusing to clients of this class 105
  106. 106. The Equals Operator The root Object class offers an Equals() method If the equals operator (==) is overridden for a Fraction, it is recommended that the Equals() method is also overridden This means that Equals() can be called on two objects Fractions 106
  107. 107. Overloading the Equals Method Test if the public override bool Equals(object o) parameter is an { object if (! (o is Fraction) ) { return false; } return this == (Fraction) o; } Use the overloaded == to test for equality 107
  108. 108. Overloading the == and != Operatorspublic static bool operator==(Fraction lhs, Fraction rhs) { if (lhs.denominator == rhs.denominator && Test for lhs.numerator == rhs.numerator) equality of { Fractions return true; } return false; }public static bool operator!=(Fraction lhs, Fraction rhs) { return !(lhs==rhs); Test for inequality by } delegating to the ==Why is it a good idea operatorto create both the ==& != operators? 108
  109. 109. Using the == and != Operators Test for equality if (f4 == f3) { Console.WriteLine("f4: {0} == F3: {1}", f4.ToString(), f3.ToString()); } if (f4 != f2) Test for inequality { Console.WriteLine("f4: {0} != F2: {1}", f4.ToString(), f2.ToString()); }Where is the ToString()method implemented? 109
  110. 110. Conversion Operators An int data type can be implicitly converted to a long Also, a long data type can be explicitly converted to an int Similarly, operators can be defined for the Fraction class to convert from: a Fraction to an integer e.g. 9/4 becomes 2  an integer to a Fraction e.g. 15 becomes 15/1 110
  111. 111. Creating Conversion Operatorspublic Fraction(int wholeNumber) Constructor taking { a whole number numerator = wholeNumber; denominator = 1; }public static implicit operator Fraction(int theInt) Implicitly { converting int return new Fraction(theInt); to fraction }public static explicit operator int(Fraction theFraction) { return theFraction.numerator /theFraction.denominator; }ExplicitlyconvertingFraction to int 111
  112. 112. Using Conversion Operators Fraction f1 = new Fraction(3,4); Fraction f2 = new Fraction(2,4); Fraction f3 = f1 + f2; Fraction f4 = f3 + 5; Convert int to fraction implicitly int truncated = (int) f4; Convert fraction to int explicitly 112
  113. 113. Unit 10 LabTo define a class called Fraction, with a constructor and a ToString()method. Create a subtraction operator (-) using operatoroverloading. Test the operator. 113
  114. 114. 11. Structs Lightweight alternative to classes Like classes they can define  Constructors, properties, methods and fields But they do not allow  Inheritance or destructors They are value not reference types Use for small, simple objects 114
  115. 115. Defining a Struct public struct Location { The struct has private int xVal; private data private int yVal; public Location(int xCoordinate, int yCoordinate) { xVal = xCoordinate; It has a yVal = yCoordinate; constructor } 115
  116. 116. Defining a Struct 2 public int XVal { get { return xVal; } set { xVal = value;} The struct has two } properties … public int YVal { get { return yVal; } set { yVal = value; } } … and a method public override string ToString() { return (String.Format("{0}, {1}", xVal,yVal)); } } // end struct 116
  117. 117. Using a Struct Create an instance of the structLocation loc1 = new Location(200,300); Display the values in the structConsole.WriteLine("Loc1 location: {0}", loc1); Invoke the default constructorLocation loc2 = new Location(); Console.WriteLine("Loc2 location: {0}", loc2);myFunc(loc1); Pass the struct to a method What is output when the default constructor is used? 117
  118. 118. Unit 11 LabTo define a struct called Colour, with a constructor and a ToString()method. This will hold three numbers to represent the red, greenand blue component of the colour. Test the Struct. 118
  119. 119. 12. Interfaces Implementing an Interface Implementing More Than One Interface Casting to an Interface The is and as Operators Extending Interfaces Combining Interfaces 119
  120. 120. What is an Interface Allows the designer to specify the behaviours an object must implement The interface describes only which properties, methods and events will exist The class using the interface agrees to implement all of these 120
  121. 121. Implementing an Interface Define the interfaceinterface IStorable { void Read(); void Write(object obj); int Status { get; set; } } Define its properties and methods 121
  122. 122. Create a Class to Implement the Interfacepublic class Document : IStorable { public void Read() Implement the Read { method Console.WriteLine( "Implementing the Read Method for IStorable"); } public void Write(object o) Implement the Write { method Console.WriteLine( "Implementing the Write Method for IStorable"); } public int Status Implement the { Status property get{ return status; } set{ status = value; } } 122
  123. 123. Test the Implementing ClassDocument doc = new Document("Test Document"); doc.Status = -1; doc.Read(); Console.WriteLine("Document Status: {0}", doc.Status); Use the interface‟s methods and property 123
  124. 124. Implementing More Than OneInterface Classes can derive from only one base class But, classes can implement any number of interfaces This provides added flexibility for class designers 124
  125. 125. Implementing Two Interfacesinterface IStorable { void Read(); void Write(object obj); int Status { get; set; } Heres the } new interfaceinterface ICompressible { void Compress(); void Decompress(); Document } implements both interfacespublic class Document : IStorable, ICompressible 125
  126. 126. Casting to an Interface In some cases you don‟t know the type of the class You only know the interface it implements You can then cast the object to that interface type You can then use the object‟s members through the interface type Access through an interface allows you to treat the interface polymorphically 126
  127. 127. Casting to an Interface 2public class Document : IStorable The Document class Implements the IStorable interface Document doc = new Document("Test Document"); IStorable isDoc = (IStorable) doc; isDoc.Read(); Cast the doc What happens if the object to the class does not IStorable type implement the interface? 127
  128. 128. The is Operator Does the objectDocument doc = new Document("Test Document"); implement interface? if (doc is IStorable) { IStorable isDoc = (IStorable) doc; isDoc.Read(); } else Only cast if { does Console.WriteLine("Could not cast to IStorable"); } 128
  129. 129. The as Operator This combines the is evaluation and the cast operation If the cast is not valid the operator returns null The as operator is more efficient than the is operator 129
  130. 130. The as Operator 2Document doc = new Document("Test Document");IStorable isDoc = doc as IStorable; if (isDoc != null) { Cast using as, then isDoc.Read(); test for null } else { Console.WriteLine("Could not cast to IStorable"); } 130
  131. 131. Extending Interfaces Add new members Modify how existing members work For example  Extend ICompressible with the new interface ILoggedCompressible  Add one additional method to ILoggedCompressible 131
  132. 132. Extending Interfaces 2interface ICompressible Define ICompressible { interface void Compress(); void Decompress(); }interface ILoggedCompressible : ICompressible Extend ICompressible to { log the bytes saved void LogSavedBytes(); } Document implementspublic class Document : ILoggedCompressible ILoggedCompressible Now implementpublic void LogSavedBytes() { that extra method Console.WriteLine("Implementing LogSavedBytes"); } 132
  133. 133. Combining Interfaces New interfaces can be created by adding existing interfaces New members can be added to the new interface 133
  134. 134. Combining Interfaces 2 Add two existing interfacesinterface IStorableCompressible : IStorable, ILoggedCompressible { void LogOriginalSize(); } Add methodpublic class Document : IStorableCompressible Class that will implement the interface 134
  135. 135. Unit 12 LabTo define an interface called IClient. This includes propertiesfor name and address details and a method called Order.Create a class called Customer that implements the interfaceand adds an additional method. Test the Customer class. 135
  136. 136. 13. ArraysAn array is a collection of objects of the same type Declaring Arrays Accessing Array Element The foreach Statement Multidimensional Arrays System.Array Indexers 136
  137. 137. A One Dimensional Array0 1 2 3 4 5 6 7Like a set ofpigeon holes Each pigeon hole can hold the same kind of object Each pigeon hole is accessed by its number: 0, 1, 2 … 137
  138. 138. Declaring Arrays Declare arrays int[] intArray; Employee[] empArray; intArray = new int[5]; empArray = new Employee[3]; What are the default values of the array Initialise arrays with 5 elements? & 3 elements 138
  139. 139. Declaring Arrays 2 Declare and initialise arraysint[] intArray = new int[5];Employee[] empArray = new Employee[3];The default values for Alternatively, declare,integers are 0, and for objects initialise andnull populate arraysint[] intArray = { 2, 4, 6, 8, 10 };Employee[] empArray ={ new Employee(5), new Employee(7), new Employee(9) }; 139
  140. 140. Accessing Array Elements This returns the 4th element since indexing starts at 0 intArray[3]; Populate the Employee array using a loop for (int i = 0;i<empArray.Length;i++) { empArray[i] = new Employee(i+5); Console.WriteLine(empArray[i].empID); } 140
  141. 141. The foreach Statement Loop through all items in the arrayforeach( int theInt in intArray ){ Console.WriteLine(theInt.ToString());} 141
  142. 142. The params keyword The method takes a variable number of integers as a parameterpublic void DisplayVals(params int[] intVals) { foreach (int i in intVals) { Console.WriteLine("DisplayVals {0}",i); } }int [] explicitArray = new int[4] {5,6,7,8};DisplayVals(explicitArray); Call method passing an array 142
  143. 143. Multidimensional Arrays Col. 0 Col. 7Row 1Row 2 3,2Row 3Row 4Row 5 143
  144. 144. Declaring 2D Arrays Declare the array int[,] boxArray = new int[2,3];int[,] rectangularArray = { {0,1,2}, {3,4,5}, {6,7,8}, {9,10,11} }; Or declare and populate the array 144
  145. 145. Loop through 2D Array Outer loopfor (int i = 0;i < rows;i++){ for (int j = 0;j<columns;j++) Inner loop { Console.WriteLine("rectangularArray[{0},{1}] = {2}", i,j,rectangularArray[i,j]); }} Which is iterated through first, the rows or the columns? 145
  146. 146. Jagged Arrays (Array of Arrays)int[][] jaggedArray = new int[rows][]; Declare the rows of various lengths jaggedArray[0] = new int[3]; jaggedArray[1] = new int[7]; jaggedArray[2] = new int[9]; Fill some elements jaggedArray[0][3] = 15; jaggedArray[1][1] = 12; jaggedArray[2][1] = 9; 146
  147. 147. System.Array Class Arrays are implemented with the System.Array class, which provides these useful methods:  Clear()  Copy()  Reverse()  Sort()  Length()  Rank() 147
  148. 148. Indexing Classes Some classes can act like arrays For example, a class list ListBoxTest can act like an array of the strings it contains An indexer allows a class to be treated like an array: ListBoxTest[3]; 148
  149. 149. Indexing Classes public class ListBoxTest { Allow array-like access public string this[int index] { get { if (index < 0 || index >= strings.Length) { // handle bad index Get value from } internal array return strings[index]; } set { Set value in strings[index] = value; internal array } } 149
  150. 150. Testing an Indexed Class// create a new listbox and initialize ListBoxTest lbt = new ListBoxTest("Hello", "World"); // add a few strings lbt[1] = “Who” lbt[2] = “are"; lbt[3] = “the"; lbt[4] = “developers"; // access all the strings for (int i = 0; i<lbt.GetNumEntries(); i++) { Console.WriteLine("lbt[{0}]: {1}",i,lbt[i]); } 150
  151. 151. Unit 13 LabTo create a two dimensional array of integers holding the twelve-times table. Use looping statements to populate the array anddisplay its elements 151
  152. 152. 14. Collection Interfaces and Types The Collection Interfaces Array Lists Queues Stacks 152
  153. 153. What Are Collections? A collection holds a group of similar objects An array is the simplest type of collection The .Net Framework provides built-in collection types The .Net Framework holds collection classes in  System.Collections Each type provides standard methods for accessing & manipulating the collection‟s content 153
  154. 154. The Collection Interfaces Collections implement interfaces that provide their characteristics Custom classes can also implement these interfaces For example, create a custom class ListBoxTest that holds the strings it displays The class can implement the collection interfaces to provide standard methods for:  Indexing  Sorting  Enumeration 154
  155. 155. The Collection Interfaces 2Interface PurposeIEnumerable Enumerate a through a collection using the foreach statementIEnumerator Iterates over collection & supports the foreach statementICollection Implemented by all collectionsIComparer Compares two objects: used for sortingIList Used by collections that can be indexedIDictionary For key/value collections such as HashTable and SortedListIDictionaryEnumerator Iterates over dictionary & supports the foreach statement 155
  156. 156. Array Lists An array list is like an array But, its size is dynamically increased as required It provides many useful properties and methods 156
  157. 157. Array List MembersMethod or PurposePropertyCapacity() The number of elements the ArrayList can holdCount() The current number of ArrayList elementsItem() Get or set the ArrayList elements at the specified indexAdd() Adds an object at the end of the ArrayList.Insert() Inserts an element into the ArrayList at the specified index.RemoveAt() Removes the element at the specified index of the ArrayListReverse() Reverses the order of the elements in the ArrayList or a portion of itSort() Sort alphabetically the array listToArray() Copy the elements of the ArrayList to a new array 157
  158. 158. Array List Example ArrayList empArray = new ArrayList(); ArrayList intArray = new ArrayList(); Populate the for (int i = 0;i<5;i++) ArrayLists { empArray.Add(new Employee(i+100)); intArray.Add(i*5); } foreach (int i in intArray) { Console.Write("{0} ", i.ToString()); Print the } ArrayLists‟ foreach(Employee e in empArray) members { Console.Write("{0} ", e.ToString()); } 158
  159. 159. Queues Queues are a first-in, first-out collection (FIFO) Imagine a queue at a bus stop Queues are good for managing limited resources e.g. messages 159
  160. 160. Queues MembersMethod or PurposePropertyCount() Gets the number of elements in the QueueClear() Remove all objectsContains() Determines if an element is in the QueueCopyTo() Copies elements to a one-dimensional arrayDequeue() Remove and return an object at start of the QueueEnqueue() Add an object at end of the QueuePeek() Returns an object at start of the Queue without removing itToArray() Copy the elements of the Queue to a new array 160
  161. 161. A Queue Example Populate theQueue intQueue = new Queue(); Queuefor (int i = 0;i<5;i++) { intQueue.Enqueue(i*5); }Console.Write("intQueue values:t" ); RemoveDisplayValues( intQueue ); elementsConsole.WriteLine("n(Dequeue)t{0}", intQueue.Dequeue() );DisplayValues( intQueue );Console.WriteLine("n(Dequeue)t{0}", intQueue.Dequeue() );DisplayValues( intQueue ); View butConsole.WriteLine("n(Peek) t{0}", intQueue.Peek() ); do notDisplayValues( intQueue ); remove elements 161
  162. 162. Displaying Queue Values The parameter type is IEnumerable public static void DisplayValues( IEnumerable myCollection ) { IEnumerator myEnumerator = myCollection.GetEnumerator(); while ( myEnumerator.MoveNext() ) Console.Write( "{0} ",myEnumerator.Current ); Console.WriteLine(); }Iterate thought itemsof the collection How does the IEnumerable interface work? 162
  163. 163. Stacks Queues are a last-in, first-out collection (LIFO) Imagine a stack of dishes on a buffet table The principal methods for adding and removing items are Push() and Pop() 163
  164. 164. Stack MembersMethod or PurposePropertyCount() Gets the number of elements in the StackClear() Remove all objectsContains() Determines if an element is in the StackCopyTo() Copies elements to a one-dimensional arrayPop() Remove and return an object at top of the StackPush() Add an object at top of the StackPeek() Return an object at top of the Stack without removing itToArray() Copy the elements of the Stack to a new array 164
  165. 165. A Stack Example Declare & populate theStack intStack = new Stack(); stackfor (int i = 0;i<8;i++) { intStack.Push(i*5); Remove an } elementConsole.WriteLine( "n(Pop)t{0}", intStack.Pop() ); View an elementConsole.WriteLine( "n(Peek) t{0}",intStack.Peek() );DisplayValues( intStack );Display allelements 165
  166. 166. Displaying Stack Values The parameter is of type public static void DisplayValues( IEnumerable IEnumerable myCollection ) { foreach (object o in myCollection) { Console.WriteLine(o); } } Iterate thought items of the collection 166
  167. 167. Unit 14 Lab1. To create an ArrayList of integers. Use looping statements topopulate this with multiples of 10. Experiment with the ArrayListsmethods, including the Sort(), Reverse() and Clear() methods.2. To create a Queue of integers. Use looping statements topopulate this. Experiment with the Queues methods, including theDequeue(),Enqueue () and Peek() methods.3. To create a Stack of integers. Use looping statements to populatethis. Experiment with the Stacks methods, including the Pop(),Push() and Peek() methods. 167
  168. 168. 15. Strings Creating Strings Manipulation Stings  Concatenating Strings  Copying Strings  Splitting Strings The StringBuilder Class Regular Expressions 168
  169. 169. What Exactly are Strings? Strings hold a variable number of characters C# provides the built in string type This aliases the System.String .Net class Strings are objects with methods for:  Concatenation  Comparison  Extracting sub-stings 169
  170. 170. Creating Strings Declare astring s1 = "abcd"; string Declare a string with anstring s2 = "ABCDn"; escape character for a new linestring s3 = "ABCDt EFGH"; Use an escape character for a tabstring s4 = myInteger.ToString(); Use the ToString() method 170
  171. 171. Comparing Stringsstring s1 = "abcd"; Hold the results of comparisonsstring s2 = "ABCD";int result; Compare two strings, case sensitiveresult = string.Compare(s1, s2);Console.WriteLine("compare s1: {0}, s2: {1}, result: {2}n", s1, s2, result); Compare, case insensitiveresult = string.Compare(s1,s2, true);Console.WriteLine("Compare insensitive. result: {0}n", result); If result is negative, the first value is smaller If result is positive, the first value is bigger If result is zero, the values are equal 171
  172. 172. Concatenating Strings Concatenation methodstring s3 = string.Concat(s1,s2);string s4 = s1 + s2; Use the overloaded + operator 172
  173. 173. Copying Strings Copy method string s5 = string.Copy(s2); string s6 = s5; Use the overloaded = operator 173
  174. 174. Test for Equality Use the member if s6.Equals(s5)…; method if string.Equals(s6,s5)…; Use the static method if s6 == s5 …; Use the overloaded == operator 174
  175. 175. Other Useful MethodsMethod Return value or actions3.Length The number of characters in s3s3[4] The 5th character of s3s3.EndsWith("Training") True if s3 ends with “Training”s3.IndexOf("Training") The index of the substrings3.Insert(101,“Excellent “) Insert the substring at 101st character 175
  176. 176. Splitting Strings 1 string s1 = "One.Two;Three Four"; A string to split const char Space = ; const char Comma = ,; const char Stop = .; The string const char SemiColon = ;; delimiters char[] delimiters = new char[] { Space, Comma, Stop, Put the SemiColon delimiters }; string output = ""; in an array int ctr = 1; 176
  177. 177. Splitting Strings 2 Split the string String[] resultArray = s1.Split(delimiters); foreach (String subString in resultArray) { output += ctr++; output += ": "; output += subString; output += "n"; } Iterate over the Console.WriteLine(output); resulting array of strings 177
  178. 178. The StringBuilder Class The class System.Text.StringBuilder can be used for creating and modifying string StringBuilder is mutable, when an instance is modified, the actual string is modified, not a copy StringBuilder is more efficient than String because only a single string object is created 178
  179. 179. The StringBuilder Class 2 Use the StringBuilder class to build theStringBuilder output = new StringBuilder(); outputint ctr = 1; Split the stringforeach (string subString in s1.Split(delimiters)) { output.AppendFormat("{0}: {1}n",ctr++,subString); }Console.WriteLine(output); AppendFormat appends a formatted string 179
  180. 180. StringBuilder MethodsMethod ExplanationAppend() Append string at end of current stringAppendFormat() Append formatted string at end of current string AppendFormat appends a formatted stringInsert() Insert string at specified positionLength () Retrieve or assign the length of the stringRemove() Remove specified charactersReplace() Replace all specified characters with new characters 180
  181. 181. Regular Expressions A powerful language to describe and manipulate text Uses pattern matching to compare string with wildcards Applying a regular expression to a string can return A substring  A modification of the original 181
  182. 182. Regular Expressions 2 Define the Regular Expressionstring s1 = "One,Two,Three Liberty Associates, Inc.";Regex theRegex = new Regex(" |, |,");StringBuilder sBuilder = new StringBuilder(); Spit the stringint id = 1; using the Regular Expressionforeach (string subString in theRegex.Split(s1)) { sBuilder.AppendFormat({0}: {1}n", id++, subString); }Console.WriteLine("{0}", sBuilder); 182
  183. 183. Unit 15 LabTo input a string representing a URL. Experimenting with extractingsubstrings and splitting the URL using the dot (.) and forward slash(/) separators. 183
  184. 184. 16. Throwing and Catching Exceptions Exception Handling The throw Statement The try and catch Statements How the Call Stack Works The finally Statement Dedicated catch Statements 184
  185. 185. Exception Handling C# handles errors and abnormal conditions with exceptions Exceptions can be thrown by A throw statement  A .Net Framework class  The operating system (e.g. a security violation) Exceptions are caught by code in a catch block (i.e. an exception handler) 185
  186. 186. The Exception Class All exceptions are of type System.Exception or derived from this Exceptions types include  ArgumentNullException  InvalidCastException  OverflowException Exception objects provide information on what went wrong (message, help file, source …) 186
  187. 187. Try and Catch Statementspublic void Func1(){ Test forConsole.WriteLine("Enter Func1..."); try errors in try { block Console.WriteLine("Entering try block..."); Func2(); Run Console.WriteLine("Exiting try block..."); statement in } catch block if catch an error { occurs Console.WriteLine("Exception caught and handled!"); } Console.WriteLine("Exit Func1...");} 187
  188. 188. Searching for an Exception Handler Main Unwind the call Statement1 stack looking Method A Statement2 Call for a handler Statement1 MethodA() Statement2 Statement3 MethodB() Call Statement4 Statement3 End method Method B Statement4 Statement1 Search for handler End method Statement2 Exception thrown !! Statement3 Search forIf no exception handler, then handler Statement4the CLR handles the exception End method 188
  189. 189. The throw Statementpublic void Run() The exception { is unhandled Console.WriteLine("Enter Run..."); so the program Func1(); terminates Console.WriteLine("Exit Run..."); } public void Func1() { Console.WriteLine("Enter Func1..."); Func2(); Console.WriteLine("Exit Func1..."); } public void Func2() { Throw an Console.WriteLine("Enter Func2..."); exception throw new System.Exception(); Console.WriteLine("Exit Func2..."); } 189
  190. 190. How the Call Stack Workspublic void Run() { Func1(); } public void Func1() catch in { Func1 try { Func2(); } catch { Console.WriteLine("Exception caught and handled!"); } } public void Func2() throw in { Func2 Console.WriteLine("Enter Func2..."); throw new System.Exception(); Will this Console.WriteLine("Exit Func2..."); statement run? } 190
  191. 191. Creating Dedicated catch Statements So far we have used a generic catch statement The catch statement can trap specific exceptions Multiple catch statements can trap different exceptions 191
  192. 192. Creating Dedicated catch Statements 2try { double a = 5; double b = 0; DoDivide(a,b) The most derived exception type is first } catch (System.DivideByZeroException) { Console.WriteLine("DivideByZeroException caught!"); } catch (System.ArithmeticException) { Console.WriteLine("ArithmeticException caught!"); } catch { Console.WriteLine("Unknown exception caught"); } Why are the catch statements in thisThe generic exception type is last order ? 192
  193. 193. The finally Statementtry { double a = 5; double b = 0; DoDivide(a,b) } catch (System.DivideByZeroException) { Console.WriteLine("DivideByZeroException caught!"); } catch { Console.WriteLine("Unknown exception caught"); } finally This statement { must execute Console.WriteLine(“close files here"); }What is another way of makingthis statement always run ? 193
  194. 194. Exception Class Methods and PropertiesMember ExplanationSource The method that raised the exceptionMessage Information about the exceptionHelplink Link to a help fileStackTrace Method calls that lead to the exceptionInnerException The exception that caused the current exception 194
  195. 195. Using the Exception Class DivideByZeroException e = new DivideByZeroException(); e.HelpLink =""; throw e; Set exception propertycatch (System.DivideByZeroException e) { Console.WriteLine("nDivideByZeroException! Msg: {0}",e.Message); Console.WriteLine("nHelpLink: {0}", e.HelpLink); Console.WriteLine("nHeres a stack trace: {0}n",.StackTrace); } Display exception properties 195
  196. 196. Unit 16 LabTo divide two integers and add exception handling with dedicatedcatch statements to create division by zero and other exceptions.Include a finally statement. 196
  197. 197. 17. Delegates and Events So what are Robin Cook has died delegates?  Tony Blair is not available Define in advance what authority to delegate  Funeral Attendances and what “parameters” are passed  Condolences and flowers Delegate the task at “runtime”  John Prescott attends the funeral 197
  198. 198. Delegates in C# A delegate  encapsulates a method  has a specific return type & parameter list  is instantiated with by passing a method as parameter  can call the delegated method at runtime 198
  199. 199. Using Delegates Define the delegate Public delegate int WhichIsFirst(object obj1, object obj2); Instantiate the delegate with a method WhichIsFirst theStudentDelegate = new WhichIsFirst(WhichStudentComesFirst); Call the delegated method i= theStudentDelegate(objJohn, objFred); 199
  200. 200. Multicasting Delegates Create a single delegate  that calls multiple methods Combine delegates with the + or += operators myMulticastDelegate = Writer + Logger; 200
  201. 201. Multicasting Delegates // Define delegate public delegate void StringDelegate(string s); // Define two methods public static void WriteString(string s) { …} public static void LogString(string s) {…} // Define and instantiate two StringDelegate objects. StringDelegate Writer, Logger Writer = new StringDelegate(WriteString); Logger = new StringDelegate(LogString); //Multicast the delegate myMulticastDelegate = Writer + Logger; //Call the two delegated methods myMulticastDelegate(“log this string") 201
  202. 202. Events in C# An object publishes a set of events Other classes can subscribe to these events For example, GUI control classes publish:  Mouse events  Keyboard events The publishing class also defines delegates The subscribing class implements these delegates 202
  203. 203. Events and DelegatesEvent this.button1.ClickInstantiate this.button1.Click += new System.EventHandler(this.button1_Click);DelegateEvent Handler private void button1_Click(object sender, System.EventArgs e) 203
  204. 204. Coupling Delegates to Event Handlers Delegates Event Handlers linkLabel1.MouseEnter += new EventHandler(Bigger); linkLabel2.MouseEnter += new EventHandler(Bigger); linkLabel3.MouseEnter += new EventHandler(Bigger); 204
  205. 205. Unit 17 LabTo create a class Pair and include a delegate WhichisFirst, aconstructor, and methods called Sort() and ReverseSort(). Thesemethods take as a parameters an instance of the WhichisFirstdelegate. To test the class create a Dog class. This implementsmethods that can be encapsulated by the delegate. 205
  206. 206. 18. Generics New feature of C# Version 2.0 and the CLR Generics allow a type parameter for classes and methods Specification of the type is deferred to instantiation at runtime Generic classes may be constrained to hold only certain types of data Generics are most commonly used with collections 206
  207. 207. Using Generics// Declare the generic class public classclass MyList<T>{....//}// Declare a list of typeMyList<int> list1 = new MyList<int>();// Declare a list of type stringMyList<string> list2 = new MyList<string>();// Declare a list of type MyClassMyList<MyClass> list3 = new MyList<MyClass>(); 207
  208. 208. The Reason for Generics An ArrayList can hold objects of any type All objects are cast to the System.Object root class But, the overheads of casting will degrade performance Also, there is no way at compile time to prevent invalid assignments, like: arrayList1(9) =“A string”; int myInt = arrayList(9); 208
  209. 209. The Benefits of Generics Import the Generic .Net class Declare a listusing System.Collections.Generic; using the type parameterList<int> list1 = new List<int>(); Add elementlist1.Add(3); without casting or boxinglist1.Add("It is raining in the South West"); Generate compile- time error! 209
  210. 210. Parameter Constraints When defining generic classes restriction can be placed on the type parameters Theses restrictions are called constraints They are specified using the where keyword in the class definition 210
  211. 211. Parameter ConstraintsConstraint Explanationclass MyList<T> where The type argument must be a value typeT: structclass MyList<T> where The type argument must be a referenceT: class typeclass MyList<T> where The type argument must have a publicT: new() parameterless constructorclass MyList<T> where The type argument must be or derive fromT: <base class name> the specified base classclass MyList<T> where The type argument must be or implementT: <interface name> the specified interface 211