C sharp part2
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
1,221
On Slideshare
1,220
From Embeds
1
Number of Embeds
1

Actions

Shares
Downloads
60
Comments
0
Likes
1

Embeds 1

http://lessons.foodtech.edu.mn 1

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Introduction to Programming in .Net Environment Masoud Milani
  • 2. Programming in C# Part 2
  • 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("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
  • 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 Outputn&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();
  • 50.
      • [Serializable()]
    1-
      • ©Masoud Milani
  • 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