C sharp part2

Post on 10-May-2015

956 views 5 download

Tags:

Transcript of C sharp part2

Introduction to Programming in

.Net Environment

Masoud Milani

Programming in C#

Part 2

Introduction to Programming in .Net Environment

1-3 ©Masoud Milani

Overview

Classes

Inheritance

Abstract classes

Sealed classes

Files

Delegates

Interfaces

Introduction to Programming in .Net Environment

1-4 ©Masoud Milani

Classes Members

Constants Fields Methods

parameters

Properties Indexer Operators Constructors Destructors

Overloading

Introduction to Programming in .Net Environment

1-5 ©Masoud Milani

Parameters Passing Pass by value

Value types are passed by value by default

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

Introduction to Programming in .Net Environment

1-6 ©Masoud Milani

Parameters Passing Pass by reference

out (output)

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

Introduction to Programming in .Net Environment

1-7 ©Masoud Milani

Parameters Passing Pass by reference

ref (input and output)

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=30b=20

Introduction to Programming in .Net Environment

1-8 ©Masoud Milani

Parameters Passing Reference types are passed by

reference by defaultpublic 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

Introduction to Programming in .Net Environment

1-9 ©Masoud Milani

Variable Number of Parameters

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;}

Introduction to Programming in .Net Environment

1-10 ©Masoud Milani

Method Overloading

More than one method with the same name can be defined for the same class

methods must have different signatures

Introduction to Programming in .Net Environment

1-11 ©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.

Introduction to Programming in .Net Environment

1-12 ©Masoud Milani

Operator Overloadingpublic 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;

Introduction to Programming in .Net Environment

1-13 ©Masoud Milani

Operator Overloadingpublic 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

Introduction to Programming in .Net Environment

1-14 ©Masoud Milani

Operator Overloadingpublic class MyType{

…public static MyType operator ++ (MyType x){

x.myValue += 1;return new MyType(x.myValue + 1);

}

}

MyType p(5);

MyType s=p++;

Introduction to Programming in .Net Environment

1-15 ©Masoud Milani

Operator Overloadingpublic 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("true");else Console.WriteLine("false");

Introduction to Programming in .Net Environment

1-16 ©Masoud Milani

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

Exams ex=new Exams();

ex [1] =100;Indexe

r

Introduction to Programming in .Net Environment

1-17 ©Masoud Milani

Indexer

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];

Introduction to Programming in .Net Environment

Exampleusing 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] = "empty";        }    }

   1-18 ©Masoud Milani

Introduction to Programming in .Net Environment

Examplepublic string this[int pos]

    {        get       {            return myData[pos];        }        set       {            myData[pos] = value;        }    }

   

1-19 ©Masoud Milani

Should use this keyword

Introduction to Programming in .Net Environment

Examplestatic void Main(string[] args)

    {        int size = 10;

        IntIndexer myInd = new IntIndexer(size);

        myInd[9] = "Some Value";        myInd[3] = "Another Value";        myInd[5] = "Any Value";

        Console.WriteLine("\nIndexer Output\n");

        for (int i=0; i < size; i++)        {            Console.WriteLine("myInd[{0}]: {1}", i,

myInd[i]);        }    }} 1-20 ©Masoud Milani

Introduction to Programming in .Net Environment

OutputIndexer 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 Value1-21 ©Masoud Milani

Introduction to Programming in .Net Environment

1-22 ©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

Introduction to Programming in .Net Environment

1-23 ©Masoud Milani

Exams class

public class Exams{

public Exams(int ex1, int ex2, int ex3){

…}

private int exam1;private int exam2;private int exam3;

public double Average{

…}

}

Introduction to Programming in .Net Environment

1-24 ©Masoud Milani

Inheritance

Implements isA relation Student isA Person

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;}

Introduction to Programming in .Net Environment

1-25 ©Masoud Milani

Inheritance A subclass can hide the inherited members of

its superclass using the keyword new

public class Person{

… public void Show() { Console.Write("Name: {0}, {1}", lastName, firstName)}

}

public class Student : Person{

…public new void Show(){

base.Show();Console.Write("major: {0}",

major);}

}

Introduction to Programming in .Net Environment

1-26 ©Masoud Milani

Inheritance

Person p = new Person("P1-F", "P1-L");p.Show();Console.WriteLine();

Student s=new Student("S1-F", "S1-L", "CS");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

Introduction to Programming in .Net Environment

1-27 ©Masoud Milani

Virtual Function

A class can allow its subclasses to override its member functions by declaring them virtualpublic class Person

{…

public virtual void Show() { Console.Write("Name: {0}, {1}", lastName, firstName)}

}

public class Student : Inheritance.Person{

…public override void Show(){

base.Show();Console.Write("major: {0}",

major);}

}

using namespace

the override keyword is also required.

Introduction to Programming in .Net Environment

1-28 ©Masoud Milani

Virtual Function

Person p = new Person("P1-F", "P1-L");p.Show();Console.WriteLine();

Student s=new Student("S1-F", "S1-L", "CS");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

Introduction to Programming in .Net Environment

1-29 ©Masoud Milani

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

Introduction to Programming in .Net Environment

Exampleusing 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("x = {0}, y = {1}", mC.x, mC.y);

}

}1-30 ©Masoud Milani

Introduction to Programming in .Net Environment

Example

class MyDerivedC: MyClass {

}

1-31 ©Masoud Milani

Complation error!

Introduction to Programming in .Net Environment

1-32 ©Masoud Milani

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

Introduction to Programming in .Net Environment

1-33 ©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

Introduction to Programming in .Net Environment

1-34 ©Masoud Milani

Abstract Classes

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("Name: {0}, {1}", lastName, firstName);

}}

Error:Abstract classes can not be instantiated

Person p(“FN-1”, “LN-1”);

Introduction to Programming in .Net Environment

1-35 ©Masoud Milani

Exercise

Courses

exam1exam2exam3

Average

take

sClass Grad Student

GradStudent( … )bool pass // >80void override Show()

class Student

string majordouble Average

Student( … )bool Pass // >60void override Show()

Abstract class Person

string fNamestring lName

Person(string fn, string ln)

void virtual Show()

isA

isA

Introduction to Programming in .Net Environment

1-36 ©Masoud Milani

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

Introduction to Programming in .Net Environment

1-37 ©Masoud Milani

Person class

public abstract class Person{

public Person(string fn, string ln){

…}private string firstName;private string lastName;

public virtual void Show(){

…}

}

Introduction to Programming in .Net Environment

1-38 ©Masoud Milani

Student class

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{

…}

}}

Introduction to Programming in .Net Environment

1-39 ©Masoud Milani

GradStudent class

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{

…}

}}

Introduction to Programming in .Net Environment

1-40 ©Masoud Milani

Files A file is a sequential sequence of bytes

Applicable classes Text Input

StreamReader

Text Output StreamWriter

Input/Output FileStream

NameSpace System.IO

Introduction to Programming in .Net Environment

1-41 ©Masoud Milani

StreamWriter

void WriteText(){

int[] data=new int[5]{1,2,3,4,5};

StreamWriter outFile=new StreamWriter("myOutFile.txt");

for(int i=0; i<data.Length; i++)outFile.WriteLine("data[{0}]={1}", i, data[i]);

outFile.Close();

}

myOutFile:data[0]=1data[1]=2data[2]=3data[3]=4data[4]=5

Introduction to Programming in .Net Environment

1-42 ©Masoud Milani

StreamReader Similar to StreamWriter

Check for end of stream using the method Peek()

StreamReader inpTextFile=new StreamReader("myOutFile.txt");

while(inpTextFile.Peek() >=0){

string nextLine=inpTextFile.ReadLine();Console.WriteLine(int.Parse(nextLine.Substring(nextLine.IndexOf("=")

+1)));} inpTextFile.Close();

Introduction to Programming in .Net Environment

1-43 ©Masoud Milani

Exercise

Modify the previous program to save and retrieve information

Introduction to Programming in .Net Environment

1-44 ©Masoud Milani

FileStream

To open a FileStream, we need to specify

Physical path

File Mode

File Access

Introduction to Programming in .Net Environment

1-45 ©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

Introduction to Programming in .Net Environment

1-46 ©Masoud Milani

FileAccess Enumeration

Read Read access

ReadWrite Read and write access

Write Write access

Introduction to Programming in .Net Environment

1-47 ©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

Introduction to Programming in .Net Environment

1-48 ©Masoud Milani

Formatter

Methods Writing

Serialize

Reading Deserialize

Exceptions: SerializationException

Introduction to Programming in .Net Environment

1-49 ©Masoud Milani

Serialization

string myString="string1";int myInt=16;int[] myData=new int[5]{1,2,3,4,5};

FileStream f=new FileStream("bFile", FileMode.Create, FileAccess.Write);

BinaryFormatter formatter=new BinaryFormatter();

formatter.Serialize(f, myString);formatter.Serialize(f, myInt);formatter.Serialize(f, myData);

f.Close();

Introduction to Programming in .Net Environment

1-50 ©Masoud Milani

[Serializable()]

Introduction to Programming in .Net Environment

1-51 ©Masoud Milani

Deserialization

string myString="string1";int myInt=16;int[] myData=new int[5]{1,2,3,4,5};

f=new FileStream("bFile", FileMode.Open, FileAccess.Read);

myString=(string)formatter.Deserialize(f);myInt=(int)formatter.Deserialize(f);newdata=(int[])formatter.Deserialize(f);

Console.WriteLine("myString={0}", myString);Console.WriteLine("myInt={0}", myInt);

Introduction to Programming in .Net Environment

1-52 ©Masoud Milani

Exercise

Modify the previous program to save and retrieve information using a Binary Formatter

Introduction to Programming in .Net Environment

1-53 ©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

….

Introduction to Programming in .Net Environment

1-54 ©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

Introduction to Programming in .Net Environment

1-55 ©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

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

Introduction to Programming in .Net Environment

1-56 ©Masoud Milani

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

Introduction to Programming in .Net Environment

1-57 ©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

Introduction to Programming in .Net Environment

1-58 ©Masoud Milani

Exception Handling

int[] a= new int[20];

try{

Console.WriteLine(a[2]);}catch (Exception e){

Console.WriteLine(e.Message);}finally{ Console.WriteLine(“Finally we are done!");}

Finally we are done!

Introduction to Programming in .Net Environment

1-59 ©Masoud Milani

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.

Introduction to Programming in .Net Environment

1-60 ©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

Introduction to Programming in .Net Environment

1-61 ©Masoud Milani

Programmer Defined Exceptions

Programmer defined exception classes must inherit from

ApplicationException class

Provide at least one constructor to set the message property

public class MyException : System.ApplicationException{

public MyException(string message):base(message){}

}

Introduction to Programming in .Net Environment

1-62 ©Masoud Milani

Programmer Defined Exceptions

public static int g(int a, int b){ // adds positive numbers

if (a <0){

MyException e=new MyException("1st parameter is negative");

throw(e);}if (b <0){

MyException e=new MyException("2nd dparameter is negative");

throw(e);}return a+b;

} try{

Console.WriteLine("g(4, -5)={0}", g(4, -5));}catch (Exception e)

Console.WriteLine(e.Message);}

Introduction to Programming in .Net Environment

1-63 ©Masoud Milani

Delegates

A delegate is a class that has only one or more methods

Allows methods to be treated like objects

delegate int D1(int i, int j);

Introduction to Programming in .Net Environment

1-64 ©Masoud Milani

Delegates

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);

}

1025

Introduction to Programming in .Net Environment

1-65 ©Masoud Milani

Delegates

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);}

1025

public static void f(D1 d){

d(5,5);}

Introduction to Programming in .Net Environment

1-66 ©Masoud Milani

Exercise Write a sort method that accepts an array of

integer and a boolean delegate, compare, and sorts the array according to the delegate

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;

}}

Introduction to Programming in .Net Environment

1-67 ©Masoud Milani

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

Introduction to Programming in .Net Environment

1-68 ©Masoud Milani

Interfaces

To add an interface, add a class and change it in the editor

interface IPublication{

string Title{

get;set;

}

string Publisher{

get;set;

}

void Display();}

Introduction to Programming in .Net Environment

1-69 ©Masoud Milani

Interfaces

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(){

…}

}

Introduction to Programming in .Net Environment

1-70 ©Masoud Milani

Interfaces

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("t0", "a0", "p0");

publications[1] = new Magazine("t1", "a1");

Display(publications);}

public class Magazine : Interfaces.IPublication{

…}

Introduction to Programming in .Net Environment

1-71 ©Masoud Milani

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