Object Oriented Programming With C Sharp Code Implementation

download Object Oriented Programming With C Sharp Code Implementation

of 77

Transcript of Object Oriented Programming With C Sharp Code Implementation

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    1/77

    In The Name of Allah, the most Gracious, the most MercifulObject-Oriented Programming Course

    *Contents of the course:1-Objects2-Classes

    3-Methods4-Arrays5-Encapsulation6-PolymorPhism7-Pattern Design

    *General Introduction to Object-Oriented Programming:-Object-Oriented Programming also Called OOP-Object-Oriented Programming is used to organize the code and

    refine it in the application.-It prevents the code redundancy.-It makes the code readable, reusable, and reliable.-It enables us to maintain the program code, modify it, and easydetermine any exceptions.

    *General Example about Object-Oriented Programming:-If we look to the real life, we will find that, it contains a lot ofthings surround us like cars, humans, bridges, buildings, birds

    -If we need to store some information about each category of thesethings likeCar-model, size, length, speedHuman-name, length, weight, genderBridges-location, length, height, strengthAnd so on.-This will generate for us a great amount of data in the Main Methodin my program, and it will not be elegant.-Also if there are exceptions, it will be difficult to correct it.-From here the OOP is created.

    -we can use the OOP to make the following example as anapplication1-We will make each category {cars, humans, bridges, buildings,birds} as a class that contain the records and tasks that eachcategory has likeCar-acceleration, break, steering wheel, horn toolHuman-moving, seeing, eating, writing, reading, sleepingAnd so on.-All of these tasks will be recorded inside the class and will bespecial only for each category.

    2-After that, we can easily access the code, maintain it, correct anyexceptions, and reuse it.

    The important topics in our course are

    Objects, Classes, Methods, and Arrays

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    2/77

    3-The code will be elegant and organized.4-By this we can prevent any redundancy and code overlapping.

    *Illustration Example of OOPWe can use the car as an illustration example to discover andunderstand the basics of classes, objects, methods, callingmethods, properties, and instance variables

    The Car in Real Life In Object-Oriented Programming

    1-Before using the car, it musthave an engineering drawing anddesign which include a design forevery thing in the car.

    1-Any program must begin bycreating a class.Car engineering designs in reallife == the classes in Object-Oriented Programming.

    2-The design of the car includinga design for the following tools:-Accelerator Pedal whichmakes the car goes faster.-Break Pedal which slowsdown the car.-Steering Wheel which turnthe car in all directions.-Gear that change the speedof the car.

    -Horn which warn others.

    All of these tools perform a taskin the car (complex) anddescribe the mechanism thatactually performs its task whichalways is hidden.

    2-All of these tools and tasks inthe car can convert in theObject-Oriented Programminginto Methods.The methods in the class areusually performing a task in theapplication, and they hide thecomplex task.Look like the car, it can containmore than one task also the

    class may contain more than onemethodthat are created toperform tasks in the class.Car's tasks in the real life ==classes'methods.

    3-To use the car, the man mustbuild it first, and make itcomplete with all tasks and

    things to perform it.Like if the driver needs toaccelerate the car, he mustpress on a small tool called theaccelerator to make the car goesfaster.

    3-We can not able to use anything inside a class until wemake an objectof it.

    The objectis a reference basedon the class and some timescalled an instance of the class.Each objecthas two things,Those are status, and thebehavior.

    4-If the driver needs toaccelerate the car, he mustpress on a small tool called theaccelerator to make the car goes

    faster, which sends a message tothe car to perform a task that

    4-To use a specific task in theclass like Methods, we must callthis Methodby the object{instance method} to perform

    the specific task that we need.Accelerating the car in the real

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    3/77

    can make the car faster. life==calling the methods.

    5-Each car has attributes, likecolor, length, speed, model, size,weight, tank size, total milesdriven, no of doors, shape, no oftires and its shape.Each car has its own attributesthat may be difference or similarto another car.

    5-The attributes are specified asa part of the objectand they arethe classes'instance variablesand some times called fields.Attributes are not necessarilyaccessible directly.

    6-The manufacturer doesn'twant the drivers to take a partwith the car's engine to observethe amount of gas in the tank,instead, the driver can check themeters and tank state on the

    dashboard.

    6-We don't need to have anaccess to an object's instancevariables in order to use them,but we can use thepropertyofthe objectwhich consists ofgetand setaccesses for reading

    (retrieve) and write (modify)values of the object's instancevariables respectively.

    *First: OOPObjects**Key Points:1- Definition.2- Creating.3- Properties.

    1-Object Definition:-Is a reference based on the class and some times called "Instanceof the Class".-Has status, and behavior like thatObject statusFields, and Properties.

    Object behaviorMethods

    Example:Like the computer

    The computer

    Has behavior that, itis switched on, orswitched off

    Has status that, it isnow switching on, or itis now switching off

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    4/77

    2-Object Creation:We can create our object by using the keyword "new" and the classname like the following conception:

    Classname Objectname=new Classname ();

    Example:Let us have a class with the name Studentand need to use itsmembers so; we create an object of it as the following:

    Student GetStudentData=new Student ();

    3-Object Properties:-Every thing in the c# is an object that inherits from the base class"object"like the windows forms and controls.-They often used to access classes' members to perform a specifictask.

    -They have properties and characteristics to obtain data and changethe information that contain.-They often used to access only the public instance members, notapplied for the static members.

    *Second: OOPClasses**Key Points:1- Definition.2- Creating.

    3- Access Modifiers.4- Access Methods.5- Constructors.6- Destructors.7- Property.8- Instance and Static.9- General Examples10- Inheritance.

    1- Class Definition:

    -The class is a container of data and methods that will operate anduse it.

    The class

    name

    The name of

    the object

    The keyword

    new, sometimes calledoperator new

    The constructor ofthe class [defaultconstructor]

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    5/77

    -The class is about a blueprint for a custom data type.2-Class Creating:-We can create the class by using the keyword "class"like thefollowing conception:

    class Classname{// add code to execute.// add fields, methods, properties}

    Example:Let us have a class that has the some fields and some methods as

    the following://initiate the class

    publicclassArithmeticOperations{

    //define fieldsprivateint x, y;

    //default constructor

    public ArithmeticOperations(){}//end default constructor

    //summation methodpublicint Sum(int m, int n){

    if(m > 0)

    x = m;if(n > 0)y = n;

    int s;

    return s = x + y;}//end summation method

    }//end the class

    3-Access Modifiers:-They are the methods that are responsible for the way of how toinput and output the data in a class

    -there are five types of the access modifiers:public, private, protected, internal, protected internal.

    (1-) Public Access Modifier:-The member can be used and accessed in the same class, or inall the program because there is no any restrictions on it.

    -To Access it, we use the object + the dot operator (.)Example:using System;using System.Collections.Generic;using System.Linq;

    using System.Text;

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    6/77

    namespace AccessingPublicMembers{

    //initiate the classclassSampleClass

    {publicint x;//define public field

    //add any statements to complete the class}//end class

    //initiate another classclassProgram

    {//define the main methodstaticvoid Main(string[] args)

    {//create object from the first class//to enable us to access field in itSampleClass myobject = newSampleClass();

    //using object to access the public field

    myobject.x = 3;Console.WriteLine("the value of the public field is : {0}", myobject.x);

    }}

    }

    The output of this example will be as following:

    (2-) Private Access Modifier:-The member can used only in the same class, or it can beaccessed by using some special public methods like get and setfor reading and writing values respectively.Get() Function for read only the data(retrieve).Set() Function for write only the data(modify).

    Both for read and write data in the class.-It makes the information hidden, and the variable isencapsulated in the object, and can be accessed by methodsand properties of the class.

    Example:using System;using System.Collections.Generic;

    using System.Linq;using System.Text;

    namespace AccessingPrivateMembers

    {//initiate the classclassMyCar

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    7/77

    {//define private fields

    privatestring myCarColor;privatedecimal myCarLength;

    //define special public method to access the private fields//define the set method for modifying values of the first field

    publicvoid SetMyCarColor(string color){

    myCarColor = color;}//end first set method

    //define the set method for modifying vallues of the second fieldpublicvoid SetMyCarLength(decimal length){

    myCarLength = length;}//end second set method

    //define the get method for retrieving values of the first fieldpublicstring GetMyCarColor()

    {

    return myCarColor;}//end first get method

    //define the get method for retrieving values of the second fieldpublicdecimal GetMyCarLength(){

    return myCarLength;

    }}//end class

    //initiate another classclassProgram

    {//define the main method

    staticvoid Main(string[] args){

    //create object from the first class//to enable us to access fields in itMyCar car = newMyCar();

    //using object to access the private fieldscar.SetMyCarColor("Black");car.SetMyCarLength(250.35m);

    //print dataConsole.WriteLine("my car color is : {0}, \nand my car length is :

    {1}",car.GetMyCarColor(),car.GetMyCarLength());}

    }}

    the output of this example will be as the following:

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    8/77

    -When we use the object of the MyCar class which is car to accessthe private members, we use set methods to pass values(write&modify) to the private fields.-When we type the name of the object and use the dot operator (.),we will find a small menu called intellisense will appear to you with

    all methods in the first class that you need to access as thefollowing:

    -The same thing occurs when we use the object to get the data(retrieve&read) of the private fields.-When we type the name of the object and use the dot operator (.),we will find a small menu called intellisense will appear to you withall methods in the first class that you need to access as thefollowing:

    (3-) Protected Access Modifier:-The member can be used in the same class of in the derivedclass by using inheritance.

    Example:If we need to make an object from the inherited class not from the

    base classusing System;using System.Collections.Generic;

    using System.Linq;using System.Text;

    namespace AccessingProtectedMembers{

    //initiate the classclassEmployee{

    //define protected fields

    protectedstring firstName;protectedstring secondName;

    Here we will find all methods that wedeclared it as public in the MyCar class like:GetMyCarColor(),GetMyCarLngth(),SetMyCarColor(),SetMyCarLength(),And we use set methods only.

    Here we will find all methods that we declaredit as public in the MyCar class like:GetMyCarColor(),GetMyCarLngth(),

    SetMyCarColor(),SetMyCarLength();And we use get methods only.

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    9/77

    protectedint myAge;}//end class

    //initiate another classclassProgram:Employee{

    //define the main method

    staticvoid Main(string[] args){

    //using object to access the protected fields//object form the inherited class

    Program prog=newProgram();prog.firstName="Joseph";prog.secondName="Gradecki";

    prog.myAge=45;//print dataConsole.WriteLine("the first name is : {0}, \nand the last name is : {1},

    \nand age is : {2}",prog.firstName,prog.secondName,prog.myAge);

    }

    }}

    The output of this example will be as the following:

    -When we type the name of the object prog and use the dotoperator (.), we will find a small menu called intellisense will appearto you with all protected fields in the first class that you need toaccess as the following:

    If we need to make an object form the base class Employee, we must use public getand set method to access it be the object, and note that we can use the inheritance ornot use it, like the following examples:using System;using System.Collections.Generic;

    using System.Linq;using System.Text;

    Here we will find all protected fields that we

    declared it in the Employee class like:firstName;myAge;

    secondName;

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    10/77

    namespace AccessingProtectedMembers

    {//initiate the classclassEmployee{

    //define protected fieldsprotectedstring firstName;protectedstring secondName;protectedint myAge;

    //define special public method to access the protected fields//define the set method for modifying values of the first fieldpublicvoid SetFirstName(string fname)

    {firstName = fname;

    }//end first set method//define the set method for modifying vallues of the second field

    publicvoid SetSecondName(string sname)

    {secondName = sname;

    }//end second set method//define the set method for modifying vallues of the third fieldpublicvoid SetMyAge(int age){

    myAge = age;}//end third set method

    //define the get method for retrieving values of the first fieldpublicstring GetFirstName()

    {return firstName;

    }//end first get method//define the get method for retrieving values of the second fieldpublicstring GetSecondName(){

    return secondName;

    }//end second get method//define the get method for retrieving values of the third fieldpublicint GetMyAge()

    {return myAge;

    }//end third get method}//end class

    //initiate another classclassProgram : Employee//inheritance{

    //define the main method

    staticvoid Main(string[] args){

    //using object to access the protected fields

    //object form the base classEmployee emp = newEmployee();emp.SetFirstName("Joseph");emp.SetSecondName("Gradecki");

    emp.SetMyAge(45);//print data

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    11/77

    Console.WriteLine("the first name is : {0}, \nand the last name is : {1},\nand age is : {2}", emp.GetFirstName(), emp.GetSecondName(),

    emp.GetMyAge());}

    }}

    The output of this example will be as the following:

    And as I said before if we followed this way by creating object from the base classEmployee it will be as the private access modifier as the following:using System;

    using System.Collections.Generic;using System.Linq;using System.Text;

    namespace AccessingProtectedMembers{

    //initiate the classclassEmployee

    {//define protected fieldsprotectedstring firstName;

    protectedstring secondName;protectedint myAge;

    //define special public method to access the protected fields//define the set method for modifying values of the first field

    publicvoid SetFirstName(string fname){

    firstName = fname;

    }//end first set method//define the set method for modifying vallues of the second field

    publicvoid SetSecondName(string sname){

    secondName = sname;}//end second set method

    //define the set method for modifying vallues of the third fieldpublicvoid SetMyAge(int age){

    myAge = age;}//end third set method

    //define the get method for retrieving values of the first fieldpublicstring GetFirstName(){

    return firstName;}//end first get method

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    12/77

    //define the get method for retrieving values of the second fieldpublicstring GetSecondName()

    {return secondName;

    }//end second get method//define the get method for retrieving values of the third field

    publicint GetMyAge(){

    return myAge;}//end third get method

    }//end class//initiate another classclassProgram//no inheritance

    {//define the main methodstaticvoid Main(string[] args){

    //using object to access the protected fields

    //object form the base classEmployee emp = newEmployee();

    emp.SetFirstName("Joseph");emp.SetSecondName("Gradecki");emp.SetMyAge(45);

    //print data

    Console.WriteLine("the first name is : {0}, \nand the last name is : {1},\nand age is : {2}", emp.GetFirstName(), emp.GetSecondName(),emp.GetMyAge());

    }

    }}

    The output of this example will be as the following:

    -When we type the name of the object emp and use the dotoperator (.), we will find a small menu called intellisense will appearto you with all public methods in the first class Employee that youneed to access as the following:

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    13/77

    -When we type the name of the object emp and use the dotoperator (.), we will find a small menu called intellisense will appearto you with all public methods in the first class Employee that youneed to access as the following:

    (4-) Internal Access Modifier:-Is the default access modifier for the class if there is no

    specified access modifier-Allows the member to be used in the same class or another

    class in the sameAssembley.

    -Within the same class it is equivalent to public accessmodifier, but can not be

    used in making .dll files.

    -All members in the internal class can be used in any place inthe same program,

    but not to code in another programs or assemblies.-Some people use the keyword "static" after writing the

    internal access modifierand befor the data type of the field.In this case, the class or the members can not be able to be

    instantiated because of existing of the keyword "static".-To Access it, we use the object + the dot operator (.)

    Example:using System;using System.Collections.Generic;using System.Linq;

    Here we will find all public methods that wedeclared it in the Employee class like:SetFirstName();

    SetMyAge();SetSecondName();And we here use the set methods only

    Here we will find all public methods that wedeclared it in the Employee class like:GetFirstName();GetMyAge();GetSecondName();And we here use the get methods only

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    14/77

    using System.Text;

    namespace AccessingInternalMembers{

    //initiate the classclassSampleClass

    {internalint x;//define internal field

    //add any statements to complete the class}//end class

    //initiate another classclassProgram{

    //define the main methodstaticvoid Main(string[] args){

    //create object from the first class

    //to enable us to access field in it

    SampleClass myobject = newSampleClass();//using object to access the internal field

    myobject.x = 3;Console.WriteLine("the value of the internal field is : {0}", myobject.x);

    }}

    }The output of this example will be as the following:

    In this example, the internal access modifier is used as the publicaccess modifier.-When we type the name of the object myObject and use the dotoperator (.), we will find a small menu called intellisense will appearto you with all public methods in the first class Employee that you

    need to access as the following:

    (5-) Protected Internal Access Modifier:-The members can be accessed by any code in the same class,

    in the derived class, or any class in the same program.Example:

    Here we will find all internal fields that wedeclared it in the SampleClass class like:The field x,And we here use it directly

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    15/77

    using System;using System.Collections.Generic;

    using System.Linq;using System.Text;

    namespace AccessingProtectedInternalMembers

    {//initiate the classclassEmployee{

    //define protected fieldsprotectedinternalstring firstName;protectedinternalstring secondName;

    protectedinternalint myAge;//define special public method to access the protected internal fields//define the set method for modifying values of the first fieldpublicvoid SetFirstName(string fname)

    {

    firstName = fname;}//end first set method

    //define the set method for modifying vallues of the second fieldpublicvoid SetSecondName(string sname){

    secondName = sname;

    }//end second set method//define the set method for modifying vallues of the third fieldpublicvoid SetMyAge(int age){

    myAge = age;}//end third set method

    //define the get method for retrieving values of the first fieldpublicstring GetFirstName(){

    return firstName;}//end first get method

    //define the get method for retrieving values of the second fieldpublicstring GetSecondName(){

    return secondName;}//end second get method

    //define the get method for retrieving values of the third fieldpublicint GetMyAge()

    { return myAge;}//end third get method

    }//end class

    //initiate another classclassProgram//no inheritance{

    //define the main methodstaticvoid Main(string[] args){

    //using object to access the protected internal fields

    //object form the first classEmployee emp = newEmployee();emp.SetFirstName("Harvey");

    emp.SetSecondName("Deitel");

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    16/77

    emp.SetMyAge(55);//print data

    Console.WriteLine("the first name is : {0}, \nand the last name is : {1},\nand age is : {2}", emp.GetFirstName(), emp.GetSecondName(),emp.GetMyAge());

    }

    }}

    The output of this example will be as the following:

    or we can use the protected internal access modifier without usingthe set or get methods, and this will be done by using the objectdirectly to access the protected internal fields as the following:Example:using System;using System.Collections.Generic;using System.Linq;using System.Text;

    namespace AccessingProtectedInternalMembers

    {//initiate the classclassEmployee{

    //define protected fieldsprotectedinternalstring firstName;protectedinternalstring secondName;

    protectedinternalint myAge;

    }//end class//initiate another class

    classProgram//no inheritance

    {//define the main methodstaticvoid Main(string[] args){

    //using object to access the protected fields//object form the first class

    Employee emp = newEmployee();emp.firstName = "Harvery";emp.secondName = "Deitel";emp.myAge = 55;

    //print dataConsole.WriteLine("the first name is : {0}, \nand the last name is : {1},

    \nand age is : {2}", emp.firstName, emp.secondName, emp.myAge);}

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    17/77

    }}

    The output of this example will be as the following:

    Or we can use inheritance in our example to access the protectedinternal fields in the base class by using an object from the baseclass as the following:Example:using System;

    using System.Collections.Generic;using System.Linq;using System.Text;

    namespace AccessingProtectedInternalMembers{

    //initiate the classclassEmployee

    {//define protected fieldsprotectedinternalstring firstName;protectedinternalstring secondName;

    protectedinternalint myAge;

    }//end class

    //initiate another classclassProgram:Employee{

    //define the main methodstaticvoid Main(string[] args){

    //using object to access the protected fields//object form the base classEmployee emp = newEmployee();emp.firstName = "Harvey";emp.secondName = "Deitel";

    emp.myAge = 55;//print dataConsole.WriteLine("the first name is : {0}, \nand the last name is : {1},

    \nand age is : {2}", emp.firstName, emp.secondName, emp.myAge);}

    }}

    The output of this example will be as the following:

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    18/77

    Or we can use inheritance in our example to access the protectedinternal fields in the base class by using an object from theinherited class as the following:Example:using System;using System.Collections.Generic;using System.Linq;

    using System.Text;

    namespace AccessingProtectedInternalMembers{

    //initiate the classclassEmployee{

    //define protected fields

    protectedinternalstring firstName;protectedinternalstring secondName;protectedinternalint myAge;

    }//end class//initiate another classclassProgram:Employee

    {//define the main methodstaticvoid Main(string[] args){

    //using object to access the protected fields//object form the inherited classProgram prog = newProgram();

    prog.firstName = "Harvey";prog.secondName = "Deitel";prog.myAge = 55;

    //print dataConsole.WriteLine("the first name is : {0}, \nand the last name is : {1},

    \nand age is : {2}", prog.firstName, prog.secondName, prog.myAge);}

    }}

    The output of this example will be as the following:

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    19/77

    But if we didn't use the inheritance, we can not use an object fromthe inherited class Program which is prog and the compiler will

    generate a syntax error.

    *The General Algorithm for Access Modifiers, and Access Methods:

    1-Initiate the class.2-Define the members.3-Accessing Members

    if(members public)

    use it in the same classuse object + dot operator (.)

    elseif(members private)

    use it in the same classuse special methods like get and set

    get for reading onlyset for writing only

    elseif(members protected)

    use it in the same classuse inheritance

    elseif(members internal)if(use internalstatic)

    use it in the same class

    elseuse it in the same classuse it aspublic

    else //protected internaluse it in the same class

    use it by inheritanceuse it aspublic

    4-End the program.

    *General Properties:

    1-Classes define the object, but not an object itself.2-Object is a reference based on the class and called Instance of it.3-The default access modifier for the classes is internal, and thedefault access modifier for the members is private.

    4-Structs members can not be declared protected, or protectedinternal because it is not support the inheritance.

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    20/77

    5-Destrcutors can not take any access modifiers.6-Constructors must be public.7-Enumeration is public.8-only one access modifier is allowed for a member except whenusing the protected internal access modifier.

    9-Namespace doesn't take any access modifier, because it has noany restriction.

    *Enumeration:

    **Key Points:1-Definition.2-Creation.3-Underlying types.4-Build-In Data types.

    1-Definition:-Enumeration is about a distinct type consisting of a set ofnamed constants called the "Enumerator List".

    2-Creation:-We can declare the enumeration by using the keyword "enum".-By default, the first value of the first enumerator is [0], and thevalue of the successive enumerators is increased by [1].

    -As the following examples;Example:

    using System;using System.Collections.Generic;using System.Linq;

    using System.Text;

    namespace EnumeratorList{

    classProgram{

    enumletter { A, B, C, D, E };

    staticvoid Main(string[] args){

    //get the elements in the listConsole.WriteLine(letter.A);

    Console.WriteLine(letter.B);Console.WriteLine(letter.C);Console.WriteLine(letter.D);

    Console.WriteLine(letter.E);Console.WriteLine("\n\n");

    //do an explicit cast//to get the corresponding values for the

    //enumerator list elements

    int a = (int)letter.A;int b = (int)letter.B;

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    21/77

    int c = (int)letter.C;int d = (int)letter.D;

    int e = (int)letter.E;//print valuesConsole.WriteLine("the value of enumerator A is : {0}", a);Console.WriteLine("the value of enumerator B is : {0}", b);

    Console.WriteLine("the value of enumerator C is : {0}", c);Console.WriteLine("the value of enumerator D is : {0}", d);Console.WriteLine("the value of enumerator E is : {0}", e);Console.WriteLine("\n\n");

    }}

    }

    The Output of this example will be as the following:

    -We can override the default value of the first enumerator, andthis can be done by passing a value to the first enumerator.As the following example;

    using System;

    using System.Collections.Generic;using System.Linq;using System.Text;

    namespace EnumeratorList{

    classProgram{

    enumletter { A=10, B, C, D, E };staticvoid Main(string[] args){

    //get the first elementConsole.WriteLine(letter.A);Console.WriteLine(letter.B);Console.WriteLine(letter.C);

    Console.WriteLine(letter.D);Console.WriteLine(letter.E);Console.WriteLine("\n\n");

    //do an explicit cast//to get the corresponding values for the

    //enumerator list elementsint a = (int)letter.A;

    int b = (int)letter.B;

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    22/77

    int c = (int)letter.C;int d = (int)letter.D;

    int e = (int)letter.E;//print valuesConsole.WriteLine("the value of enumerator A is : {0}", a);Console.WriteLine("the value of enumerator B is : {0}", b);

    Console.WriteLine("the value of enumerator C is : {0}", c);Console.WriteLine("the value of enumerator D is : {0}", d);Console.WriteLine("the value of enumerator E is : {0}", e);Console.WriteLine("\n\n");

    }}

    }

    The Output of this example will be as the following:

    Example:using System;using System.Collections.Generic;using System.Linq;using System.Text;

    namespace EnumeratorList

    {publicenumDayOfWeek{

    Sunday = 0,Monday = 1,Tuesday = 2,Wednesday = 3,

    Thursday = 4,Friday = 5,Saturday = 6

    }

    classProgram{

    staticvoid Main(){

    DayOfWeek day = DayOfWeek.Thursday;int x = (int)DayOfWeek.Thursday;

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    23/77

    System.Console.WriteLine("today is : {0}, \n\nand the value of the dayin the enumerator list is: {1}", day, x);

    Console.WriteLine("\n\n");}

    }}

    The Output of this example will be as the following:

    3-Underlying Types:-Every enumerator type has an underlying type which can be anyintergral type except "char", and the default underlying type is"int".-We can see this in the cast operation;-In the previous two examples, we saw that, to get the value ofthe enumerator elements in the enumerator list, we convert eachenumerator to the default underlying type which is "int".-The importance of using the underlying types is to specify how

    much storage is allocated for each enumerator in the memory.

    4-Build-In Data Types:-As we know, there is about sixteen [16] primary build-in datatypes, as list in the following table:

    Build-InDataTypes

    Used For:The use of the data type in the object

    oriented programming

    StorageSize inBytes

    bool true or false values 1 byte

    byte Values from [0] to [255] 1 bytesbyte Values from [-128] to [127] 1 byte

    char Single Unicode character 2 bytes

    DateTime Values from [01/01/0001] to [12/31/9991] 8 bytes

    decimal Decimal fraction, with precision of 28-digits 16 bytes

    double Double precision floating point numbers, with14-digits of accuracy

    8 bytes

    float Single precision floating point numbers, with6-digits of accuracy

    4 bytes

    short Small integers in the range of [-32,768] to

    [32,767]

    2 bytes

    ushort Values from [0] to [65,536] 2 bytes

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    24/77

    int Whole numbers in the range of [-2,147,483,648] to [2,147,483,647]

    4 bytes

    uint Values from [0] to [4,294,967,296] 4 bytes

    long Larger whole number 8 bytes

    ulong Values from [0] to [1.844674407*10^19] 8 bytes

    string Alphanumeric data, letters, digits, and othercharacters

    Eachletter 2bytes

    object Any type of data 4 bytes

    *Cast Operation:**Key Points:

    1-Definition.2-Types.

    1-Definition:It means that, the conversion from one data type to another.

    2-Types:There are two types of the cast operation

    *Implicit Cast Operation:-It is used to convert from smaller data type to bigger datatype.-There is no any lose in the data.

    Example:using System;using System.Collections.Generic;using System.Linq;using System.Text;

    SmallerData T e Convert into

    BiggerData T e

    NOLose

    InData

    ImplicitCast

    Result

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    25/77

    namespace ImplicitCast

    {classProgram

    {staticvoid Main()

    {//before castingint x = 1234;int m = x;

    Console.WriteLine("\n\tthe value of m before casting is : {0}", m);Console.WriteLine("\n\n");

    //after casting

    //this is the implicit cast//double is longer than int//double is 8 bytes storage//int is 4 bytes storage

    //it is ok to put 4 in 8

    //and there is no lose in datadouble n = m;

    Console.WriteLine("\tthe value of n after casting is : {0}", n);Console.WriteLine("\n\n");

    }}

    }

    The Output of this example will be as following:

    From this, we can convert any smaller data type to any bigger datatype as the following:byteshort, int, long, float, double, decimal.shortint, long, float, double, decimal.intlong, float, double, decimal.

    longfloat, double, decimal.floatdouble only.

    *Explicit Cast Operation:-It is used to convert from bigger data type to smaller data

    type.-There is significant lose in the data.

    Can not convert float into decimal implicitly, and this can be done with the explicit cast.

    Can not convert double into decimal implicitly, and this can be done with the explicit cast

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    26/77

    -The way of the explicit cast is to put the data type (smaller)that we need to convert into, between braces like this () andafter it the value that we need to cast itExample:

    using System;using System.Collections.Generic;

    using System.Linq;using System.Text;

    namespace ExplicitCast{

    classProgram{

    staticvoid Main(){

    //before castingdouble x = 1234.56;

    Console.WriteLine("\n\tthe value of x before casting is : {0:}", x);Console.WriteLine("\n\n");

    //after casting//this is the explicit cast//double is longer than int//double is 8 bytes storage//int is 4 bytes storage

    //it is not ok to put 4 in 8//and there is significant lose in dataint m = (int)x;//this is the way of explicit cast

    Console.WriteLine("\tthe value of n after casting is : {0}", m);Console.WriteLine("\n\n");

    }}

    }

    the Output of this example will be as the following:

    BiggerData T e Convert into

    SmallerData T e

    LoseIn

    Data

    ExplicitCast

    Result

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    27/77

    5- Constructor:**Key Points:1-Definition.2-Properties.3-Default Values of Build-In Data Types.4-Constructor Types. default overloaded static5- Inheriting Constructor.6-Calling Constructor.

    1-Definition:Is a special method like any method, and it is considered the

    heart of the classes.

    2-Properties:The constructor has the following properties, which distinguish itfrom other methods:1- Has the same name as the class.2- Doesn't return any value.3-Called automatically when the object is created.4-Executed before any code in the class.5- Is an ideal location for any initialization task.6-Must be Public (Access Modifier), because the object must

    access and execute it.7-The "new" operator calls it, when creating an object.8-Has two types (default[parameterless], and overloaded

    [parameterized]).9-The overloaded constructor can take any number of

    parameters to use the data.10- It is called when the class is created.11- Can be found more than one constructor in the class.

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    28/77

    12- It is created spontaneously if we never created anyconstructor and be the default constructor that takes noparameters.

    3-Default Values of Build-In Data Types:As we saw, there are sixteen [16] primary build-in data types.When we create a class, but we didn't create or build anyconstructors inside this class, the compiler spontaneously willcreate an implicit default constructor, and use the defaultvalues of the data types for your attributes in the class thathave no initialization values.As the following table contents, we will find all of the defaultvalues of the primary build-in types.

    Build-In

    DataTypes

    Default

    Value

    Build-In

    DataTypes

    Default

    Value

    bool False int 0

    byte 0 uint 0

    sbyte 0 long 0L

    decimal 0.0M ulong 0L

    double 0.0D string null

    float 0.0F object null

    short 0 enum 0

    ushort 0 char null

    4-Constructor Types:There are three basic constructors that used widely in theObject-Oriented Programming[OOP].

    *Default Constructor:-Which has no any parameters-Is created spontaneously and implicitly if you never createdany constructor in the class.

    Example:using System;using System.Collections.Generic;

    using System.Linq;using System.Text;

    namespace DefaultConstructor

    {//initiate a classclassMyCar

    {//define the fields of the class

    privatestring myCarColor;privatedecimal myCarLength;

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    29/77

    //default constructor//must be public

    //has the same name as the class//doesn't return any value//ideal location for any initialization taskpublic MyCar()

    {myCarColor = "black";myCarLength = 250.35M;

    }//end default constructor

    //define get methodspublicstring GetMyCarColor(){

    return myCarColor;}publicdecimal GetMyCarLength(){

    return myCarLength;

    }//end get methods}

    classProgram{

    staticvoid Main(){

    //creating object from the classMyCar car = newMyCar();

    //print dataConsole.WriteLine("my car color is : {0}, \nand my car length is : {1}",

    car.GetMyCarColor(), car.GetMyCarLength());}

    }}

    The Output of this example will be as the following:

    *OverLoaded Constructor:-Which take parameters, and make an assignment for the instancevariables in the class.-If you make an overloaded constructor, the compiler will not makethe default constructor.-Can be found more than one overloaded constructor in the class.Example:using System;

    using System.Collections.Generic;using System.Linq;

    using System.Text;

    The location ofinitialization

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    30/77

    namespace OverloadedConstructor{

    //initiate a classclassMyCar{

    //define the fields of the class

    privatestring myCarColor;privatedecimal myCarLength;

    //overloaded constructor//must be public

    //has the same name as the class//doesn't return any value//ideal location for any initialization task

    //making an assignment for the instance variablespublic MyCar(string color, decimal length){

    //assignment for instance variables

    myCarColor = color;

    myCarLength = length;}//end overloaded constructor

    //define get methodspublicstring GetMyCarColor(){

    return myCarColor;

    }publicdecimal GetMyCarLength(){

    return myCarLength;

    }//end get methods}

    classProgram{

    staticvoid Main(){

    //creating object from the class

    MyCar car = newMyCar("black", 250.35M);//print dataConsole.WriteLine("my car color is : {0}, \nand my car length is : {1}",

    car.GetMyCarColor(), car.GetMyCarLength());}

    }}

    The Output of this example will be as the following:

    *Static Constructor:

    -Constructors can be declared Static be using the keyword "static".

    The location ofinitialization

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    31/77

    -Static constructors are called automatically and immediately beforeany static fields are accessed.-Are normally used to initialize Static classes and members.-Are used to initialize any static data or perform a particular actionthat needs to be performed once time only.

    -They aren't take any access modifiers.-They aren't take any parameters.-They can't be called directly.Example:

    //static constructor//can not take any access modifier//can not take any parameters//has the same name as the class//doesn't return any value//ideal location for any initialization taskstatic MyCar()

    {myCarColor = "black";myCarLength = 250.35M;

    }//end static constructor

    5- Inheriting Constructor:-The constructor can use the keyword "base" to call aconstructor of the base class in inheritance.-To call the default base constructor, use "base" without anyparameters.

    -To call the overloaded base constructor, use "base" withparameters.-When calling the overloaded base constructor, the keyword"base" will has the parameter that match the base constructorin number of parameters, parameters types, parameterssequence, else it will be a syntax error.Example:

    using System;using System.Collections.Generic;using System.Linq;

    using System.Text;

    namespace InheritingConstructor

    {//initiate a classclassMyBook{

    //define the fieldsprivatestring Name;privatestring Author;

    //the overloaded constructorpublic MyBook(string name, string author){

    //assignment for instance variablesName = name;

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    32/77

    Author = author;}//end the overloaded constructor

    }//end MyBook class//initiate another class that inherit from the first classclassMyPaper : MyBook//inheritance{

    //define the fieldsprivatestring BookName;privatestring BookAuthor;

    //the overloaded constructor that call the overloaded

    //constructor from the base classpublic MyPaper(string bookName, string bookAuthor)

    : base(bookName,bookAuthor)

    {BookName = bookName;BookAuthor = bookAuthor;

    }//end the overloaded constructor of the derived class

    //define the get methods

    publicstring GetBookName(){

    return BookName;}publicstring GetBookAuthor(){

    return BookAuthor;}//end the get methods

    }classProgram

    {staticvoid Main()

    {//creating object from the base classMyBook book = newMyBook("java", "William Harvey");

    //print dataConsole.WriteLine("\n\tmy book name is : {0}, \n\tand my book author

    is : {1}", book.GetBookName(), book.GetBookAuthor());Console.WriteLine("\n\n");

    //creating object from the derived class

    MyPaper paper = newMyPaper("C# Fundamentals", "Joseph D.Gradecki");

    //print dataConsole.WriteLine("my book name is : {0}, \nand my book author is :

    {1}", paper.GetBookName(), paper.GetBookAuthor());Console.WriteLine("\n\n");}

    }

    }

    The Output of this example will be as the following:

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    33/77

    6-Calling Constructor:-The constructor can use the keyword "this" to call aconstructor of the same class.-To call the default constructor, use "this" without anyparameters.-To call the overloaded constructor, use "this" withparameters.-When calling the overloaded constructor, the keyword "this"will has the parameter that match the constructor in number ofparameters, parameters types, parameters sequence, else itwill be a syntax error.Example:

    using System;

    using System.Collections.Generic;using System.Linq;using System.Text;

    namespace CallingConstructor{

    //initiate a classclassMyBook{

    //define the fieldsprivatestring Name;privatestring Author;

    //the default constructorpublic MyBook(){

    Name = "Visual C # 2005 How to Program";

    Author = "Pual Deitel";}

    //the overloaded constructorpublic MyBook(string name, string author):this()

    {//assignment for instance variablesName = name;Author = author;

    }//end the overloaded constructor//define the get methodspublicstring GetBookName()

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    34/77

    {return Name;

    }publicstring GetBookAuthor(){

    return Author;

    }//end the get methods}//end MyBook class

    //initiate another class that inherit from the first classclassProgram

    {staticvoid Main(){

    //creating object from the classMyBook book = newMyBook();

    //print dataConsole.WriteLine("\n\tmy book name is : {0}, \n\tand my book author

    is : {1}", book.GetBookName(), book.GetBookAuthor());

    Console.WriteLine("\n\n");}

    }}

    The Output of this example will be as the following:

    7-Destructor:**Key Points:1- General Introduction.2- Definition.3- Properties.4- Destructor Working.5- Garbage Collector. Definition. Steps of Working. Declaring.

    1-General Introduction: Every object created uses various system resources like

    the memory which are reserved for the object's useuntil they are explicitly released.

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    35/77

    If all references to object that manage the resources arelost before the resource is explicitly released, theapplication can no longer access the resources torelease it and this called {memory leak}.

    Dot Net Framework Common Library [FCL], hadproduced a way to give back the resources to thesystem when they are no longer needed.

    Common Language Runtime [CLR] performs automaticmemory management by using the "Garbage Collector",to reclaim the memory occupied by the objects that areno longer in use so, memory can be used for otherobjects.

    When there are no more references to an object, itbecomes eligible for destruction.

    Every object has a special member called "Destructor",which is invoked by the garbage collector to performtermination housekeeping on an object, just before thegarbage collector reclaims the object's memory.

    After the garbage collector calls the object's destructor,the object becomes eligible for garbage collector.

    The memory for such an object can be reclaimed by thegarbage collector.

    2- Definition:

    Is a special method like any method, and we can able toignore it and didn't write it in the class, because the CLR willbe automatically did a management for the memory, andreclaim the unreferenced objects .

    2-Properties:The destructor has the following properties, which distinguishit from other methods:1- Has the same name as the class.

    2- Doesn't return any value.3- Called automatically when the object is destroyed.4- Can not be defined in the struct.5- The class can only have one destructor.6- It can not be inherited or overloaded.7- It can not be called, because it is invoked by the garbagecollector.8- It is called when the program exits.9- It doesn't take any access modifier.10- It doesn't take any parameters.

    11- It is denoted by the sign (~) and pronounces "tiled".

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    36/77

    Simple Example:using System;using System.Collections.Generic;using System.Linq;using System.Text;

    namespace Destructor{

    //initiate a class

    classSampleClass{

    //define the fields

    privateint x = 4;//destructor~SampleClass(){

    Console.WriteLine("\n\tthe value of x is: {0}",x);}

    }//end MyBook class//initiate another class that inherit from the first classclassProgram{

    staticvoid Main()

    {//creating object from the classSampleClass mysampleclass = newSampleClass();

    //using the garbage collector to invoke the destructor

    GC.Collect();//print dataConsole.WriteLine("\n\n");

    }}

    }The Output of this example will be as the following:

    After printing the value of the instance variable x, it will destroy itsvalue from the memory.

    3-Destructor Working:The destructor implicitly calls the "finalize" method on theobjects base class, so the compiler understanding the code ofthe destructor as the following:protectedoverridevoid Finalize()

    {try//try block for first testing

    {//statements that you need to execute

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    37/77

    }finally//finally always execute its code in any case

    {base.Finalize();

    }}

    The finalize method allows an object to attempt to freeresources and perform other clean up operations before theobject is reclaimed by the garbage collector.

    4-Garbage Collector:1- Definition:

    Checks for objects that are no longer being used by theapplication.

    2- Steps of Working:The garbage collector working according to the following threesteps:

    Searches for managed objects that are referenced in themanaged code.

    Attempts to finalize objects that are not referenced. Frees objects that are no referenced and reclaim the

    memory.

    3- Declaring:We can oblige the garbage collector to work by using thebuild-in static class that called "GC" , and the method"Collect" as the following://using the garbage collector to invoke the destructor

    //oblige the garbage collector to workGC.Collect();

    -This way oblige the garbage collector of all generation, and itis the widely use.-We also can oblige the garbage collector to work with thesame class, but with using of another method which oblige itfor all generation from [0] through specific generation.-To have the garbage collector reclaim objects up to aspecified generation of objects, use the GC.Collect(Int32)

    The class The method

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    38/77

    method overload. When you specify the maximum generation,all objects are collected.

    //using the garbage collector to invoke the destructor//oblige the garbage collector to work

    GC.Collect(2,GCCollectionMode.Optimized);

    -Using GCCollectionMode.Optimized, to determine that, is thisan optimized time to reclaim the memory or not.

    Example:classProgram

    {staticvoid Main(){

    //creating object from the class

    //and the object will reserve a location in the memorySampleClass mysampleclass = newSampleClass();

    //when making the object is null//it will not be in use

    //but it still has the location in the memorymysampleclass = null;

    //oblige the garbage collector//to invoke the object destructor

    //to reclaim the memoryGC.Collect();

    }

    }

    -If the destructor writes to console any data, we must usethe following method with the garbage collector

    GC.WaitForPendingFinalizers();

    -This method will make the garbage collector wait until thedestructor finish its work completely, then reclaim the

    memory.

    7- Property:**Key Points:

    1- Introduction.2-Defintion.3-get Accessor.4-set Accessor.5-General Characteristics.

    The class The method

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    39/77

    1- Introduction:-We dont need to access an object's instance variables inorder to use them, but we can use the object's propertieswhich contian the get and the set accessors to retrieve andmodify the values of instance variables respectively.

    2-Definition:-It is about a special method, that used to affect the values ofthe instance variables in the class by using some specialaccessors as the following:get accessor for retrieve and return the values of the instance variables.set accessor for modify and write the values of the instance variables.-It can contain one of them as the following:get accessor only called read-only property.

    set accessor only

    called write-only property.-It can contain both accessors.-After declaring the property, we can use it as a variable.-A property is named with the capaitalized name of theinstance variable that it manipulate.

    3-get Accessor:-Begins with the identifier get, not capital.-Delimited by braces.-The body contains a return statement, because get accessoris used for retrieving and returning the value of the instancevariable.

    4- set Accessor:-Begins with the identifier set, not capital.-Delimited by braces.-The value is implicitly declared and initialized in it.-Can not contain a local variable in the body.-Doesn't return any value.-Usually makes an assignment for the instance variable byusing the keyword "value" which refere to any value that theuser will input from the console window, or any initialization inthe main body of the main class.

    4-General Characteristics: We can use property as if it is an instance variable. Properties of the class should also used the class's own

    methods to manipulate the classes private instancevariables.

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    40/77

    Accessing an instance variable via a property'saccessors creates more robust class, that is easier tomaipulate and less likely to malfunction.

    Example:using System;using System.Collections.Generic;using System.Linq;using System.Text;

    namespace ReadAndWriteProperty{

    classGradeBook{

    //define the fieldsprivatestring courseName;

    //property to get and set the course name

    publicstring CourseName{

    get//get accessor for retrieve the value{

    return courseName;//must contain return statement}

    set//set accessor for modify the value{

    courseName = value;//assignment the value of the instancevariable

    //the keyword "value" make the instance variable taking anyvalue that the

    //user will enter it on the console window}

    }}classProgram

    {staticvoid Main(string[] args){

    //allow to user to enter a valueConsole.Write("\tPlease Enter The Course Name:");

    //reading values from the console windowstring Name = Console.ReadLine();

    //create an object from the classGradeBook myGradeBook = newGradeBook();//passing the value that the user will enter it//to the property and immediately to the instance variable

    myGradeBook.CourseName = Name;//printing resultsConsole.WriteLine("\n\tInitial course name

    is:{0}\n",myGradeBook.CourseName);Console.WriteLine("\n\t\aWelcome to the grade book of : {0}",

    myGradeBook.CourseName);Console.WriteLine("\n\n");

    }}

    }

    The Output of this example will be as the following:

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    41/77

    -In the set Accessor we can ignore the keyword "value", andinitialize the instance variable by putting an explicit value, andany value the user will input it from the console window, thecompiler will ignore it, and print only the explicit value of theinstance variable as the following:

    Example:using System;using System.Collections.Generic;using System.Linq;using System.Text;

    namespace ReadOnlyProperty{

    classGradeBook{

    //define the fieldsprivatestring courseName;

    //property to get and set the course namepublicstring CourseName{

    get//get accessor for retrieve the value

    {return courseName;//must contain return statement

    }set//set accessor for modify the value{

    courseName = "C# fundamentals";//assignment the value of theinstance variable

    //the keyword "value" make the instance variable taking any value

    that the//user will enter it on the console window

    }}

    }classProgram

    {staticvoid Main(string[] args){

    //allow to user to enter a value

    Console.Write("\tPlease Enter The Course Name:");//reading values from the console window

    string Name = Console.ReadLine();//create an object from the class

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    42/77

    GradeBook myGradeBook = newGradeBook();//passing the value that the user will enter it

    //to the property and immediately to the instance variablemyGradeBook.CourseName = Name;

    //printing resultsConsole.WriteLine("\n\tInitial course name

    is:{0}\n",myGradeBook.CourseName);Console.WriteLine("\n\t\aWelcome to the grade book of : {0}",

    myGradeBook.CourseName);Console.WriteLine("\n\n");

    }}

    }

    The Output of this example will be as the following:

    -Read-Only property, we can use it to retrieve and return the valueof the instance variable in case of abandoning writing any value ofthe instance variable as the following:

    Example:using System;using System.Collections.Generic;using System.Linq;using System.Text;

    namespace ConsoleApplication1

    {classDemo{

    //define the fields

    internalint x = 3;internalint y = 4;

    //read only property

    publicint Multiple{

    //get accessor for reading only

    //the value of the instance variablesget{

    return x * y;}//end get accessor

    }//end property}classProgram

    {

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    43/77

    staticvoid Main(string[] args){

    //create an object from the classDemo myclass = newDemo();

    //print dataConsole.WriteLine("the multiple of {0}, and {1} is : {2}",myclass.x,

    myclass.y, myclass.Multiple);}

    }}

    The Output of this example will be as the following:

    -Also we can use the property to override the value of the instancevariable as the following:

    Example:using System;

    using System.Collections.Generic;

    using System.Linq;using System.Text;

    namespace OverrideInstanceVariableValue{

    classDemo{

    //define the fieldsprivateint x = 3;

    //using property

    publicint X{

    //get accessor for reading//the value of the instance variableget{

    return x;

    }//end get accessor//set accessor for modifying//the value of the instance variableset{

    x = value;//assignment the value of the instance variable//the keyword "value" make the instance variable taking any

    value that the//user will enter it on the console window

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    44/77

    }//end set accessor}//end property

    }classProgram{

    staticvoid Main(string[] args)

    {//create an object from the classDemo myclass = newDemo();

    //print data

    Console.WriteLine("\n\tthe value of instance variable is : {0}",myclass.X);

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

    myclass.X = 10;Console.WriteLine("\n\tthe new value of instance variable is :

    {0}", myclass.X);Console.WriteLine("\n\n");

    }

    }}

    The Output of this example will be as the following:

    -We can put a statement inside each of the get and setaccessors to print it as the following:

    Example:using System;using System.Collections.Generic;

    using System.Linq;using System.Text;

    namespace GetAndSetAccessorsStatements

    {classDemo{

    //define the fieldsprivateint x = 3;

    //using propertypublicint X

    {//get accessor for reading//the value of the instance variable

    get{

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    45/77

    Console.WriteLine("\n\treturn the value of the instancevariable");

    return x;}//end get accessor

    //set accessor for modifying//the value of the instance variable

    set{

    x = value;Console.WriteLine("\tset the value of the instance variable");

    //assignment the value of the instance variable//the keyword "value" make the instance variable taking any

    value that the

    //user will enter it on the console window}//end set accessor

    }//end property}

    classProgram

    {staticvoid Main(string[] args)

    {//create an object from the classDemo myclass = newDemo();

    //print data

    Console.WriteLine("\n\tthe value of instance variable is : {0}",myclass.X);

    Console.WriteLine("\n\n");myclass.X = 10;

    Console.WriteLine("\n\tthe new value of instance variable is :{0}", myclass.X);

    Console.WriteLine("\n\n");}

    }}

    The Output of this example will be as the following:

    8- Instance and Static:

    **Key Points:1- Instance Members.

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    46/77

    Definition. Declaration. Accessing.

    2-Static Members. Defintion. Declaration. Accessing. Features. When Will We Use It? Benefits. General Example.

    1- Instance Members:*Definition:

    -It it the default for members in any class-Also for the classes itself.

    *Declaration:-If we declare any member in the class without usingthe keyword "static", it is considered instance.

    privateint x;

    -This is instance field{variable}.-Also like the following instance method.

    publicint Summation(int x, int y){

    int s;return x = x + y;

    }

    *Accessing:

    -In accessing the instance members, we must take careof the access modifier of this member to be able toaccess it see the access modifier.-The public instance members can be accessed anywhere by using the object of the class that containthese members and the (.) dot operator.-The private instance members can be accessed anywhere by using the special methods in the class thatcontain these members like the set(), and get()methods with the object of this class.

    -The protected instance members can be accessed anywhere by using the inheritance of the class that contain

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    47/77

    these members to the class that the access operationwill occur in.-The internal instance members can be accessed anywhere by using the object of the class that containthese members and the (.) dot operator.

    -when the use of the class that contains instancemembers is terminated, the value of the local variable islost.-See any previous example.

    2-Static Members:*Definition:

    -All objects of the static members share the same pieceof data.

    -Also for the classes itself.

    *Declaration:-By using the keyword "static" before the return type ofthe member and after the access modifier of it.

    privatestaticint x;-This is a static variable.-Also like the following static method

    staticvoid Main(string[] args){

    Console.WriteLine("Welcome to C#.Net");}

    *Accessing:-Public static members can be accessed any where byusing the name of the class that contain the staticmembers, and the (.) operator, then the name of themember that you need to access it.-Private static members can be accessed any whereonly by using some public static special methods likeget(), and set() methods, and properties of the class.-they are availabe as soon as the class is loaded intothe memory at the execution time.

    Example:-the most common example is the "Math" Class.-Math Class is a static class, with a great collection of

    static methods of the mathematical operation about

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    48/77

    twentynine [29] static methods, and two [2] constantvalues.Examples:using System;using System.Collections.Generic;

    using System.Linq;using System.Text;

    namespace ConsoleApplication1{

    classProgram{

    constint x = 0;staticvoid Main(string[] args)

    {//define fieldsdouble a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u,

    v, w, x;//using Absolute method//returns the absolute valuea = Math.Abs(23.7);

    b = Math.Abs(-23.7);//using Ceiling method//returns the value to the smallest integer not less than

    the input value

    c = Math.Ceiling(9.2);d = Math.Ceiling(-9.8);

    //using Cos method

    //return the trigonomertric cosine of the value in radianse = Math.Cos(0.0);f = Math.Cos(90.0);

    //using Exponential method

    //returns the exponential of the value e^valueg = Math.Exp(1.0);h = Math.Exp(2.0);

    //using Floor method//returns the value of the largest integer not greater than

    the input valuei = Math.Floor(9.2);

    j = Math.Floor(-9.8);//using log method//returns the natural logarithm of the value and base is e

    k = Math.Log(Math.E);l = Math.Log(Math.E * Math.E);

    //using max method//returns the maximum value of two values

    m = Math.Max(2.3, 12.7);n = Math.Max(-2.3, -12.7);

    //using min method//returns the minimum value of two values

    o = Math.Min(2.3, 12.7);p = Math.Min(-2.3, -12.7);

    //using power method//returns the first value raised to the power of the second

    valueq = Math.Pow(2.0, 7.0);

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    49/77

    r = Math.Pow(9.0, 0.5);//using sin method

    //returns the trigonometric sine of the value in radianss = Math.Sin(0.0);t = Math.Sin(90.0);

    //using square root method

    //returns the square root of the valueu = Math.Sqrt(900.0);v = Math.Sqrt(64.0);

    //using tan method

    //returns the trigonometric tangent of the value in radiansw = Math.Tan(0.0);x = Math.Tan(45.0);

    Console.WriteLine("\n\tthe absolute method, the absolutevalue of {0}, is : {1}", 23.7, a);

    Console.WriteLine("\tthe absolute method, the absolutevalue of {0}, is : {1}", -23.7, b);

    Console.WriteLine("\tthe ceiling method, the ceiling value

    of {0}, is : {1}", 9.2, c);Console.WriteLine("\tthe ceiling method, the ceiling value

    of {0}, is : {1}", -9.8, d);Console.WriteLine("\tthe cosine method, the cosien value

    of {0}, is : {1}", 0.0, e);Console.WriteLine("\tthe cosine method, the cosien value

    of {0}, is : {1}", 90.0, f);Console.WriteLine("\tthe exponential method, the

    exponential value of {0}, is : {1}", 1.0, g);Console.WriteLine("\tthe exponential method, the

    exponential value of {0}, is : {1}", 2.0, h);Console.WriteLine("\tthe floor method, the floor value of

    {0}, is : {1}", 9.2, i);Console.WriteLine("\tthe floor method, the floor value of

    {0}, is : {1}", -9.8, j);Console.WriteLine("\tthe log method, the log value of {0},

    is : {1}", Math.E, k);

    Console.WriteLine("\tthe log method, the log value of {0},is : {1}", Math.E, l);

    Console.WriteLine("\tthe max method, the max value of

    {0}, and the value of {1}, is : {2}", 2.3, 12.7, m);Console.WriteLine("\tthe max method, the max value of

    {0}, and the value of {1}, is : {2}", -2.3, -12.7, n);Console.WriteLine("\tthe min method, the min value of

    {0}, and the value of {1}, is : {2}", 2.3, 12.7, o);Console.WriteLine("\tthe min method, the min value of{0}, and the value of {1}, is : {2}", -2.3, -12.7, p);

    Console.WriteLine("\tthe power method, the power value

    of {0}, and the value of {1}, is : {2}", 2.0, 7.0, q);Console.WriteLine("\tthe power method, the power value

    of {0}, and the value of {1}, is : {2}", 2.0, 7.0, r);

    Console.WriteLine("\tthe sine method, the sine value of{0}, is : {1}", 0.0, s);

    Console.WriteLine("\tthe sine method, the sine value of{0}, is : {1}", 90.0, t);

    Console.WriteLine("\tthe square root method, the squareroot value of {0}, is : {1}", 900, u);

    Console.WriteLine("\tthe square root method, the square

    root value of {0}, is : {1}", 64.0, v);

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    50/77

    Console.WriteLine("\tthe tangent method, the tangentvalue of {0}, is : {1}", 0.0, w);

    Console.WriteLine("\tthe tangent method, the tangentvalue of {0}, is : {1}", 45.0, x);

    }

    }}

    The Output of this example will be as the following:

    -The "math" method only deals with double values.

    *Features:

    only contain static members. can not be instantiated. can not be inherited, because they are sealed. only contain static constructor.

    *When Will We Use It?-We use the static classes or members when themembers in the class didn't need to a specific instanceof the class.-We create static members in the class when no objectof the class exist.

    *Benefits:-Static members in static classes can make the programor the application implementation simpler and faster,because they didn't need to create an object to call itsmembers.

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    51/77

    *General Example:-Let us have a game that worriors conquer the enemy.-The warrior can conquer the enemy if thetj are at least fourwarriors, else they will be coward.-From this, each warrior must know its count so, we will add avariable called WarriorCount.-If we declared it as instance variable as the following:

    int WarriorCount = 0;

    -Each warrior will have its separate copy of the instancevariable, and every time we add new warrior, we will have toupdate the instance variable.

    -This will waste time in updating the separate copy and will beerror prone.-If we declared it as static variable as the following:

    staticint WarriorCount = 0;

    -This will make all warriors chare the variable, and each onecan access the variable as if it is an instance variable, but infact, only one copy of the static variable is maintained.

    9-General Examples:Example:1using System;using System.Collections.Generic;using System.Linq;using System.Text;

    namespace EmployeeConstructorAndDestructor{

    classEmployee{

    //define the fieldsprivatestring firstName;

    privatestring lastName;privatestaticint count = 0;

    //constructorpublic Employee(string fname, string lname){

    //assignment for the instance variablesfirstName = fname;

    lastName = lname;//increment the counter of the employeescount++;

    //print the names of the employees and there count

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    52/77

    Console.WriteLine("\n\temployee construction {0}, {1}; count ={2}", firstName, lastName, count);

    }//destrcuctor~Employee(){

    //decrement the counter of the employeescount--;

    //print the names of the employees and there countConsole.WriteLine("\n\temployees destruction {0}, {1}; count =

    {2}", firstName, lastName, count);}

    //read only property

    publicstring FirstName{

    get{

    //return the first name of the employees

    return firstName;}//end get

    }//end property//read only propertypublicstring LastName{

    get{

    //return the last name of the employeesreturn lastName;

    }//end get}//end property

    //read only propertypublicstaticint Count{

    get{

    //return the counter of the employeesreturn count;

    }//end get

    }//end property}//end classclassProgram{

    staticvoid Main(string[] args){//print initial value of emlpoyee before constructionConsole.WriteLine("\n\temployee before instantiation: {0}",

    Employee.Count);//passing values to the constructor//passing first name, and the second name of two employees

    Employee emp1 = newEmployee("Harvey", "M. Deitel");Employee emp2 = newEmployee("Paul", "j. Deitel");

    //print the number of the employees after passing valuesConsole.WriteLine("\n\temployees after instantiation is : {0}",

    Employee.Count);//print the name of the employees

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    53/77

    Console.WriteLine("\n\temployee1 is : {0} {1},\n\n\temployee2 is: {2} {3}", emp1.FirstName, emp1.LastName, emp2.FirstName,

    emp2.LastName);//making objects null//objects are no longer needed//objects are no longer in use

    //objects are eligible for destrcutionemp1 = null;emp2 = null;

    //oblige the garbage collector

    //that invoke the destructor//and execute it, then reclaim the memoryGC.Collect();

    //wait until the destrutor finish its executionGC.WaitForPendingFinalizers();

    //print the number of the employees after the destruction of theobjects

    Console.WriteLine("\n\temployees after destruction : {0}",

    Employee.Count);Console.WriteLine("\n\n");

    }}

    }

    The Output of this example will be as the following:

    Example:2using System;using System.Collections.Generic;using System.Linq;using System.Text;

    namespace TwoClasses{

    //initiate the first classclassCommissionEmployee{

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    54/77

    //define the fieldsprivatestring firstName;

    privatestring lastName;privatestring socialSecurityNumber;privatedecimal grossSales;privatedecimal commissionRate;

    //the default constructorpublic CommissionEmployee(){}//end default constructor

    //the overloaded constructorpublic CommissionEmployee(string fname, string lname, string ssn,

    decimal sale, decimal rate)

    {//assignment for the instance variablesfirstName = fname;lastName = lname;

    socialSecurityNumber = ssn;

    grossSales = sale;commissionRate = rate;

    }//end overloaded constructor//read-only propertypublicstring FirstName{

    get{

    //return the first name of the employeereturn firstName;

    }//end get accessor}//end property

    //read-only properypublicstring LastName{

    get{

    //return the second name of the employeereturn lastName;

    }//end get accessor

    }//end property//read-only propertypublicstring SocialSecurityNumber{

    get{//return the social security number of the employeereturn socialSecurityNumber;

    }//end get accessor}//end property

    //read and write property

    publicdecimal GrossSales{

    get{

    //return the gross sales of the employeereturn grossSales;

    }//end get accessor

    set

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    55/77

    {//put the condition on the value of the gross sales

    //gross sales will take its value from the user input in the mainclass

    grossSales = (value < 0) ? 0 : value;}//end set accessor

    }//end property//read and write propertypublicdecimal CommissionRate{

    get{

    //return the commission rate of the employee

    return commissionRate;}//end get accessorset{

    //put the condition on the value of the commission rate

    //commission rate will take its value from the user input in themain class

    commissionRate = (value > 0 &&value < 1) ? value : 0;}//end set accessor

    }//end property//define a method that return the earning of the employee

    publicdecimal Earning(){

    return commissionRate * grossSales;}//end method

    }//inititate the second classclassBasePlusCommissionEmployee

    {//define the fieldsprivatestring firstName;privatestring lastName;privatestring socialSecurityNumber;

    privatedecimal grossSales;privatedecimal commissionRate;privatedecimal baseSalary;

    //the default constructorpublic BasePlusCommissionEmployee(){}//end default constructor

    //the overloaded constructorpublic BasePlusCommissionEmployee(string fname, string lname,string ssn, decimal sale, decimal rate, decimal salary)

    {

    //assignment for the instance variablesfirstName = fname;lastName = lname;

    socialSecurityNumber = ssn;grossSales = sale;commissionRate = rate;baseSalary = salary;

    }//end default constructor//read-only propertypublicstring FirstName

    {

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    56/77

    get{

    //return the first name of the employeereturn firstName;

    }//end get accessor}//end property

    //read-only properypublicstring LastName{

    get

    {//return the second name of the employeereturn lastName;

    }//end get accessor}//end property

    //read-only propertypublicstring SocialSecurityNumber

    {

    get{

    //return the social security number of the employeereturn socialSecurityNumber;

    }//end get accessor}//end property

    //read and write propertypublicdecimal GrossSales{

    get

    {//return the gross sales of the employee

    return grossSales;}//end get accessorset{

    //put the condition on the value of the gross sales

    //gross sales will take its value from the user input in the mainclass

    grossSales = (value < 0) ? 0 : value;

    }//end set accessor}//end property

    //read and write propertypublicdecimal CommissionRate

    { get{

    //return the commission rate of the employee

    return commissionRate;}//end get accessorset

    {//put the condition on the value of the commission rate//commission rate will take its value from the user input in the

    main class

    commissionRate = (value > 0 &&value < 1) ? value : 0;}//end set accessor

    }//end property

    //read and write property

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    57/77

    publicdecimal BaseSalary{

    get{

    //return the base salary of the employeereturn baseSalary;

    }//end get accessorset{

    //put the condition on the value of the base salary

    //base salary will take its value from the user input in the mainclass

    baseSalary = (value < 0) ? 0 : value;

    }//end set accessor}//end property

    //define a method that return the earning of the employeepublicdecimal Earning()

    {

    return baseSalary + (commissionRate * grossSales);}//end method

    }classProgram{

    staticvoid Main(string[] args)

    {//declaring fields according to the first class CommissionEmployeestring firstname, lastname, socialnumber;decimal grosssales, commissionrate, basesalary;

    Console.WriteLine("\n\tfor the first class which isCommissionEmployee.");

    Console.Write("\n\tFirst Name: ");firstname = Console.ReadLine();Console.Write("\n\tLast Name: ");lastname = Console.ReadLine();Console.Write("\n\tSocial Security Number: ");

    socialnumber = Console.ReadLine();Console.Write("\n\tGross Sales: ");grosssales = decimal.Parse(Console.ReadLine());

    Console.Write("\n\tCommission Rate: ");commissionrate = decimal.Parse(Console.ReadLine());Console.WriteLine("\n\n");CommissionEmployee emp = new

    CommissionEmployee(firstname,lastname,socialnumber,grosssales,commissionrate);Console.WriteLine("\a\tfirst name is : {0},\n\n\tlast name is :

    {1},\n\n\tsocial security number is : {2},\n\n\tgross sales are :

    {3:C},\n\n\tthe commission rate is : {4:C},\n\n\tthe earnings are :{5:C}", emp.FirstName, emp.LastName, emp.SocialSecurityNumber,emp.GrossSales, emp.CommissionRate, emp.Earning());

    Console.WriteLine("\n\n");Console.WriteLine("\n\tfor the second class which is

    BasePlusCommissionEmployee.");Console.Write("\n\tBase Salary: ");

    basesalary = decimal.Parse(Console.ReadLine());Console.WriteLine("\n\n");

    //creating object from the class

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    58/77

    BasePlusCommissionEmployee baseEmp = newBasePlusCommissionEmployee(firstname, lastname, socialnumber,

    grosssales, commissionrate, basesalary);Console.WriteLine("\a\tfirst name is : {0},\n\n\tlast name is :

    {1},\n\n\tsocial security number is : {2},\n\n\tgross sales are :{3:C},\n\n\tthe commission rate is : {4:C},\n\n\tthe earnings are :

    {5:C},\n\n\tthe base salary is : {6:C}", baseEmp.FirstName,baseEmp.LastName, baseEmp.SocialSecurityNumber, baseEmp.GrossSales,baseEmp.CommissionRate, baseEmp.Earning(),baseEmp.BaseSalary);

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

    }}

    }The Output of this example will be as the following:

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    59/77

    10- Inheritance:

    **Key Points:1-General Introduction.2-Definition.3-Declaration.4-Overriding Methods.5-Types.6- Is-a and Has-a Relations.7-Properties.8- Importance.9-Disadvantages.10- Examples.

    1-General Introduction: When we create a new class, it can be based on

    another class.like vehicle, which can be cars, planes, bicycle,trucks,from this we can find that,cars based on vehicles.

    planes based on vehicles. Inheritance is created to avoid the code redundancy

    by way of inheriting all of one class members, inanother class, that use all members in the otherclass and can add new members in it.

    As an example, like humanThere are men and womenEach man has its own attributes like woman as:name, age, weight, length, shape, hair colorAnd both can share some attributes like:

    Each of them has two eyes, two ears, one nose, onemouth, two hands, two legs, hair

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    60/77

    From this we can do the followingMake a large class called humanIn which all shared attributes among men andwomen.Then make a two small specified classes

    Class for menin which all specific attributes in men.Class for womenIn which all specific attributes inwomen.The two small classes[men, and women] will inheritthe shared attributes from the large class[human].

    From this we can find that, the inheritance avoid usfrom repeating the code in both two small classes, inthe same time both of them have these sharedattributes, but without declaring any sharedattributes in both, just by inheritance.

    2-Definition:Inheritance is a form{shape, way, or type} of code resue,in which the new class is created by absorbing an existingclasss members and enhancing them with a new modifiedcapabilities.The inheritance is denoted by the arrow, with closedarrowhead, like thisAn illustration data gram for both the base class, and the

    new class which called the child or derived class.

    *Illustration Example:Usually we have to fall back upon the inheritance, when wefind a shared data among two classes, we take this shared

    data and isulate it in one class, in a manner that all otherclasses that need this shared data can inherit it.

    Called

    Derived Class,SubClass, orChild Class

    Supply Membersto other classes toinherit from it.

    More Specifiedthan its baseclass.

    Based Class,Super, or

    Parent Class

    Existing class.From YourCreation, or

    Build-In Class

    New class,inherit fromanother class

    Called

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    61/77

    Example:We all know the difference between the Expert, and TheEmployeeExpertpaid by hour, and more efficient.Employeepaid by salary, and sufficient efficient.

    Suppose that, we have two classes [Expert, Employee],and there are some fields in these two classes as thefollowing illustration:

    Expert Class Employee Class

    As we see, both classes share data, and there are somedifferent data also, if we make the two classes as this, itwill generate for us a great redundancy in the code, andthe program will be very large, also can not be elegant.So, we will isolate the shared data alone in one class[Person], then let the different data in both classes as it.Finnally, we make the two classes inherit from the baseclass that include the shared data.By this way, we will avoid the code redundancy, and theprogram will be more robust and elegant.

    Expert Class Employee Class

    ExpertNameAddressPhoneIDHourRentHourWorked

    mployeeENameAddressPhoneIDSalaryDaysWorked

    ExpertHourRentHourWorked

    mployeeESalary

    DaysWorked

    PersonNameAddressPhoneID

    Subclass,Child, orDerived Class

    Superclass,Parent, or BaseClass

    Subclass,Child, or

    Derived Class

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    62/77

    3- Declaration: To make a class inherit from another class, we use

    the sign (:) that pronounces colon. Type the derived class befor the sign, and the base

    class after it.

    Example:

    public class DeriverdClass : BaseClass

    -As this example of the vehicle:

    public class MyCar : Vehicle

    -We use the keyword base to call any thing insidethe base class like constructors, methods,-the base keyword is a hidden pointer, that holdsthe address of the current object being used.-If we need the derived class to have a differentimplementation for the base class methods, we must

    write the method in the derived class that overridesthe base class methods.

    4- Overriding Method:

    We can create a method with in the sameargements list as a method in the base class.

    The new methd is said to override the base classmethod.

    The derived class will use the new method ratherthan the method in the base class.

    *How to override a method? Declare the original method in the base class after

    the access modifier with any of the following twokeyword:virtual:before the method that has a code.abstract:before the method that has no code.override:if we need to override it in the baseclass not in the derived class.

    Declare the new method in the derived class withthe keyowrd overrideExample:

    Access

    Modifier

    Keyword

    class

    The DerivedClass, thatneeds toinherit

    Superclass,Parent, or BaseClass

    Thecolonsign (:)

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    63/77

    In the base class:privatevirtualdecimal ExtendedPrice()

    {//any code to execute

    }

    In the derived class:protectedoverridedecimal ExtendedPrice(){

    //any code to execute}

    When we use the keyword virtualbefore anymethod in the base class, we have two options inthe derived class according to this method use:Option1:use the original method as it.Option2:override it and supply a new code.

    When we use the keyword abstract in the baseclass method that has no any code, in the derivedclass we must provide its own code.

    The class that has any method with declaration ofthe keyword abstract, it will be consideredabstract class which only can be used forinheritance.

    We can not instantiate objects from a class thatcontains abstract method.

    5-Types:We have two types of inheritance of the classes1- Direct Inheritance:

    The derived class inherit explicitly from the base class,and there are no any classes between them.

    2- Indirect Inheritance:The derived class inherit from a class that inheirt from aclass that inherit from the base class, and there is noany explicitly inheritance between this derived class andthe base class.

    6- Is-a and Has-a Relations

    1- Is-a Relation: It is representing the inheritance relationship.

    Like:Car is a Vehicle.

    Object of the derived class can be treated asobject of its base class.

    Like:

  • 8/6/2019 Object Oriented Programming With C Sharp Code Implementation

    64/77

    Car is an object from the derived class, and in the sametime it is an object from the base class Vehicle.

    2- Has-a Relation: It is representing the composition relationship.

    Like:Car has a steering wheel.

    Object contains as member reference to otherobject.

    Like:Car object ha