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

C sharp part2

on

  • 1,150 views

 

Statistics

Views

Total Views
1,150
Views on SlideShare
1,149
Embed Views
1

Actions

Likes
1
Downloads
59
Comments
0

1 Embed 1

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

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    C sharp part2 C sharp part2 Presentation Transcript

    • 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 Outputn&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