際際滷

際際滷Share a Scribd company logo
Introduction to Programming in  .Net Environment Masoud Milani
Programming in C# Part 2
Overview Classes Inheritance Abstract classes Sealed classes Files Delegates Interfaces 1- 息Masoud Milani
Classes Members Constants  Fields Methods parameters Properties Indexer Operators Constructors Destructors Overloading 1- 息Masoud Milani
Parameters Passing Pass by value Value types are passed by value by default 1- 息Masoud Milani int Smallest(int a, int b) { if (a > b)   return b; else return a; } Change in a value parameter is not reflected in the caller
Parameters Passing Pass by reference out  (output) 1- 息Masoud Milani void Smaller(int a, int b, out int result) { result=a>b?b: a; } Change in a out parameter is reflected in the caller The function can not use the value of an out parameter before an assignment is made to it. int a=20; int b=30; Smaller(a, b, out sm); sm=20
Parameters Passing Pass by reference ref  (input and output) 1- 息Masoud Milani void Swap(ref int a, ref int b) { int t=a; a=b; b=t; } Change in a ref parameter is reflected in the caller The function can use the value of a reference parameter before an assignment is made to it. int a=20; int b=30; Swap(ref a, ref b); a=30 b=20
Parameters Passing Reference types are passed by reference by default 1- 息Masoud Milani public class ParamClass { public int myValue; } ParamClass p=new ParamClass(); p.myValue=9; Console.WriteLine("Before Increment,  p.myValue={0}", p.myValue); Increment(p); Console.WriteLine("After Increment,  p.myValue={0}", p.myValue); static void Increment(ParamClass q) { q.myValue++; } Before Increment, p.myValue=9 After Increment, p.myValue=10
Variable Number of Parameters 1- 息Masoud Milani int a=Smallest(5, 4, -3, 45, 2); int b=Smallest(1, 2, 3); int Smallest(params int[] a) { int smallest=int.MaxValue; foreach (int x in a) if (x < smallest) smallest=x; return smallest; }
Method Overloading More than one method with the same name can be defined for the same class methods must have different signatures 1- 息Masoud Milani
Operator Overloading More than one operator with the same name can be defined for the same class Overloaded operators must be public Static Precedence and associativity of the operators can not be changed. 1- 息Masoud Milani
Operator Overloading 1- 息Masoud Milani public class MyType { public MyType(int v) { myValue=v; } public int myValue; public static MyType operator + (MyType x, MyType y) { return new MyType(x.myValue + y.myValue); }  } MyType p(5); MyType q(6); MyType s=p+q; s += p;
Operator Overloading 1- 息Masoud Milani public class MyType {  public static MyType operator + (MyType x, int y) { return new MyType(x.myValue + y); }  } MyType p(5); MyType s=p+7; s += 7
Operator Overloading 1- 息Masoud Milani public class MyType {  public static MyType operator ++ (MyType x) { x.myValue += 1; return new MyType(x.myValue + 1); }  } MyType p(5); MyType s=p++;
Operator Overloading 1- 息Masoud Milani public class MyType {  public static bool operator true(MyType x) { return x.myValue !=0; } public static bool operator false (MyType x) { return x.myValue == 0; }  } MyType z(5); if (z) Console.WriteLine(&quot;true&quot;); else Console.WriteLine(&quot;false&quot;);
Indexers Indexers are properties that allow objects to be accessed like arrays The accessor functions for indexers take additional parameter(s) for index Indexers can not be declared static 1- 息Masoud Milani Exams ex=new Exams(); ex [1] =100; Indexer
Indexer 1- 息Masoud Milani public class Exams { public int this[int examNo] { get {  } set {  } } Exams ex=new Exams(); ex[1]=100; ex[2]=50; int average=ex[1] + ex[2];
Example using System; /// <summary> ///油油油油 A simple indexer example. /// </summary> class IntIndexer { 油油油 private string[] myData; 油油油 public IntIndexer(int size) 油油油 { 油油油油油油油 myData = new string[size]; 油油油油油油油 for (int i=0; i < size; i++) 油油油油油油油 { 油油油油油油油油油油油 myData[i] = &quot;empty&quot;; 油油油油油油油 } 油油油 } 油油油 1- 息Masoud Milani
Example public string this[int pos] 油油油 { 油油油油油油油 get 油油油油油油 { 油油油油油油油油油油油 return myData[pos]; 油油油油油油油 } 油油油油油油油 set 油油油油油油 { 油油油油油油油油油油油 myData[pos] = value; 油油油油油油油 } 油油油 } 油油油 1- 息Masoud Milani Should use this keyword
Example static void Main(string[] args) 油油油 { 油油油油油油油 int size = 10; 油油油油油油油 IntIndexer myInd = new IntIndexer(size); 油油油油油油油 myInd[9] = &quot;Some Value&quot;; 油油油油油油油 myInd[3] = &quot;Another Value&quot;; 油油油油油油油 myInd[5] = &quot;Any Value&quot;; 油油油油油油油 Console.WriteLine(&quot;\nIndexer Output\n&quot;); 油油油油油油油 for (int i=0; i < size; i++) 油油油油油油油 { 油油油油油油油油油油油 Console.WriteLine(&quot;myInd[{0}]: {1}&quot;, i,  myInd[i]); 油油油油油油油 } 油油油 } } 1- 息Masoud Milani
Output Indexer Output  myInd[0]: empty  myInd[1]: empty  myInd[2]: empty  myInd[3]: Another Value  myInd[4]: empty  myInd[5]: Any Value  myInd[6]: empty  myInd[7]: empty  myInd[8]: empty  myInd[9]: Some Value 1- 息Masoud Milani
Exercise Write a class Exams that have 3 private integer fields exam1, exam2 and exam3 An indexer that sets or gets the value of each exam A public property Average that returns the average of the three exams 1- 息Masoud Milani
Exams class 1- 息Masoud Milani public class Exams { public Exams(int ex1, int ex2, int ex3) {  } private int exam1; private int exam2; private int exam3; public double Average {  } }
Inheritance Implements isA relation Student isA Person 1- 息Masoud Milani public class Person { public Person(string fn, string ln) { firstName=fn; lastName=ln; } private string firstName; private string lastName; } public class Student : Person { public Student(string fn, string ln, string mj):  base(fn, ln) { major=mj; } private string major; }
Inheritance A subclass can hide the inherited members of its superclass using the keyword  new 1- 息Masoud Milani public class Person {  public void Show() { Console.Write(&quot;Name: {0}, {1}&quot;, lastName, firstName)} } public class Student : Person {  public new void Show() { base.Show(); Console.Write(&quot;major: {0}&quot;, major); } }
Inheritance 1- 息Masoud Milani Person p = new Person(&quot;P1-F&quot;, &quot;P1-L&quot;); p.Show(); Console.WriteLine(); Student s=new Student(&quot;S1-F&quot;, &quot;S1-L&quot;, &quot;CS&quot;); s.Show(); Console.WriteLine(); p=s; p.Show(); Name: P1-L, P1-F Name: S1-L, S1-F Name: S1-L, S1-F Major: CS
Virtual Function A class can allow its subclasses to override its member functions by declaring them  virtual 1- 息Masoud Milani public class Person {  public virtual void Show() { Console.Write(&quot;Name: {0}, {1}&quot;, lastName, firstName)} } public class Student : Inheritance.Person {  public override void Show() { base.Show(); Console.Write(&quot;major: {0}&quot;, major); } } using namespace the override keyword is also required.
Virtual Function 1- 息Masoud Milani Person p = new Person(&quot;P1-F&quot;, &quot;P1-L&quot;); p.Show(); Console.WriteLine(); Student s=new Student(&quot;S1-F&quot;, &quot;S1-L&quot;, &quot;CS&quot;); s.Show(); Console.WriteLine(); p=s; p.Show(); Name: S1-L, S1-F Major: CS Name: S1-L, S1-F Major: CS Name: P1-L, P1-F
Sealed Modifier A sealed class is a class that can not be the base of any other class used to prevent inheritance from the class to facilitate future class modification A sealed method overrides an inherited virtual method with the same signature Used to prevent further overriding of the method 1- 息Masoud Milani
Example using System; sealed class MyClass  { public int x;  public int y; } class MainClass  { public static void Main()  { MyClass mC = new MyClass();  mC.x = 110; mC.y = 150; Console.WriteLine(&quot;x = {0}, y = {1}&quot;, mC.x, mC.y);  } } 1- 息Masoud Milani
Example class MyDerivedC: MyClass  { }  1- 息Masoud Milani Complation error!
Abstract Classes An abstract class is a class that can not be instantiated Abstract classes are used for reuse and structural organization of the program Abstract classes can have abstract or specified methods Non-abstract subclasses must override the abstract methods that they inherit 1- 息Masoud Milani
Abstract Classes Software requirement is given: There is no object that is only a person. Each person is either a student or a graduate student 1- 息Masoud Milani
Abstract Classes 1- 息Masoud Milani public abstract class Person { public Person(string fn, string ln) { firstName=fn; lastName=ln; } private string firstName; private string lastName; public virtual void Show() { Console.Write(&quot;Name: {0}, {1}&quot;,  lastName, firstName); } } Error: Abstract classes can not be instantiated Person p(FN-1, LN-1);
Exercise 1- 息Masoud Milani Courses exam1 exam2 exam3 Average takes Class Grad Student GradStudent(  ) bool pass // >80 void override Show() class Student string major double Average Student(  ) bool Pass  // >60 void override Show() Abstract class Person string fName string lName Person(string fn, string ln) void virtual Show() isA isA
Exercise Ask the number of students For each student ask First Name Last Name Major Scores for each of three exams Whether or not this is a graduate student Create an appropriate student object and store it in an array Call Show member of each array entry 1- 息Masoud Milani
Person class 1- 息Masoud Milani public abstract class Person { public Person(string fn, string ln) {  } private string firstName; private string lastName; public virtual void Show() {  } }
Student class 1- 息Masoud Milani public class Student : Inheritance.Person { public Student(string fn, string ln, string mj, int ex1, int ex2, int ex3):base(fn, ln) {  } private string major; public override void Show() {  } public virtual bool Pass { get {  } } protected Exams scores; public double Average { get {  } } }
GradStudent class 1- 息Masoud Milani public class GradStudent : Inheritance.Student { public GradStudent(string fn, string ln, string mj, int ex1, int ex2, int ex3): base(fn, ln, mj, ex1, ex2, ex3) {  } public override bool Pass { get {  } } }
Files A file is a sequential sequence of bytes Applicable classes Text Input StreamReader Text Output StreamWriter Input/Output FileStream NameSpace System.IO 1- 息Masoud Milani
StreamWriter 1- 息Masoud Milani void WriteText() { int[] data=new int[5]{1,2,3,4,5}; StreamWriter outFile=new StreamWriter(&quot;myOutFile.txt&quot;); for(int i=0; i<data.Length; i++) outFile.WriteLine(&quot;data[{0}]={1}&quot;, i, data[i]); outFile.Close(); } myOutFile: data[0]=1 data[1]=2 data[2]=3 data[3]=4 data[4]=5
StreamReader Similar to StreamWriter Check for end of stream using the method  Peek() 1- 息Masoud Milani StreamReader inpTextFile=new StreamReader(&quot;myOutFile.txt&quot;); while(inpTextFile.Peek() >=0) { string nextLine=inpTextFile.ReadLine(); Console.WriteLine(int.Parse(nextLine.Substring(nextLine.IndexOf(&quot;=&quot;)+1))); }  inpTextFile.Close();
Exercise Modify the previous program to save and retrieve information 1- 息Masoud Milani
FileStream To open a FileStream, we need to specify Physical path File Mode File Access 1- 息Masoud Milani
FileMode Enumeration Append   Opens the file if it exists and seeks to the end of the file, or creates a new file  Create A new file should be created. If the file already exists, it will be overwritten. Open An existing file should be opened 1- 息Masoud Milani
FileAccess Enumeration Read Read access  ReadWrite Read and write access  Write Write access 1- 息Masoud Milani
Formatter Direct reading to and Writing from FileStreams is very difficult Must read and write byte by byte Use a formatter to format objects that are to be written to the FileStream BinaryFormatter Formats objects in binary 1- 息Masoud Milani
Formatter Methods Writing Serialize Reading Deserialize Exceptions: SerializationException  1- 息Masoud Milani
Serialization 1- 息Masoud Milani string myString=&quot;string1&quot;; int myInt=16; int[] myData=new int[5]{1,2,3,4,5}; FileStream f=new FileStream(&quot;bFile&quot;, FileMode.Create, FileAccess.Write); BinaryFormatter formatter=new BinaryFormatter(); formatter.Serialize(f, myString); formatter.Serialize(f, myInt); formatter.Serialize(f, myData); f.Close();
[Serializable()] 1- 息Masoud Milani
Deserialization 1- 息Masoud Milani string myString=&quot;string1&quot;; int myInt=16; int[] myData=new int[5]{1,2,3,4,5}; f=new FileStream(&quot;bFile&quot;, FileMode.Open, FileAccess.Read); myString=(string)formatter.Deserialize(f); myInt=(int)formatter.Deserialize(f); newdata=(int[])formatter.Deserialize(f); Console.WriteLine(&quot;myString={0}&quot;, myString); Console.WriteLine(&quot;myInt={0}&quot;, myInt);
Exercise Modify the previous program to save and retrieve information using a Binary Formatter 1- 息Masoud Milani
Exception Handling Exceptions are raised when a program encounters an illegal computation Division by zero Array index out of range Read beyond end of file  . 1- 息Masoud Milani
Exception Handling A method that is unable to perform a computation  throws  an exception object Exceptions can be caught by appropriate routines called  exception handlers Exception handlers receive the exception object containing information regarding the error  Exception objects are instances of classes that are derived from  Exception class 1- 息Masoud Milani
Exception Handling try  statement allows for catching exceptions in a block of code try statement has one or more  catch  clauses to catch exceptions that are raised in the protected block  1- 息Masoud Milani int[] a= new int[20]; try { Console.WriteLine(a[20]); } catch (Exception e) { Console.WriteLine(e.Message); } Index was outside the bounds of the array
Exception Handling A try block can have multiple catch clauses The catch clauses are searched to find the first clause with a parameter that matches the thrown exception The program continues execution with the first statement  that follows the  try-catch-finally construct 1- 息Masoud Milani
Exception Handling try statement has an optional  finally  clause that executes When an exception is thrown and the corresponding catch clause is executed When the protected block executes without raising throwing exception 1- 息Masoud Milani
Exception Handling 1- 息Masoud Milani int[] a= new int[20]; try { Console.WriteLine(a[2]); } catch (Exception e) { Console.WriteLine(e.Message); } finally { Console.WriteLine(Finally we are done!&quot;); } Finally we are done!
Exception Handling Exception classes IndexOutOfRangeException Class油  when an attempt is made to access an element of an array with an index that is outside the bounds of the array. This class cannot be inherited  DivideByZeroException Class The exception that is thrown when there is an attempt to divide an integral or decimal value by zero. 1- 息Masoud Milani
Exception Handling Exception classes InvalidCastException Class The exception that is thrown for invalid casting or explicit conversion EndOfStreamException Class The exception that is thrown when reading is attempted past the end of a stream For a list of Exception classes search for SystemException Hierarchy in MSDN.Net 1- 息Masoud Milani
Programmer Defined Exceptions Programmer defined exception classes must inherit from  ApplicationException class Provide at least one constructor to set the message property 1- 息Masoud Milani public class MyException : System.ApplicationException { public MyException(string message):base(message) { } }
Programmer Defined Exceptions 1- 息Masoud Milani public static int g(int a, int b) { // adds positive numbers if (a <0) { MyException e=new MyException(&quot;1st parameter is negative&quot;); throw(e); } if (b <0) { MyException e=new MyException(&quot;2nd dparameter is negative&quot;); throw(e); } return a+b; } try { Console.WriteLine(&quot;g(4, -5)={0}&quot;, g(4, -5)); } catch (Exception e) Console.WriteLine(e.Message); }
Delegates A delegate is a class that has only one or more methods Allows methods to be treated like objects 1- 息Masoud Milani delegate int D1(int i, int j);
Delegates 1- 息Masoud Milani delegate int D1(int i, int j); public static int add(int a, int b) { Console.WriteLine(a+b); return a+b; } public static int mult(int a, int b) { Console.WriteLine(a*b); return a*b } static void Main(string[] args) { D1 d1=new D1(add); D1 d2=new D1(mult); d1=d1 + d2; d1(5, 5); } 10 25
Delegates 1- 息Masoud Milani delegate int D1(int i, int j); public static int add(int a, int b) { Console.WriteLine(a+b); return a+b; } public static int mult(int a, int b) { Console.WriteLine(a*b); return a*b } static void Main(string[] args) { D1 d1=new D1(add); D1 d2=new D1(mult); d1=d1 + d2; f(d1); } 10 25 public static void f(D1 d) { d(5,5); }
Exercise Write a sort method that accepts an array of integer and a boolean delegate, compare, and sorts the array according to the delegate 1- 息Masoud Milani public static void sort(int[] data, CompareDelegate Compare) { for (int i=0; i<data.Length; ++i) for(int j=i+1; j<data.Length; j++) if (Compare(data[i],data[j])) { int t=data[i]; data[i]=data[j]; data[j]=t; } }
Interfaces An interface specifies the members that must be provided by classes that implement them An Interface can define methods, properties, events, and indexers The interface itself does not provide implementations for the members that it defines 1- 息Masoud Milani
Interfaces To add an interface, add a class and change it in the editor 1- 息Masoud Milani interface IPublication { string Title { get; set; } string Publisher { get; set; } void Display(); }
Interfaces 1- 息Masoud Milani public class Book: IPublication { public Book(string title, string author,  string publisher) { Title=title; Author=author; Publisher=publisher; } private string author; private string title; private string publisher; public string Author {  } public string Title {  } public string Publisher {  } public void Display() {  } }
Interfaces 1- 息Masoud Milani static public void Display(IPublication[] p) { for (int i=0; i<p.Length; ++i) p[i].Display(); } static void Main(string[] args) { IPublication[] publications= new  IPublication[2]; publications[0] = new Book (&quot;t0&quot;, &quot;a0&quot;, &quot;p0&quot;); publications[1] = new Magazine (&quot;t1&quot;, &quot;a1&quot;); Display(publications); } public class Magazine : Interfaces.IPublication {  }
Interfaces An interface can have only public members A class that is implementing an interface must implement all its members A class can implement multiple interfaces 1- 息Masoud Milani

More Related Content

What's hot (20)

Basic c#
Basic c#Basic c#
Basic c#
kishore4268
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
mohamedsamyali
18CSS101J PROGRAMMING FOR PROBLEM SOLVING
18CSS101J PROGRAMMING FOR PROBLEM SOLVING18CSS101J PROGRAMMING FOR PROBLEM SOLVING
18CSS101J PROGRAMMING FOR PROBLEM SOLVING
GOWSIKRAJAP
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
Intro C# Book
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
Abou Bakr Ashraf
Core C#
Core C#Core C#
Core C#
Jussi Pohjolainen
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
Divyanshu Dubey
Unit 3
Unit 3 Unit 3
Unit 3
GOWSIKRAJAP
10. Recursion
10. Recursion10. Recursion
10. Recursion
Intro C# Book
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
Rasan Samarasinghe
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
Intro C# Book
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
Sreedhar Chowdam
Object Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIObject Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part III
Ajit Nayak
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NET
Rasan Samarasinghe
Visula C# Programming Lecture 8
Visula C# Programming Lecture 8Visula C# Programming Lecture 8
Visula C# Programming Lecture 8
Abou Bakr Ashraf
C sharp chap5
C sharp chap5C sharp chap5
C sharp chap5
Mukesh Tekwani
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, Recursion
Sreedhar Chowdam
C sharp chap4
C sharp chap4C sharp chap4
C sharp chap4
Mukesh Tekwani
09. Methods
09. Methods09. Methods
09. Methods
Intro C# Book
Programming C Language
Programming C LanguageProgramming C Language
Programming C Language
natarafonseca
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
mohamedsamyali
18CSS101J PROGRAMMING FOR PROBLEM SOLVING
18CSS101J PROGRAMMING FOR PROBLEM SOLVING18CSS101J PROGRAMMING FOR PROBLEM SOLVING
18CSS101J PROGRAMMING FOR PROBLEM SOLVING
GOWSIKRAJAP
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
Intro C# Book
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
Abou Bakr Ashraf
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
Rasan Samarasinghe
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
Intro C# Book
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
Sreedhar Chowdam
Object Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIObject Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part III
Ajit Nayak
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NET
Rasan Samarasinghe
Visula C# Programming Lecture 8
Visula C# Programming Lecture 8Visula C# Programming Lecture 8
Visula C# Programming Lecture 8
Abou Bakr Ashraf
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, Recursion
Sreedhar Chowdam
Programming C Language
Programming C LanguageProgramming C Language
Programming C Language
natarafonseca

Viewers also liked (7)

仍舒弍仂舒仂亳 5
仍舒弍仂舒仂亳 5仍舒弍仂舒仂亳 5
仍舒弍仂舒仂亳 5
anjelo0028
仍舒弍仂舒仂亳 6
仍舒弍仂舒仂亳 6仍舒弍仂舒仂亳 6
仍舒弍仂舒仂亳 6
anjelo0028
How to deliver Bad Financial News
How to deliver Bad Financial NewsHow to deliver Bad Financial News
How to deliver Bad Financial News
Mark Normand
仍舒弍仂舒仂亳 2, 3
仍舒弍仂舒仂亳  2, 3仍舒弍仂舒仂亳  2, 3
仍舒弍仂舒仂亳 2, 3
anjelo0028
仍舒弍仂舒仂亳 10
仍舒弍仂舒仂亳 10仍舒弍仂舒仂亳 10
仍舒弍仂舒仂亳 10
anjelo0028
仍舒弍仂舒仂亳 13,14
仍舒弍仂舒仂亳 13,14仍舒弍仂舒仂亳 13,14
仍舒弍仂舒仂亳 13,14
anjelo0028
Wonderful World - Road trip to Perth, Australia 2007
Wonderful World - Road trip to Perth, Australia 2007Wonderful World - Road trip to Perth, Australia 2007
Wonderful World - Road trip to Perth, Australia 2007
Mark Normand
仍舒弍仂舒仂亳 5
仍舒弍仂舒仂亳 5仍舒弍仂舒仂亳 5
仍舒弍仂舒仂亳 5
anjelo0028
仍舒弍仂舒仂亳 6
仍舒弍仂舒仂亳 6仍舒弍仂舒仂亳 6
仍舒弍仂舒仂亳 6
anjelo0028
How to deliver Bad Financial News
How to deliver Bad Financial NewsHow to deliver Bad Financial News
How to deliver Bad Financial News
Mark Normand
仍舒弍仂舒仂亳 2, 3
仍舒弍仂舒仂亳  2, 3仍舒弍仂舒仂亳  2, 3
仍舒弍仂舒仂亳 2, 3
anjelo0028
仍舒弍仂舒仂亳 10
仍舒弍仂舒仂亳 10仍舒弍仂舒仂亳 10
仍舒弍仂舒仂亳 10
anjelo0028
仍舒弍仂舒仂亳 13,14
仍舒弍仂舒仂亳 13,14仍舒弍仂舒仂亳 13,14
仍舒弍仂舒仂亳 13,14
anjelo0028
Wonderful World - Road trip to Perth, Australia 2007
Wonderful World - Road trip to Perth, Australia 2007Wonderful World - Road trip to Perth, Australia 2007
Wonderful World - Road trip to Perth, Australia 2007
Mark Normand

Similar to C sharp part2 (20)

Java interface
Java interfaceJava interface
Java interface
Md. Tanvir Hossain
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
Abed Bukhari
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
.NET F# Events
.NET F# Events.NET F# Events
.NET F# Events
DrRajeshreeKhande
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
Renas Rekany
02.adt
02.adt02.adt
02.adt
Aditya Asmara
175035 cse lab-05
175035 cse lab-05 175035 cse lab-05
175035 cse lab-05
Mahbubay Rabbani Mim
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
Ma箪ur Chourasiya
Methods in Java
Methods in JavaMethods in Java
Methods in Java
Kavitha713564
Java cn b畉n - Chapter4
Java cn b畉n - Chapter4Java cn b畉n - Chapter4
Java cn b畉n - Chapter4
Vince Vo
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
Eduardo Bergavera
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
Pranali Chaudhari
Lecture 5
Lecture 5Lecture 5
Lecture 5
Muhammad Fayyaz
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
Akaks
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
Gousalya Ramachandran
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
Jaanus P旦ial
USER DEFINE FUNCTION AND STRUCTURE AND UNION
USER DEFINE FUNCTION AND STRUCTURE AND UNIONUSER DEFINE FUNCTION AND STRUCTURE AND UNION
USER DEFINE FUNCTION AND STRUCTURE AND UNION
MSridhar18
Diifeerences In C#
Diifeerences In C#Diifeerences In C#
Diifeerences In C#
rohit_gupta_mrt
Bc0037
Bc0037Bc0037
Bc0037
hayerpa
Unit vi(dsc++)
Unit vi(dsc++)Unit vi(dsc++)
Unit vi(dsc++)
Durga Devi
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
Abed Bukhari
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
Renas Rekany
Java cn b畉n - Chapter4
Java cn b畉n - Chapter4Java cn b畉n - Chapter4
Java cn b畉n - Chapter4
Vince Vo
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
Eduardo Bergavera
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
Akaks
USER DEFINE FUNCTION AND STRUCTURE AND UNION
USER DEFINE FUNCTION AND STRUCTURE AND UNIONUSER DEFINE FUNCTION AND STRUCTURE AND UNION
USER DEFINE FUNCTION AND STRUCTURE AND UNION
MSridhar18
Bc0037
Bc0037Bc0037
Bc0037
hayerpa
Unit vi(dsc++)
Unit vi(dsc++)Unit vi(dsc++)
Unit vi(dsc++)
Durga Devi

More from anjelo0028 (9)

仍舒弍仂舒仂亳 11,12
仍舒弍仂舒仂亳 11,12仍舒弍仂舒仂亳 11,12
仍舒弍仂舒仂亳 11,12
anjelo0028
仍舒弍仂舒仂亳 9
仍舒弍仂舒仂亳 9仍舒弍仂舒仂亳 9
仍舒弍仂舒仂亳 9
anjelo0028
仍舒弍仂舒仂亳 8
仍舒弍仂舒仂亳 8仍舒弍仂舒仂亳 8
仍舒弍仂舒仂亳 8
anjelo0028
仍舒弍仂舒仂亳 7
仍舒弍仂舒仂亳 7仍舒弍仂舒仂亳 7
仍舒弍仂舒仂亳 7
anjelo0028
仍舒弍仂舒仂亳 4
仍舒弍仂舒仂亳 4仍舒弍仂舒仂亳 4
仍舒弍仂舒仂亳 4
anjelo0028
仍舒弍仂舒仂亳 3
仍舒弍仂舒仂亳 3仍舒弍仂舒仂亳 3
仍舒弍仂舒仂亳 3
anjelo0028
亞仍仆亳亶 仗仂亞舒仄 仍亠从 1
亞仍仆亳亶 仗仂亞舒仄 仍亠从 1亞仍仆亳亶 仗仂亞舒仄 仍亠从 1
亞仍仆亳亶 仗仂亞舒仄 仍亠从 1
anjelo0028
亞仍仆亳亶 仗仂亞舒仄 仍亠从 1
亞仍仆亳亶 仗仂亞舒仄 仍亠从 1亞仍仆亳亶 仗仂亞舒仄 仍亠从 1
亞仍仆亳亶 仗仂亞舒仄 仍亠从 1
anjelo0028
仍舒弍仂舒仂亳 11,12
仍舒弍仂舒仂亳 11,12仍舒弍仂舒仂亳 11,12
仍舒弍仂舒仂亳 11,12
anjelo0028
仍舒弍仂舒仂亳 9
仍舒弍仂舒仂亳 9仍舒弍仂舒仂亳 9
仍舒弍仂舒仂亳 9
anjelo0028
仍舒弍仂舒仂亳 8
仍舒弍仂舒仂亳 8仍舒弍仂舒仂亳 8
仍舒弍仂舒仂亳 8
anjelo0028
仍舒弍仂舒仂亳 7
仍舒弍仂舒仂亳 7仍舒弍仂舒仂亳 7
仍舒弍仂舒仂亳 7
anjelo0028
仍舒弍仂舒仂亳 4
仍舒弍仂舒仂亳 4仍舒弍仂舒仂亳 4
仍舒弍仂舒仂亳 4
anjelo0028
仍舒弍仂舒仂亳 3
仍舒弍仂舒仂亳 3仍舒弍仂舒仂亳 3
仍舒弍仂舒仂亳 3
anjelo0028
亞仍仆亳亶 仗仂亞舒仄 仍亠从 1
亞仍仆亳亶 仗仂亞舒仄 仍亠从 1亞仍仆亳亶 仗仂亞舒仄 仍亠从 1
亞仍仆亳亶 仗仂亞舒仄 仍亠从 1
anjelo0028
亞仍仆亳亶 仗仂亞舒仄 仍亠从 1
亞仍仆亳亶 仗仂亞舒仄 仍亠从 1亞仍仆亳亶 仗仂亞舒仄 仍亠从 1
亞仍仆亳亶 仗仂亞舒仄 仍亠从 1
anjelo0028

C sharp part2

  • 1. Introduction to Programming in .Net Environment Masoud Milani
  • 3. Overview Classes Inheritance Abstract classes Sealed classes Files Delegates Interfaces 1- 息Masoud Milani
  • 4. Classes Members Constants Fields Methods parameters Properties Indexer Operators Constructors Destructors Overloading 1- 息Masoud Milani
  • 5. Parameters Passing Pass by value Value types are passed by value by default 1- 息Masoud Milani int Smallest(int a, int b) { if (a > b) return b; else return a; } Change in a value parameter is not reflected in the caller
  • 6. Parameters Passing Pass by reference out (output) 1- 息Masoud Milani void Smaller(int a, int b, out int result) { result=a>b?b: a; } Change in a out parameter is reflected in the caller The function can not use the value of an out parameter before an assignment is made to it. int a=20; int b=30; Smaller(a, b, out sm); sm=20
  • 7. Parameters Passing Pass by reference ref (input and output) 1- 息Masoud Milani void Swap(ref int a, ref int b) { int t=a; a=b; b=t; } Change in a ref parameter is reflected in the caller The function can use the value of a reference parameter before an assignment is made to it. int a=20; int b=30; Swap(ref a, ref b); a=30 b=20
  • 8. Parameters Passing Reference types are passed by reference by default 1- 息Masoud Milani public class ParamClass { public int myValue; } ParamClass p=new ParamClass(); p.myValue=9; Console.WriteLine(&quot;Before Increment, p.myValue={0}&quot;, p.myValue); Increment(p); Console.WriteLine(&quot;After Increment, p.myValue={0}&quot;, p.myValue); static void Increment(ParamClass q) { q.myValue++; } Before Increment, p.myValue=9 After Increment, p.myValue=10
  • 9. Variable Number of Parameters 1- 息Masoud Milani int a=Smallest(5, 4, -3, 45, 2); int b=Smallest(1, 2, 3); int Smallest(params int[] a) { int smallest=int.MaxValue; foreach (int x in a) if (x < smallest) smallest=x; return smallest; }
  • 10. Method Overloading More than one method with the same name can be defined for the same class methods must have different signatures 1- 息Masoud Milani
  • 11. Operator Overloading More than one operator with the same name can be defined for the same class Overloaded operators must be public Static Precedence and associativity of the operators can not be changed. 1- 息Masoud Milani
  • 12. Operator Overloading 1- 息Masoud Milani public class MyType { public MyType(int v) { myValue=v; } public int myValue; public static MyType operator + (MyType x, MyType y) { return new MyType(x.myValue + y.myValue); } } MyType p(5); MyType q(6); MyType s=p+q; s += p;
  • 13. Operator Overloading 1- 息Masoud Milani public class MyType { public static MyType operator + (MyType x, int y) { return new MyType(x.myValue + y); } } MyType p(5); MyType s=p+7; s += 7
  • 14. Operator Overloading 1- 息Masoud Milani public class MyType { public static MyType operator ++ (MyType x) { x.myValue += 1; return new MyType(x.myValue + 1); } } MyType p(5); MyType s=p++;
  • 15. Operator Overloading 1- 息Masoud Milani public class MyType { public static bool operator true(MyType x) { return x.myValue !=0; } public static bool operator false (MyType x) { return x.myValue == 0; } } MyType z(5); if (z) Console.WriteLine(&quot;true&quot;); else Console.WriteLine(&quot;false&quot;);
  • 16. Indexers Indexers are properties that allow objects to be accessed like arrays The accessor functions for indexers take additional parameter(s) for index Indexers can not be declared static 1- 息Masoud Milani Exams ex=new Exams(); ex [1] =100; Indexer
  • 17. Indexer 1- 息Masoud Milani public class Exams { public int this[int examNo] { get { } set { } } Exams ex=new Exams(); ex[1]=100; ex[2]=50; int average=ex[1] + ex[2];
  • 18. Example using System; /// <summary> ///油油油油 A simple indexer example. /// </summary> class IntIndexer { 油油油 private string[] myData; 油油油 public IntIndexer(int size) 油油油 { 油油油油油油油 myData = new string[size]; 油油油油油油油 for (int i=0; i < size; i++) 油油油油油油油 { 油油油油油油油油油油油 myData[i] = &quot;empty&quot;; 油油油油油油油 } 油油油 } 油油油 1- 息Masoud Milani
  • 19. Example public string this[int pos] 油油油 { 油油油油油油油 get 油油油油油油 { 油油油油油油油油油油油 return myData[pos]; 油油油油油油油 } 油油油油油油油 set 油油油油油油 { 油油油油油油油油油油油 myData[pos] = value; 油油油油油油油 } 油油油 } 油油油 1- 息Masoud Milani Should use this keyword
  • 20. Example static void Main(string[] args) 油油油 { 油油油油油油油 int size = 10; 油油油油油油油 IntIndexer myInd = new IntIndexer(size); 油油油油油油油 myInd[9] = &quot;Some Value&quot;; 油油油油油油油 myInd[3] = &quot;Another Value&quot;; 油油油油油油油 myInd[5] = &quot;Any Value&quot;; 油油油油油油油 Console.WriteLine(&quot;\nIndexer Output\n&quot;); 油油油油油油油 for (int i=0; i < size; i++) 油油油油油油油 { 油油油油油油油油油油油 Console.WriteLine(&quot;myInd[{0}]: {1}&quot;, i, myInd[i]); 油油油油油油油 } 油油油 } } 1- 息Masoud Milani
  • 21. Output Indexer Output myInd[0]: empty myInd[1]: empty myInd[2]: empty myInd[3]: Another Value myInd[4]: empty myInd[5]: Any Value myInd[6]: empty myInd[7]: empty myInd[8]: empty myInd[9]: Some Value 1- 息Masoud Milani
  • 22. Exercise Write a class Exams that have 3 private integer fields exam1, exam2 and exam3 An indexer that sets or gets the value of each exam A public property Average that returns the average of the three exams 1- 息Masoud Milani
  • 23. Exams class 1- 息Masoud Milani public class Exams { public Exams(int ex1, int ex2, int ex3) { } private int exam1; private int exam2; private int exam3; public double Average { } }
  • 24. Inheritance Implements isA relation Student isA Person 1- 息Masoud Milani public class Person { public Person(string fn, string ln) { firstName=fn; lastName=ln; } private string firstName; private string lastName; } public class Student : Person { public Student(string fn, string ln, string mj): base(fn, ln) { major=mj; } private string major; }
  • 25. Inheritance A subclass can hide the inherited members of its superclass using the keyword new 1- 息Masoud Milani public class Person { public void Show() { Console.Write(&quot;Name: {0}, {1}&quot;, lastName, firstName)} } public class Student : Person { public new void Show() { base.Show(); Console.Write(&quot;major: {0}&quot;, major); } }
  • 26. Inheritance 1- 息Masoud Milani Person p = new Person(&quot;P1-F&quot;, &quot;P1-L&quot;); p.Show(); Console.WriteLine(); Student s=new Student(&quot;S1-F&quot;, &quot;S1-L&quot;, &quot;CS&quot;); s.Show(); Console.WriteLine(); p=s; p.Show(); Name: P1-L, P1-F Name: S1-L, S1-F Name: S1-L, S1-F Major: CS
  • 27. Virtual Function A class can allow its subclasses to override its member functions by declaring them virtual 1- 息Masoud Milani public class Person { public virtual void Show() { Console.Write(&quot;Name: {0}, {1}&quot;, lastName, firstName)} } public class Student : Inheritance.Person { public override void Show() { base.Show(); Console.Write(&quot;major: {0}&quot;, major); } } using namespace the override keyword is also required.
  • 28. Virtual Function 1- 息Masoud Milani Person p = new Person(&quot;P1-F&quot;, &quot;P1-L&quot;); p.Show(); Console.WriteLine(); Student s=new Student(&quot;S1-F&quot;, &quot;S1-L&quot;, &quot;CS&quot;); s.Show(); Console.WriteLine(); p=s; p.Show(); Name: S1-L, S1-F Major: CS Name: S1-L, S1-F Major: CS Name: P1-L, P1-F
  • 29. Sealed Modifier A sealed class is a class that can not be the base of any other class used to prevent inheritance from the class to facilitate future class modification A sealed method overrides an inherited virtual method with the same signature Used to prevent further overriding of the method 1- 息Masoud Milani
  • 30. Example using System; sealed class MyClass { public int x; public int y; } class MainClass { public static void Main() { MyClass mC = new MyClass(); mC.x = 110; mC.y = 150; Console.WriteLine(&quot;x = {0}, y = {1}&quot;, mC.x, mC.y); } } 1- 息Masoud Milani
  • 31. Example class MyDerivedC: MyClass { } 1- 息Masoud Milani Complation error!
  • 32. Abstract Classes An abstract class is a class that can not be instantiated Abstract classes are used for reuse and structural organization of the program Abstract classes can have abstract or specified methods Non-abstract subclasses must override the abstract methods that they inherit 1- 息Masoud Milani
  • 33. Abstract Classes Software requirement is given: There is no object that is only a person. Each person is either a student or a graduate student 1- 息Masoud Milani
  • 34. Abstract Classes 1- 息Masoud Milani public abstract class Person { public Person(string fn, string ln) { firstName=fn; lastName=ln; } private string firstName; private string lastName; public virtual void Show() { Console.Write(&quot;Name: {0}, {1}&quot;, lastName, firstName); } } Error: Abstract classes can not be instantiated Person p(FN-1, LN-1);
  • 35. Exercise 1- 息Masoud Milani Courses exam1 exam2 exam3 Average takes Class Grad Student GradStudent( ) bool pass // >80 void override Show() class Student string major double Average Student( ) bool Pass // >60 void override Show() Abstract class Person string fName string lName Person(string fn, string ln) void virtual Show() isA isA
  • 36. Exercise Ask the number of students For each student ask First Name Last Name Major Scores for each of three exams Whether or not this is a graduate student Create an appropriate student object and store it in an array Call Show member of each array entry 1- 息Masoud Milani
  • 37. Person class 1- 息Masoud Milani public abstract class Person { public Person(string fn, string ln) { } private string firstName; private string lastName; public virtual void Show() { } }
  • 38. Student class 1- 息Masoud Milani public class Student : Inheritance.Person { public Student(string fn, string ln, string mj, int ex1, int ex2, int ex3):base(fn, ln) { } private string major; public override void Show() { } public virtual bool Pass { get { } } protected Exams scores; public double Average { get { } } }
  • 39. GradStudent class 1- 息Masoud Milani public class GradStudent : Inheritance.Student { public GradStudent(string fn, string ln, string mj, int ex1, int ex2, int ex3): base(fn, ln, mj, ex1, ex2, ex3) { } public override bool Pass { get { } } }
  • 40. Files A file is a sequential sequence of bytes Applicable classes Text Input StreamReader Text Output StreamWriter Input/Output FileStream NameSpace System.IO 1- 息Masoud Milani
  • 41. StreamWriter 1- 息Masoud Milani void WriteText() { int[] data=new int[5]{1,2,3,4,5}; StreamWriter outFile=new StreamWriter(&quot;myOutFile.txt&quot;); for(int i=0; i<data.Length; i++) outFile.WriteLine(&quot;data[{0}]={1}&quot;, i, data[i]); outFile.Close(); } myOutFile: data[0]=1 data[1]=2 data[2]=3 data[3]=4 data[4]=5
  • 42. StreamReader Similar to StreamWriter Check for end of stream using the method Peek() 1- 息Masoud Milani StreamReader inpTextFile=new StreamReader(&quot;myOutFile.txt&quot;); while(inpTextFile.Peek() >=0) { string nextLine=inpTextFile.ReadLine(); Console.WriteLine(int.Parse(nextLine.Substring(nextLine.IndexOf(&quot;=&quot;)+1))); } inpTextFile.Close();
  • 43. Exercise Modify the previous program to save and retrieve information 1- 息Masoud Milani
  • 44. FileStream To open a FileStream, we need to specify Physical path File Mode File Access 1- 息Masoud Milani
  • 45. FileMode Enumeration Append Opens the file if it exists and seeks to the end of the file, or creates a new file Create A new file should be created. If the file already exists, it will be overwritten. Open An existing file should be opened 1- 息Masoud Milani
  • 46. FileAccess Enumeration Read Read access ReadWrite Read and write access Write Write access 1- 息Masoud Milani
  • 47. Formatter Direct reading to and Writing from FileStreams is very difficult Must read and write byte by byte Use a formatter to format objects that are to be written to the FileStream BinaryFormatter Formats objects in binary 1- 息Masoud Milani
  • 48. Formatter Methods Writing Serialize Reading Deserialize Exceptions: SerializationException 1- 息Masoud Milani
  • 49. Serialization 1- 息Masoud Milani string myString=&quot;string1&quot;; int myInt=16; int[] myData=new int[5]{1,2,3,4,5}; FileStream f=new FileStream(&quot;bFile&quot;, FileMode.Create, FileAccess.Write); BinaryFormatter formatter=new BinaryFormatter(); formatter.Serialize(f, myString); formatter.Serialize(f, myInt); formatter.Serialize(f, myData); f.Close();
  • 51. Deserialization 1- 息Masoud Milani string myString=&quot;string1&quot;; int myInt=16; int[] myData=new int[5]{1,2,3,4,5}; f=new FileStream(&quot;bFile&quot;, FileMode.Open, FileAccess.Read); myString=(string)formatter.Deserialize(f); myInt=(int)formatter.Deserialize(f); newdata=(int[])formatter.Deserialize(f); Console.WriteLine(&quot;myString={0}&quot;, myString); Console.WriteLine(&quot;myInt={0}&quot;, myInt);
  • 52. Exercise Modify the previous program to save and retrieve information using a Binary Formatter 1- 息Masoud Milani
  • 53. Exception Handling Exceptions are raised when a program encounters an illegal computation Division by zero Array index out of range Read beyond end of file . 1- 息Masoud Milani
  • 54. Exception Handling A method that is unable to perform a computation throws an exception object Exceptions can be caught by appropriate routines called exception handlers Exception handlers receive the exception object containing information regarding the error Exception objects are instances of classes that are derived from Exception class 1- 息Masoud Milani
  • 55. Exception Handling try statement allows for catching exceptions in a block of code try statement has one or more catch clauses to catch exceptions that are raised in the protected block 1- 息Masoud Milani int[] a= new int[20]; try { Console.WriteLine(a[20]); } catch (Exception e) { Console.WriteLine(e.Message); } Index was outside the bounds of the array
  • 56. Exception Handling A try block can have multiple catch clauses The catch clauses are searched to find the first clause with a parameter that matches the thrown exception The program continues execution with the first statement that follows the try-catch-finally construct 1- 息Masoud Milani
  • 57. Exception Handling try statement has an optional finally clause that executes When an exception is thrown and the corresponding catch clause is executed When the protected block executes without raising throwing exception 1- 息Masoud Milani
  • 58. Exception Handling 1- 息Masoud Milani int[] a= new int[20]; try { Console.WriteLine(a[2]); } catch (Exception e) { Console.WriteLine(e.Message); } finally { Console.WriteLine(Finally we are done!&quot;); } Finally we are done!
  • 59. Exception Handling Exception classes IndexOutOfRangeException Class油 when an attempt is made to access an element of an array with an index that is outside the bounds of the array. This class cannot be inherited DivideByZeroException Class The exception that is thrown when there is an attempt to divide an integral or decimal value by zero. 1- 息Masoud Milani
  • 60. Exception Handling Exception classes InvalidCastException Class The exception that is thrown for invalid casting or explicit conversion EndOfStreamException Class The exception that is thrown when reading is attempted past the end of a stream For a list of Exception classes search for SystemException Hierarchy in MSDN.Net 1- 息Masoud Milani
  • 61. Programmer Defined Exceptions Programmer defined exception classes must inherit from ApplicationException class Provide at least one constructor to set the message property 1- 息Masoud Milani public class MyException : System.ApplicationException { public MyException(string message):base(message) { } }
  • 62. Programmer Defined Exceptions 1- 息Masoud Milani public static int g(int a, int b) { // adds positive numbers if (a <0) { MyException e=new MyException(&quot;1st parameter is negative&quot;); throw(e); } if (b <0) { MyException e=new MyException(&quot;2nd dparameter is negative&quot;); throw(e); } return a+b; } try { Console.WriteLine(&quot;g(4, -5)={0}&quot;, g(4, -5)); } catch (Exception e) Console.WriteLine(e.Message); }
  • 63. Delegates A delegate is a class that has only one or more methods Allows methods to be treated like objects 1- 息Masoud Milani delegate int D1(int i, int j);
  • 64. Delegates 1- 息Masoud Milani delegate int D1(int i, int j); public static int add(int a, int b) { Console.WriteLine(a+b); return a+b; } public static int mult(int a, int b) { Console.WriteLine(a*b); return a*b } static void Main(string[] args) { D1 d1=new D1(add); D1 d2=new D1(mult); d1=d1 + d2; d1(5, 5); } 10 25
  • 65. Delegates 1- 息Masoud Milani delegate int D1(int i, int j); public static int add(int a, int b) { Console.WriteLine(a+b); return a+b; } public static int mult(int a, int b) { Console.WriteLine(a*b); return a*b } static void Main(string[] args) { D1 d1=new D1(add); D1 d2=new D1(mult); d1=d1 + d2; f(d1); } 10 25 public static void f(D1 d) { d(5,5); }
  • 66. Exercise Write a sort method that accepts an array of integer and a boolean delegate, compare, and sorts the array according to the delegate 1- 息Masoud Milani public static void sort(int[] data, CompareDelegate Compare) { for (int i=0; i<data.Length; ++i) for(int j=i+1; j<data.Length; j++) if (Compare(data[i],data[j])) { int t=data[i]; data[i]=data[j]; data[j]=t; } }
  • 67. Interfaces An interface specifies the members that must be provided by classes that implement them An Interface can define methods, properties, events, and indexers The interface itself does not provide implementations for the members that it defines 1- 息Masoud Milani
  • 68. Interfaces To add an interface, add a class and change it in the editor 1- 息Masoud Milani interface IPublication { string Title { get; set; } string Publisher { get; set; } void Display(); }
  • 69. Interfaces 1- 息Masoud Milani public class Book: IPublication { public Book(string title, string author, string publisher) { Title=title; Author=author; Publisher=publisher; } private string author; private string title; private string publisher; public string Author { } public string Title { } public string Publisher { } public void Display() { } }
  • 70. Interfaces 1- 息Masoud Milani static public void Display(IPublication[] p) { for (int i=0; i<p.Length; ++i) p[i].Display(); } static void Main(string[] args) { IPublication[] publications= new IPublication[2]; publications[0] = new Book (&quot;t0&quot;, &quot;a0&quot;, &quot;p0&quot;); publications[1] = new Magazine (&quot;t1&quot;, &quot;a1&quot;); Display(publications); } public class Magazine : Interfaces.IPublication { }
  • 71. Interfaces An interface can have only public members A class that is implementing an interface must implement all its members A class can implement multiple interfaces 1- 息Masoud Milani