Você está na página 1de 77

In The Name of Allah, the most Gracious, the most Merciful Object-Oriented Programming Course *Contents of the course:

1-Objects The important topics in our course are 2-Classes 3-Methods Objects, Classes, Methods, and Arrays 4-Arrays 5-Encapsulation 6-PolymorPhism 7-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 easy determine any exceptions.

*General Example about Object-Oriented Programming: -If we look to the real life, we will find that, it contains a lot of things surround us like cars, humans, bridges, buildings, birds -If we need to store some information about each category of these things like Car- model, size, length, speed Human- name, length, weight, gender Bridges- location, length, height, strength And so on. -This will generate for us a great amount of data in the Main Method in 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 an application 1-We will make each category {cars, humans, bridges, buildings, birds} as a class that contain the records and tasks that each category has like Car- acceleration, break, steering wheel, horn tool Human- moving, seeing, eating, writing, reading, sleeping And so on. -All of these tasks will be recorded inside the class and will be special only for each category. 2-After that, we can easily access the code, maintain it, correct any exceptions, and reuse it.

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

*Illustration Example of OOP We can use the car as an illustration example to discover and understand the basics of classes, objects, methods, calling methods, properties, and instance variables The Car in Real Life 1-Before using the car, it must have an engineering drawing and design which include a design for every thing in the car. 2-The design of the car including a design for the following tools: -Accelerator Pedal which makes the car goes faster. which slows -Break Pedal down the car. -Steering Wheel which turn the car in all directions. -Gear that change the speed of the car. which warn others. -Horn All of these tools perform a task in the car (complex) and describe the mechanism that actually performs its task which always is hidden. 3-To use the car, the man must build it first, and make it complete with all tasks and things to perform it. Like if the driver needs to accelerate the car, he must press on a small tool called the accelerator to make the car goes faster. 4-If the driver needs to accelerate the car, he must press on a small tool called the accelerator to make the car goes faster, which sends a message to the car to perform a task that In Object-Oriented Programming 1-Any program must begin by creating a class. Car engineering designs in real life == the classes in ObjectOriented Programming. 2-All of these tools and tasks in the car can convert in the Object-Oriented Programming into Methods. The methods in the class are usually performing a task in the application, and they hide the complex task. Look like the car, it can contain more than one task also the class may contain more than one method that are created to perform tasks in the class. Car's tasks in the real life == classes' methods.

3-We can not able to use any thing inside a class until we make an object of it. The object is a reference based on the class and some times called an instance of the class. Each object has two things, Those are status, and the behavior. 4-To use a specific task in the class like Methods, we must call this Method by the object {instance method} to perform the specific task that we need. Accelerating the car in the real

can make the car faster. 5-Each car has attributes, like color, length, speed, model, size, weight, tank size, total miles driven, no of doors, shape, no of tires and its shape. Each car has its own attributes that may be difference or similar to another car. 6-The manufacturer doesn't want the drivers to take a part with the car's engine to observe the amount of gas in the tank, instead, the driver can check the meters and tank state on the dashboard.

life==calling the methods. 5-The attributes are specified as a part of the object and they are the classes' instance variables and some times called fields. Attributes are not necessarily accessible directly.

6-We don't need to have an access to an object's instance variables in order to use them, but we can use the property of the object which consists of get and set accesses for reading (retrieve) and write (modify) values of the object's instance variables respectively.

*First: OOP Objects **Key Points: 1- Definition. 2- Creating. 3- Properties. 1-Object Definition: -Is a reference based on the class and some times called "Instance of the Class". -Has status, and behavior like that Object status Fields, and Properties. Object behavior Methods Example: Like the computer Has behavior that, it is switched on, or switched off

The computer
Has status that, it is now switching on, or it is now switching off

2-Object Creation: We can create our object by using the keyword "new" and the class name like the following conception: Classname Objectname=new Classname (); Example: Let us have a class with the name Student and need to use its members so; we create an object of it as the following: Student GetStudentData=new Student ();

The class name

The name of the object

The keyword new, some times called operator new

The constructor of the class [default constructor]

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 specific task. -They have properties and characteristics to obtain data and change the information that contain. -They often used to access only the public instance members, not applied for the static members.

*Second: OOP Classes **Key Points: 1- Definition. 2- Creating. 3- Access Modifiers. 4- Access Methods. 5- Constructors. 6- Destructors. 7- Property. 8- Instance and Static. 9- General Examples 10- Inheritance. 1- Class Definition: -The class is a container of data and methods that will operate and use it.

-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 the following 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 public class ArithmeticOperations { //define fields private int x, y; //default constructor public ArithmeticOperations() { }//end default constructor //summation method public int 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 to input 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 in all the program because there is no any restrictions on it. -To Access it, we use the object + the dot operator (.) Example:
using using using using System; System.Collections.Generic; System.Linq; System.Text;

namespace AccessingPublicMembers { //initiate the class class SampleClass { public int x; //define public field //add any statements to complete the class }//end class //initiate another class class Program { //define the main method static void Main(string[] args) { //create object from the first class //to enable us to access field in it SampleClass myobject = new SampleClass(); //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 be accessed by using some special public methods like get and set for 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 is encapsulated in the object, and can be accessed by methods and properties of the class. Example:
using using using using System; System.Collections.Generic; System.Linq; System.Text;

namespace AccessingPrivateMembers { //initiate the class class MyCar

{ //define private fields private string myCarColor; private decimal myCarLength; //define special public method to access the private fields //define the set method for modifying values of the first field public void SetMyCarColor(string color) { myCarColor = color; }//end first set method //define the set method for modifying vallues of the second field public void SetMyCarLength(decimal length) { myCarLength = length; }//end second set method //define the get method for retrieving values of the first field public string GetMyCarColor() { return myCarColor; }//end first get method //define the get method for retrieving values of the second field public decimal GetMyCarLength() { return myCarLength; } }//end class //initiate another class class Program { //define the main method static void Main(string[] args) { //create object from the first class //to enable us to access fields in it MyCar car = new MyCar(); //using object to access the private fields car.SetMyCarColor("Black"); car.SetMyCarLength(250.35m); //print data Console.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:

-When we use the object of the MyCar class which is car to access the 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 the following: Here we will find all methods that we declared it as public in the MyCar class like: GetMyCarColor(), GetMyCarLngth(), SetMyCarColor(), SetMyCarLength(), And we use set methods only. -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 with all methods in the first class that you need to access as the following: Here we will find all methods that we declared it as public in the MyCar class like: GetMyCarColor(), GetMyCarLngth(), SetMyCarColor(), SetMyCarLength(); And we use get methods only.

(3-) Protected Access Modifier: -The member can be used in the same class of in the derived class by using inheritance. Example: If we need to make an object from the inherited class not from the base class
using using using using System; System.Collections.Generic; System.Linq; System.Text;

namespace AccessingProtectedMembers { //initiate the class class Employee { //define protected fields protected string firstName; protected string secondName;

protected int myAge; }//end class //initiate another class class Program:Employee { //define the main method static void Main(string[] args) { //using object to access the protected fields //object form the inherited class Program prog=new Program(); prog.firstName="Joseph"; prog.secondName="Gradecki"; prog.myAge=45; //print data Console.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 dot operator (.), we will find a small menu called intellisense will appear to you with all protected fields in the first class that you need to access as the following:

Here we will find all protected fields that we declared it in the Employee class like: firstName; myAge; secondName;

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

namespace AccessingProtectedMembers { //initiate the class class Employee { //define protected fields protected string firstName; protected string secondName; protected int myAge; //define special public method to access the protected fields //define the set method for modifying values of the first field public void SetFirstName(string fname) { firstName = fname; }//end first set method //define the set method for modifying vallues of the second field public void SetSecondName(string sname) { secondName = sname; }//end second set method //define the set method for modifying vallues of the third field public void SetMyAge(int age) { myAge = age; }//end third set method //define the get method for retrieving values of the first field public string GetFirstName() { return firstName; }//end first get method //define the get method for retrieving values of the second field public string GetSecondName() { return secondName; }//end second get method //define the get method for retrieving values of the third field public int GetMyAge() { return myAge; }//end third get method }//end class //initiate another class class Program : Employee //inheritance { //define the main method static void Main(string[] args) { //using object to access the protected fields //object form the base class Employee emp = new Employee(); 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:

And as I said before if we followed this way by creating object from the base class Employee 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 class class Employee { //define protected fields protected string firstName; protected string secondName; protected int myAge; //define special public method to access the protected fields //define the set method for modifying values of the first field public void SetFirstName(string fname) { firstName = fname; }//end first set method //define the set method for modifying vallues of the second field public void SetSecondName(string sname) { secondName = sname; }//end second set method //define the set method for modifying vallues of the third field public void SetMyAge(int age) { myAge = age; }//end third set method //define the get method for retrieving values of the first field public string GetFirstName() { return firstName; }//end first get method

//define the get method for retrieving values of the second field public string GetSecondName() { return secondName; }//end second get method //define the get method for retrieving values of the third field public int GetMyAge() { return myAge; }//end third get method }//end class //initiate another class class Program //no inheritance { //define the main method static void Main(string[] args) { //using object to access the protected fields //object form the base class Employee emp = new Employee(); 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 dot operator (.), we will find a small menu called intellisense will appear to you with all public methods in the first class Employee that you need to access as the following:

Here we will find all public methods that we declared it in the Employee class like: SetFirstName(); SetMyAge(); SetSecondName(); And we here use the set methods only

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

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

(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 same Assembley. -Within the same class it is equivalent to public access modifier, but can not be used in making .dll files. -All members in the internal class can be used in any place in the same program, but not to code in another programs or assemblies. -Some people use the keyword "static" after writing the internal access modifier and 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;

using System.Text; namespace AccessingInternalMembers { //initiate the class class SampleClass { internal int x; //define internal field //add any statements to complete the class }//end class //initiate another class class Program { //define the main method static void Main(string[] args) { //create object from the first class //to enable us to access field in it SampleClass myobject = new SampleClass(); //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 public access modifier. -When we type the name of the object myObject and use the dot operator (.), we will find a small menu called intellisense will appear to you with all public methods in the first class Employee that you need to access as the following: Here we will find all internal fields that we declared it in the SampleClass class like: The field x, And we here use it directly

(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:

using using using using

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

namespace AccessingProtectedInternalMembers { //initiate the class class Employee { //define protected fields protected internal string firstName; protected internal string secondName; protected internal int myAge; //define special public method to access the protected internal fields //define the set method for modifying values of the first field public void SetFirstName(string fname) { firstName = fname; }//end first set method //define the set method for modifying vallues of the second field public void SetSecondName(string sname) { secondName = sname; }//end second set method //define the set method for modifying vallues of the third field public void SetMyAge(int age) { myAge = age; }//end third set method //define the get method for retrieving values of the first field public string GetFirstName() { return firstName; }//end first get method //define the get method for retrieving values of the second field public string GetSecondName() { return secondName; }//end second get method //define the get method for retrieving values of the third field public int GetMyAge() { return myAge; }//end third get method }//end class //initiate another class class Program //no inheritance { //define the main method static void Main(string[] args) { //using object to access the protected internal fields //object form the first class Employee emp = new Employee(); emp.SetFirstName("Harvey"); emp.SetSecondName("Deitel");

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 using the set or get methods, and this will be done by using the object directly to access the protected internal fields as the following: Example:
using using using using System; System.Collections.Generic; System.Linq; System.Text;

namespace AccessingProtectedInternalMembers { //initiate the class class Employee { //define protected fields protected internal string firstName; protected internal string secondName; protected internal int myAge; }//end class //initiate another class class Program //no inheritance { //define the main method static void Main(string[] args) { //using object to access the protected fields //object form the first class Employee emp = new Employee(); emp.firstName = "Harvery"; emp.secondName = "Deitel"; emp.myAge = 55; //print data Console.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:

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

namespace AccessingProtectedInternalMembers { //initiate the class class Employee { //define protected fields protected internal string firstName; protected internal string secondName; protected internal int myAge; }//end class //initiate another class class Program:Employee { //define the main method static void Main(string[] args) { //using object to access the protected fields //object form the base class Employee emp = new Employee(); emp.firstName = "Harvey"; emp.secondName = "Deitel"; emp.myAge = 55; //print data Console.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:

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

namespace AccessingProtectedInternalMembers { //initiate the class class Employee { //define protected fields protected internal string firstName; protected internal string secondName; protected internal int myAge; }//end class //initiate another class class Program:Employee { //define the main method static void Main(string[] args) { //using object to access the protected fields //object form the inherited class Program prog = new Program(); prog.firstName = "Harvey"; prog.secondName = "Deitel"; prog.myAge = 55; //print data Console.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:

But if we didn't use the inheritance, we can not use an object from the 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 class use object + dot operator (.) else if(members private) use it in the same class use special methods like get and set get for reading only set for writing only else if(members protected) use it in the same class use inheritance else if(members internal) if(use internal static) use it in the same class else use it in the same class use it as public else //protected internal use it in the same class use it by inheritance use it as public

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 the default access modifier for the members is private. 4-Structs members can not be declared protected, or protected internal because it is not support the inheritance.

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 when using the protected internal access modifier. 9-Namespace doesn't take any access modifier, because it has no any 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 of named 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 the value of the successive enumerators is increased by [1]. -As the following examples; Example:
using using using using System; System.Collections.Generic; System.Linq; System.Text;

namespace EnumeratorList { class Program { enum letter { A, B, C, D, E }; static void Main(string[] args) { //get the elements in the list Console.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;

int c = (int)letter.C; int d = (int)letter.D; int e = (int)letter.E; //print values Console.WriteLine("the value Console.WriteLine("the value Console.WriteLine("the value Console.WriteLine("the value Console.WriteLine("the value Console.WriteLine("\n\n"); } } }

of of of of of

enumerator enumerator enumerator enumerator enumerator

A is : {0}", a); B is : {0}", b); C is : {0}", c); D is : {0}", d); E is : {0}", e);

The Output of this example will be as the following:

-We can override the default value of the first enumerator, and this can be done by passing a value to the first enumerator. As the following example;
using using using using System; System.Collections.Generic; System.Linq; System.Text;

namespace EnumeratorList { class Program { enum letter { A=10, B, C, D, E }; static void Main(string[] args) { //get the first element Console.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;

int c = (int)letter.C; int d = (int)letter.D; int e = (int)letter.E; //print values Console.WriteLine("the value Console.WriteLine("the value Console.WriteLine("the value Console.WriteLine("the value Console.WriteLine("the value Console.WriteLine("\n\n"); } } }

of of of of of

enumerator enumerator enumerator enumerator enumerator

A is : {0}", a); B is : {0}", b); C is : {0}", c); D is : {0}", d); E is : {0}", e);

The Output of this example will be as the following:

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

namespace EnumeratorList { public enum DayOfWeek { Sunday = 0, Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6 } class Program { static void Main() { DayOfWeek day = DayOfWeek.Thursday; int x = (int)DayOfWeek.Thursday;

System.Console.WriteLine("today is : {0}, \n\nand the value of the day in 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 any intergral 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 of the enumerator elements in the enumerator list, we convert each enumerator 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 data types, as list in the following table: Build-In Used For: Storage Data The use of the data type in the object Size in Types oriented programming Bytes bool true or false values 1 byte byte Values from [0] to [255] 1 byte sbyte 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, with 8 bytes 14-digits of accuracy float Single precision floating point numbers, with 4 bytes 6-digits of accuracy short Small integers in the range of [-32,768] to 2 bytes [32,767] ushort Values from [0] to [65,536] 2 bytes

int uint long ulong string

Whole numbers in the range of [2,147,483,648] to [2,147,483,647] Values from [0] to [4,294,967,296] Larger whole number Values from [0] to [1.844674407*10^19] Alphanumeric data, letters, digits, and other characters Any type of data

4 bytes 4 bytes 8 bytes 8 bytes Each letter 2 bytes 4 bytes

object

*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 data type. -There is no any lose in the data. Smaller Data Type Bigger Data Type

Convert into NO Lose In Data

Implicit Cast Result Example:


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

namespace ImplicitCast { class Program { static void Main() { //before casting int 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 data double 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 data type as the following: byte short, int, long, float, double, decimal. short int, long, float, double, decimal. int long, float, double, decimal. long float, double, decimal. float double only. 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

*Explicit Cast Operation: -It is used to convert from bigger data type to smaller data type. -There is significant lose in the data.

Bigger Data Type

Convert into Lose In Data

Smaller Data Type

Explicit Cast Result -The way of the explicit cast is to put the data type (smaller) that we need to convert into, between braces like this () and after it the value that we need to cast it Example:
using using using using System; System.Collections.Generic; System.Linq; System.Text;

namespace ExplicitCast { class Program { static void Main() { //before casting double 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 data int 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:

5- Constructor: **Key Points: 1- Definition. 2- Properties. 3- Default Values of Build-In Data Types. 4- Constructor Types. default overloaded static 5- 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 it from 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.

12- It is created spontaneously if we never created any constructor and be the default constructor that takes no parameters.

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 any constructors inside this class, the compiler spontaneously will create an implicit default constructor, and use the default values of the data types for your attributes in the class that have no initialization values. As the following table contents, we will find all of the default values of the primary build-in types. Build-In Default Build-In Default Data Value Data Value Types Types 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 the Object-Oriented Programming[OOP]. *Default Constructor: -Which has no any parameters -Is created spontaneously and implicitly if you never created any constructor in the class. Example:
using using using using System; System.Collections.Generic; System.Linq; System.Text;

namespace DefaultConstructor { //initiate a class class MyCar { //define the fields of the class private string myCarColor; private decimal myCarLength;

//default constructor //must be public //has the same name as the class //doesn't return any value //ideal location for any initialization task public MyCar() { The location of myCarColor = "black"; initialization myCarLength = 250.35M; }//end default constructor //define get methods public string GetMyCarColor() { return myCarColor; } public decimal GetMyCarLength() { return myCarLength; }//end get methods } class Program { static void Main() { //creating object from the class MyCar car = new MyCar(); //print data Console.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 instance variables in the class. -If you make an overloaded constructor, the compiler will not make the default constructor. -Can be found more than one overloaded constructor in the class. Example:
using using using using System; System.Collections.Generic; System.Linq; System.Text;

namespace OverloadedConstructor { //initiate a class class MyCar { //define the fields of the class private string myCarColor; private decimal 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 variables public MyCar(string color, decimal length) { //assignment for instance variables myCarColor = color; myCarLength = length; }//end overloaded constructor //define get methods public string GetMyCarColor() { return myCarColor; } public decimal GetMyCarLength() { return myCarLength; }//end get methods } class Program { The location of static void Main() { initialization //creating object from the class MyCar car = new MyCar("black", 250.35M); //print data Console.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".

-Static constructors are called automatically and immediately before any static fields are accessed. -Are normally used to initialize Static classes and members. -Are used to initialize any static data or perform a particular action that 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 task static MyCar() { myCarColor = "black"; myCarLength = 250.35M; }//end static constructor

5- Inheriting Constructor: -The constructor can use the keyword "base" to call a constructor of the base class in inheritance. -To call the default base constructor, use "base" without any parameters. -To call the overloaded base constructor, use "base" with parameters. -When calling the overloaded base constructor, the keyword "base" will has the parameter that match the base constructor in number of parameters, parameters types, parameters sequence, else it will be a syntax error. Example:
using using using using System; System.Collections.Generic; System.Linq; System.Text;

namespace InheritingConstructor { //initiate a class class MyBook { //define the fields private string Name; private string Author; //the overloaded constructor public MyBook(string name, string author) { //assignment for instance variables Name = name;

Author = author; }//end the overloaded constructor }//end MyBook class //initiate another class that inherit from the first class class MyPaper : MyBook //inheritance { //define the fields private string BookName; private string BookAuthor; //the overloaded constructor that call the overloaded //constructor from the base class public MyPaper(string bookName, string bookAuthor) : base(bookName,bookAuthor) { BookName = bookName; BookAuthor = bookAuthor; }//end the overloaded constructor of the derived class //define the get methods public string GetBookName() { return BookName; } public string GetBookAuthor() { return BookAuthor; }//end the get methods } class Program { static void Main() { //creating object from the base class MyBook book = new MyBook("java", "William Harvey"); //print data Console.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 = new MyPaper("C# Fundamentals", "Joseph D. Gradecki"); //print data Console.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:

6- Calling Constructor: -The constructor can use the keyword "this" to call a constructor of the same class. -To call the default constructor, use "this" without any parameters. -To call the overloaded constructor, use "this" with parameters. -When calling the overloaded constructor, the keyword "this" will has the parameter that match the constructor in number of parameters, parameters types, parameters sequence, else it will be a syntax error. Example:
using using using using System; System.Collections.Generic; System.Linq; System.Text;

namespace CallingConstructor { //initiate a class class MyBook { //define the fields private string Name; private string Author; //the default constructor public MyBook() { Name = "Visual C # 2005 How to Program"; Author = "Pual Deitel"; } //the overloaded constructor public MyBook(string name, string author):this() { //assignment for instance variables Name = name; Author = author; }//end the overloaded constructor //define the get methods public string GetBookName()

{ return Name; } public string GetBookAuthor() { return Author; }//end the get methods }//end MyBook class //initiate another class that inherit from the first class class Program { static void Main() { //creating object from the class MyBook book = new MyBook(); //print data Console.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 use until they are explicitly released.

If all references to object that manage the resources are lost before the resource is explicitly released, the application can no longer access the resources to release it and this called {memory leak}. Dot Net Framework Common Library [FCL], had produced a way to give back the resources to the system when they are no longer needed. Common Language Runtime [CLR] performs automatic memory management by using the "Garbage Collector", to reclaim the memory occupied by the objects that are no longer in use so, memory can be used for other objects. When there are no more references to an object, it becomes eligible for destruction. Every object has a special member called "Destructor", which is invoked by the garbage collector to perform termination housekeeping on an object, just before the garbage 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 the garbage collector.

2- Definition: Is a special method like any method, and we can able to ignore it and didn't write it in the class, because the CLR will be automatically did a management for the memory, and reclaim the unreferenced objects .

2- Properties: The destructor has the following properties, which distinguish it 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 garbage collector. 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".

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

namespace Destructor { //initiate a class class SampleClass { //define the fields private int 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 class class Program { static void Main() { //creating object from the class SampleClass mysampleclass = new SampleClass(); //using the garbage collector to invoke the destructor GC.Collect(); //print data Console.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 its value from the memory.

3- Destructor Working: The destructor implicitly calls the "finalize" method on the objects base class, so the compiler understanding the code of the destructor as the following:
protected override void Finalize() { try //try block for first testing { //statements that you need to execute

} finally //finally always execute its code in any case { base.Finalize(); } }

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

4- Garbage Collector: 1- Definition: Checks for objects that are no longer being used by the application.

2- Steps of Working: The garbage collector working according to the following three steps: Searches for managed objects that are referenced in the managed 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 the build-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 work GC.Collect();

The class

The method

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

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

The class

The method

-Using GCCollectionMode.Optimized, to determine that, is this an optimized time to reclaim the memory or not. Example:
class Program { static void Main() { //creating object from the class //and the object will reserve a location in the memory SampleClass mysampleclass = new SampleClass(); //when making the object is null //it will not be in use //but it still has the location in the memory mysampleclass = null; //oblige the garbage collector //to invoke the object destructor //to reclaim the memory GC.Collect(); } } -If the destructor writes to console any data, we must

use

the following method with the garbage collector


GC.WaitForPendingFinalizers();

-This method will make the garbage collector wait until the destructor 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.

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

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

-It can contain one of them as the following:


get accessor only set accessor only

-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 the instance 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 accessor is used for retrieving and returning the value of the instance variable.

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 by using the keyword "value" which refere to any value that the user will input from the console window, or any initialization in the 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 instance variables.

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

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

namespace ReadAndWriteProperty { class GradeBook { //define the fields private string courseName; //property to get and set the course name public string 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 instance variable //the keyword "value" make the instance variable taking any value that the //user will enter it on the console window } } } class Program { static void 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 GradeBook myGradeBook = new GradeBook(); //passing the value that the user will enter it //to the property and immediately to the instance variable myGradeBook.CourseName = Name; //printing results Console.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:

-In the set Accessor we can ignore the keyword "value", and initialize the instance variable by putting an explicit value, and any value the user will input it from the console window, the compiler will ignore it, and print only the explicit value of the instance variable as the following: Example:
using using using using System; System.Collections.Generic; System.Linq; System.Text;

namespace ReadOnlyProperty { class GradeBook { //define the fields private string courseName; //property to get and set the course name public string 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 the instance variable //the keyword "value" make the instance variable taking any value that the //user will enter it on the console window } } } class Program { static void 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

GradeBook myGradeBook = new GradeBook(); //passing the value that the user will enter it //to the property and immediately to the instance variable myGradeBook.CourseName = Name; //printing results Console.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 value of the instance variable in case of abandoning writing any value of the instance variable as the following: Example:
using using using using System; System.Collections.Generic; System.Linq; System.Text;

namespace ConsoleApplication1 { class Demo { //define the fields internal int x = 3; internal int y = 4; //read only property public int Multiple { //get accessor for reading only //the value of the instance variables get { return x * y; }//end get accessor }//end property } class Program {

static void Main(string[] args) { //create an object from the class Demo myclass = new Demo(); //print data Console.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 instance variable as the following: Example:
using using using using System; System.Collections.Generic; System.Linq; System.Text;

namespace OverrideInstanceVariableValue { class Demo { //define the fields private int x = 3; //using property public int X { //get accessor for reading //the value of the instance variable get { return x; }//end get accessor //set accessor for modifying //the value of the instance variable set { 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

}//end set accessor }//end property } class Program { static void Main(string[] args) { //create an object from the class Demo myclass = new Demo(); //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 set accessors to print it as the following: Example:
using using using using System; System.Collections.Generic; System.Linq; System.Text;

namespace GetAndSetAccessorsStatements { class Demo { //define the fields private int x = 3; //using property public int X { //get accessor for reading //the value of the instance variable get {

Console.WriteLine("\n\treturn the value of the instance variable"); 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 } class Program { static void Main(string[] args) { //create an object from the class Demo myclass = new Demo(); //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.

2- Static

Definition. Declaration. Accessing. 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 using the keyword "static", it is considered instance.
private int x; -This

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

public int Summation(int x, int y) { int s; return x = x + y; }

*Accessing: -In accessing the instance members, we must take care of the access modifier of this member to be able to access it see the access modifier. -The public instance members can be accessed any where by using the object of the class that contain these members and the (.) dot operator. -The private instance members can be accessed any where by using the special methods in the class that contain these members like the set(), and get() methods with the object of this class. -The protected instance members can be accessed any where by using the inheritance of the class that contain

these members to the class that the access operation will occur in. -The internal instance members can be accessed any where by using the object of the class that contain these members and the (.) dot operator. -when the use of the class that contains instance members is terminated, the value of the local variable is lost. -See any previous example.

2- Static Members: *Definition: -All objects of the static members share the same piece of data. -Also for the classes itself.

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

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


static void Main(string[] args) { Console.WriteLine("Welcome to C#.Net"); }

*Accessing: -Public static members can be accessed any where by using the name of the class that contain the static members, and the (.) operator, then the name of the member that you need to access it. -Private static members can be accessed any where only by using some public static special methods like get(), and set() methods, and properties of the class. -they are availabe as soon as the class is loaded into the 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

twentynine [29] static methods, and two [2] constant values. Examples:
using using using using System; System.Collections.Generic; System.Linq; System.Text;

namespace ConsoleApplication1 { class Program { const int x = 0; static void Main(string[] args) { //define fields double 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 value a = 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 radians e = Math.Cos(0.0); f = Math.Cos(90.0); //using Exponential method //returns the exponential of the value e^value g = Math.Exp(1.0); h = Math.Exp(2.0); //using Floor method //returns the value of the largest integer not greater than the input value i = 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 value q = Math.Pow(2.0, 7.0);

r = Math.Pow(9.0, 0.5); //using sin method //returns the trigonometric sine of the value in radians s = Math.Sin(0.0); t = Math.Sin(90.0); //using square root method //returns the square root of the value u = Math.Sqrt(900.0); v = Math.Sqrt(64.0); //using tan method //returns the trigonometric tangent of the value in radians w = Math.Tan(0.0); x = Math.Tan(45.0); Console.WriteLine("\n\tthe absolute method, the absolute value of {0}, is : {1}", 23.7, a); Console.WriteLine("\tthe absolute method, the absolute value 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 square root value of {0}, is : {1}", 900, u); Console.WriteLine("\tthe square root method, the square root value of {0}, is : {1}", 64.0, v);

Console.WriteLine("\tthe tangent method, the tangent value of {0}, is : {1}", 0.0, w); Console.WriteLine("\tthe tangent method, the tangent value 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 the members in the class didn't need to a specific instance of the class. -We create static members in the class when no object of the class exist.

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

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

-Each warrior will have its separate copy of the instance variable, and every time we add new warrior, we will have to update the instance variable. -This will waste time in updating the separate copy and will be error prone. -If we declared it as static variable as the following:
static int WarriorCount = 0;

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

9-General Examples: Example:1


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

namespace EmployeeConstructorAndDestructor { class Employee { //define the fields private string firstName; private string lastName; private static int count = 0; //constructor public Employee(string fname, string lname) { //assignment for the instance variables firstName = fname; lastName = lname; //increment the counter of the employees count++; //print the names of the employees and there count

Console.WriteLine("\n\temployee construction {0}, {1}; count = {2}", firstName, lastName, count); } //destrcuctor ~Employee() { //decrement the counter of the employees count--; //print the names of the employees and there count Console.WriteLine("\n\temployees destruction {0}, {1}; count = {2}", firstName, lastName, count); } //read only property public string FirstName { get { //return the first name of the employees return firstName; }//end get }//end property //read only property public string LastName { get { //return the last name of the employees return lastName; }//end get }//end property //read only property public static int Count { get { //return the counter of the employees return count; }//end get }//end property }//end class class Program { static void Main(string[] args) { //print initial value of emlpoyee before construction Console.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 = new Employee("Harvey", "M. Deitel"); Employee emp2 = new Employee("Paul", "j. Deitel"); //print the number of the employees after passing values Console.WriteLine("\n\temployees after instantiation is : {0}", Employee.Count); //print the name of the employees

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 destrcution emp1 = null; emp2 = null; //oblige the garbage collector //that invoke the destructor //and execute it, then reclaim the memory GC.Collect(); //wait until the destrutor finish its execution GC.WaitForPendingFinalizers(); //print the number of the employees after the destruction of the objects Console.WriteLine("\n\temployees after destruction : {0}", Employee.Count); Console.WriteLine("\n\n"); } } }

The Output of this example will be as the following:

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

namespace TwoClasses { //initiate the first class class CommissionEmployee {

//define the fields private string firstName; private string lastName; private string socialSecurityNumber; private decimal grossSales; private decimal commissionRate; //the default constructor public CommissionEmployee() { }//end default constructor //the overloaded constructor public CommissionEmployee(string fname, string lname, string ssn, decimal sale, decimal rate) { //assignment for the instance variables firstName = fname; lastName = lname; socialSecurityNumber = ssn; grossSales = sale; commissionRate = rate; }//end overloaded constructor //read-only property public string FirstName { get { //return the first name of the employee return firstName; }//end get accessor }//end property //read-only propery public string LastName { get { //return the second name of the employee return lastName; }//end get accessor }//end property //read-only property public string SocialSecurityNumber { get { //return the social security number of the employee return socialSecurityNumber; }//end get accessor }//end property //read and write property public decimal GrossSales { get { //return the gross sales of the employee return grossSales; }//end get accessor set

{ //put the condition on the value of the gross sales //gross sales will take its value from the user input in the main class grossSales = (value < 0) ? 0 : value; }//end set accessor }//end property //read and write property public decimal CommissionRate { get { //return the commission rate of the employee return commissionRate; }//end get accessor set { //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 //define a method that return the earning of the employee public decimal Earning() { return commissionRate * grossSales; }//end method }//inititate the second class class BasePlusCommissionEmployee { //define the fields private string firstName; private string lastName; private string socialSecurityNumber; private decimal grossSales; private decimal commissionRate; private decimal baseSalary; //the default constructor public BasePlusCommissionEmployee() { }//end default constructor //the overloaded constructor public BasePlusCommissionEmployee(string fname, string lname, string ssn, decimal sale, decimal rate, decimal salary) { //assignment for the instance variables firstName = fname; lastName = lname; socialSecurityNumber = ssn; grossSales = sale; commissionRate = rate; baseSalary = salary; }//end default constructor //read-only property public string FirstName {

get { //return the first name of the employee return firstName; }//end get accessor }//end property //read-only propery public string LastName { get { //return the second name of the employee return lastName; }//end get accessor }//end property //read-only property public string SocialSecurityNumber { get { //return the social security number of the employee return socialSecurityNumber; }//end get accessor }//end property //read and write property public decimal GrossSales { get { //return the gross sales of the employee return grossSales; }//end get accessor set { //put the condition on the value of the gross sales //gross sales will take its value from the user input in the main class grossSales = (value < 0) ? 0 : value; }//end set accessor }//end property //read and write property public decimal CommissionRate { get { //return the commission rate of the employee return commissionRate; }//end get accessor set { //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

public decimal BaseSalary { get { //return the base salary of the employee return baseSalary; }//end get accessor set { //put the condition on the value of the base salary //base salary will take its value from the user input in the main class baseSalary = (value < 0) ? 0 : value; }//end set accessor }//end property //define a method that return the earning of the employee public decimal Earning() { return baseSalary + (commissionRate * grossSales); }//end method } class Program { static void Main(string[] args) { //declaring fields according to the first class CommissionEmployee string firstname, lastname, socialnumber; decimal grosssales, commissionrate, basesalary; Console.WriteLine("\n\tfor the first class which is CommissionEmployee."); 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,commis sionrate); 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

BasePlusCommissionEmployee baseEmp = new BasePlusCommissionEmployee(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:

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, in another class, that use all members in the other class and can add new members in it. As an example, like human There are men and women Each man has its own attributes like woman as: name, age, weight, length, shape, hair color And both can share some attributes like: Each of them has two eyes, two ears, one nose, one mouth, two hands, two legs, hair

From this we can do the following Make a large class called human In which all shared attributes among men and women. Then make a two small specified classes Class for men in which all specific attributes in men. Class for women In which all specific attributes in women. The two small classes[men, and women] will inherit the shared attributes from the large class[human]. From this we can find that, the inheritance avoid us from repeating the code in both two small classes, in the same time both of them have these shared attributes, but without declaring any shared attributes 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 existing classs members and enhancing them with a new modified capabilities. The inheritance is denoted by the arrow, with closed arrowhead, like this An illustration data gram for both the base class, and the new class which called the child or derived class. Existing class. From Your Creation, or Build-In Class Based Class, Super, or Parent Class Supply Members to other classes to inherit from it.

Called

New class, inherit from another class

Called

Derived Class, SubClass, or Child Class

More Specified than its base class.

*Illustration Example: Usually we have to fall back upon the inheritance, when we find a shared data among two classes, we take this shared data and isulate it in one class, in a manner that all other classes that need this shared data can inherit it.

Example: We all know the difference between the Expert, and The Employee Expert paid by hour, and more efficient. Employee paid by salary, and sufficient efficient. Suppose that, we have two classes [Expert, Employee], and there are some fields in these two classes as the following illustration: Expert Class Employee Class Expert Name Address Phone ID HourRent HourWorked Employee Name Address Phone ID Salary DaysWorked

As we see, both classes share data, and there are some different data also, if we make the two classes as this, it will generate for us a great redundancy in the code, and the 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 base class that include the shared data. By this way, we will avoid the code redundancy, and the program will be more robust and elegant. Expert Class Employee Class Expert HourRent HourWorked Employee Salary DaysWorked Subclass, Child, or Derived Class

Subclass, Child, or Derived Class

Person Name Address Phone ID

Superclass, Parent, or Base Class

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 The Derived Class, that needs to inherit The colon sign (:) Superclass, Parent, or Base Class

Access Modifier

Keyword class

-As this example of the vehicle: public class MyCar : Vehicle -We use the keyword base to call any thing inside the base class like constructors, methods, -the base keyword is a hidden pointer, that holds the address of the current object being used. -If we need the derived class to have a different implementation for the base class methods, we must write the method in the derived class that overrides the base class methods.

4- Overriding Method: We can create a method with in the same argements list as a method in the base class. The new methd is said to override the base class method. The derived class will use the new method rather than 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 two keyword: 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 base class not in the derived class. Declare the new method in the derived class with the keyowrd override Example:

In the base class:


private virtual decimal ExtendedPrice() { //any code to execute }

In the derived class:


protected override decimal ExtendedPrice() { //any code to execute }

When we use the keyword virtual before any method in the base class, we have two options in the 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 base class method that has no any code, in the derived class we must provide its own code. The class that has any method with declaration of the keyword abstract, it will be considered abstract class which only can be used for inheritance. We can not instantiate objects from a class that contains abstract method.

5- Types: We have two types of inheritance of the classes 1- 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 a class that inherit from the base class, and there is no any explicitly inheritance between this derived class and the base class.

6- Is-a and Has-a Relations 1- Is-a Relation: It is representing the inheritance relationship. Like: Car is a Vehicle. Like: Object of the derived class can be treated as object of its base class.

Car is an object from the derived class, and in the same time 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 other object. Like: Car object has a reference to steering wheel.

*Inheritance Hierarchy: Refers to inheritance more than one class. Always read from the bottom to the top most, to achieve the Is-a relationship. Example:

CommunityMember

Employee Faculty
Administrator

Student
Undergraduate
Freshmen

Alumnus
Graduate
Sophomore

Staff
Teachers

Juniors

Dean

Chairperson

-To read this relation, for example the dean. Dean is an Administrator, is a Faculty member, is an Employee, is a CommunityMember. Sophomore is an Undergraduate, is a Student, is a CommunityMember. -By this we achieve the Is-a relationship. -From this, we can find that: CommunityMember is a direct base class to each of these classes [ Employee, Student, and Alumnus ], this type is Direct Inheritance. CommunityMember is an indirect base class to each of the other remaining class like [ Faculty, Staff, Undergraduate ], this type is Indirect Inheritance.

7- Properties: All public and protected members of the base class are inherited in the derived class. Access modifier for the base class members can be private or protected. To use base class properties in the derived class, the properties must be read and write [have get, and set]. Base class exist within the derived class in a hierarchical relationship. The set of objects represented by the base class is typically larger than the set of objects that represented by any of its derived classes, because every derived object is an object of its base class, and one base class can have more than one derived class. Not every class relation is inheritance relationship, it can be composition or aggregation relationships. Objects of all derived classes can be treated as an object of the common base class, not on contrary. Like: Car is a Vehicle, but not all Vehicles are cars.

8- Importance: It saves time during the program development by reusing proven and debugged high quality software. It increases the likelihood that a system will be implemented effectively. When declaring a new class, rather than declaring the completely new members, we can designate that, the new class should inherit the members of existing class. It prevents the code redundancy, and also it makes it readable, reliable, and reusable.

9- Disadvantage: The derived class can inherit all members that it needs and that it is not need.

10- Examples: Example:1 The circle and the cylinder Circle and cylinder have shared properties, like that: the cylinder has its base as circle.

Both only differ of that, the circle has not any length, but the cylinder has. The area of the circle is: *r^2. The area of the cylinder is:the area of the base which is circle, muliple by the length of the cylinder:(*r^2)*length.

Circle

Cylinder

The Program will be as the following:


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

namespace CircleAndCylinderInInheritance { //initiate the circle class class Circle { //define the fields of the circle private double radius; private const double PI = 3.1415; //overloaded constructor public Circle(double r) { //assignment radius = r; }//end constructor //method to display the area of the shape //it is declared virtual, becaus it will be override // in the derived class which is the cylinder //it is declared virtual not abstract, because it has a code public virtual double FindArea() { return PI * radius * radius; }//end method }//end circle class //initiate the cylinder class class Cylinder : Circle//inheritance { //define the field of the cylinder //in addition to the fields of the circle //that it inherit them by inheritance private double height; //overloaded constructor //the constructor of the cylinder inherit //the constructor of the circle public Cylinder(double radius,double h):base(radius) {

height = h; }//end constructor //override the method that display the area of the circle //to make it display the area of the cylinder public override double FindArea() { return height*base.FindArea(); }//end method }//end class class Program { static void Main(string[] args) { //ask user to input the radius of the circle Console.Write("\n\tPlease Enter the Radius of the Circle: "); //reading user input, and validate it to be double. double radius = double.Parse(Console.ReadLine()); //creat an object from the base class circle //and pass value to the radius through the constructor Circle cir=new Circle(radius); //print the area of the circle Console.WriteLine("\n\tthe area of the circle is : {0}", cir.FindArea()); Console.WriteLine("\n\n"); //ask user to input the height of the cylinder Console.Write("\n\tPlease Enter the Height of the Cylinder: "); //reading user input, and validate it to be double. double height = double.Parse(Console.ReadLine()); //create an object from the derived class cylinder //and pass value to the height through the constructor Cylinder cyl = new Cylinder(radius,height); //print the area of the cylinder Console.WriteLine("\n\tthe area of the cylinder is : {0}",cyl.FindArea()); Console.WriteLine("\n\n"); } } }

The Output of this example will be as the following:

Example:2 This example will be like the example2 in the general examples on the classes. I attempt to make it by inheritance, to see the difference and the importance of the inheritance. The commission rate, the gross sales, and the base salary. Each employee receives a commission amount on the gross [total] sales, with a specific rate. After the comission amount has been calculated, the employee added its value to his/her base salary. *Equaations in the classes: If gross slaes < 0 return 0, Else retuen the value of it. If the commission rate > 0 and in the same time it is < 1 return the value of the commission rate, Else return 0. Commission amoutn = commission rate * gross sales. If base salary < 0 return 0, Else return the value of it. All earnings = base salary + commission amount. The program will be as the following:
using System; using System.Collections.Generic;

using System.Linq; using System.Text; namespace ConsoleApplication2 { //initiate the class class CommissionEmployee { //define the fields private string firstName; private string lastName; private string socialSecurityNumber; private decimal grossSales; private decimal commissionRate; //the overloaded constructor public CommissionEmployee(string fname, string lname, string ssn, decimal sale, decimal rate) { //assignment for the instance variables firstName = fname; lastName = lname; socialSecurityNumber = ssn; grossSales = sale; commissionRate = rate; }//end overloaded constructor //read-only property public string FirstName { get { //return the first name of the employee return firstName; }//end get accessor }//end property //read-only propery public string LastName { get { //return the second name of the employee return lastName; }//end get accessor }//end property //read-only property public string SocialSecurityNumber { get { //return the social security number of the employee return socialSecurityNumber; }//end get accessor }//end property //read and write property public decimal GrossSales { get {

//return the gross sales of the employee return grossSales; }//end get accessor set { //put the condition on the value of the gross sales //gross sales will take its value from the user input in the main class grossSales = (value < 0) ? 0 : value; }//end set accessor }//end property //read and write property public decimal CommissionRate { get { //return the commission rate of the employee return commissionRate; }//end get accessor set { //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 //define a method that return the earning of the employee public virtual decimal Earning() { return commissionRate * grossSales; }//end method } class BasePlusCommissionEmployee : CommissionEmployee { //define the fields private decimal baseSalary; //the overloaded constructor public BasePlusCommissionEmployee(string fname, string lname, string ssn, decimal sale, decimal rate, decimal salary) : base(fname, lname, ssn, sale, rate) { baseSalary = salary; } //end overloaded constructor //read and write property public decimal BaseSalary { get { //return the base salary of the employee return baseSalary; }//end get accessor set { //put the condition on the value of the base salary

//base salary will take its value from the user input in the main class baseSalary = (value < 0) ? 0 : value; }//end set accessor }//end property //define a method that return the earning of the employee public override decimal Earning() { return baseSalary + base.Earning(); }//end method } class Program { static void Main(string[] args) { //declaring fields according to the first class CommissionEmployee string firstname, lastname, socialnumber; decimal grosssales, commissionrate, basesalary; Console.WriteLine("\n\tfor the first class which is CommissionEmployee."); 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,commi ssionrate); 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 (Commission Amount) 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 BasePlusCommissionEmployee baseEmp = new BasePlusCommissionEmployee(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 base salary is : {5:C}, \n\n\tthe earnings are : {6:C},", baseEmp.FirstName, baseEmp.LastName, baseEmp.SocialSecurityNumber, baseEmp.GrossSales, baseEmp.CommissionRate, baseEmp.BaseSalary, baseEmp.Earning());

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

The Output of this example will be as the following:

*Third: OOP Methods **Key Points: 1- Definition.

23456-

Importance. Return and Non-Return Methods. Parameterized and Non-Parameterized Methods. Calling Methods. Illustration Example.

1- Definition: Methods are constructions that break down the large sections of the code into small unit. Methods perform specific tasks, and usually hides the entire operations [encapsulate] from the user.

2- Importance:

Maintain and modify the code easily. Understand the code. Make the code readable, reliable, and reusable. Avoid code redundancy. Easy determine the exceptions and correct them.

3- Return and Non-Return Method: -We have two types of methods, that type of them returns a value and another type doesnt return any value. *Methods that return value: -We specify the return type of the method before the name of it. Like this: accessmodifier returntype MethodName() { //the task of the method, with return statement } *Methods that doesnt return any value: -We use the keyword void before the name of the method. Like this: accessmodifier void methodName() { //the task of the method }

4- Parameterized and Non-Parameterized Methods: -We have two types of method, that one type take parameters, and another type doesnt. *Methods that take Parameters: -We specify the type of the parameters, the name of it in the two braces after the name of the method. Like this: accessmodifier returntype MethodName(datatype parametersName) { //any code. } *Methods that didnt take any parameters: -We left the braces empty Like this: accessmodifier returntype MethodName() { //any code. }

5- Calling Method: To call a method in any location, we give the name of the method, and its parameters if it takes. When we specify multiple parameters in both the method header and the call to this method, the number of the parameters, their sequence, and their data types must match in both location [method header, and call to this method].

6- Illustration Example: The combination formula like this: Combination (m, n) =m! /n! (m - n)! The program will be as the following:
using using using using System; System.Collections.Generic; System.Linq; System.Text;

namespace ConsoleApplication1 { //initiate the primary class class Program

{ //define the factorial method static double Factorial(double n) { double f = 1; for (int i = 1; i <= n; i++) f *= i; return f; }//end factorial method //define the combination method static double Combination(double m, double n) { //calling the factorial method double c = Factorial(m) / (Factorial(n) * Factorial(m - n)); return c; }//end combination method //define the primary method static void Main(string[] args) { double m, n; //asking user to enter the first element Console.Write("\n\tplease Enter The First Number: "); //read the first element m = double.Parse(Console.ReadLine()); //asking user to enter the second element Console.Write("\n\tplease Ente The Second Number: "); //read the second element n = double.Parse(Console.ReadLine()); //calling the combination method if (m < n || n < 0 || m < 0) { Console.WriteLine("\n\t\aerror\n"); } else { double c = Combination(m, n); //print the result of the combination Console.WriteLine("\n\tthe combination of {0}, {1}, is {2}", m, n, c); Console.WriteLine("\n\n"); } } } }

The Output of this example will be as the following: In case of correct data:

In case of wrong data:

Done, and I have to give preference to Allah. praise be to God ! ******** Prepared by Ibraheim Gaber. Facult of Computers and Informatics. Third year-Computer Science.

Você também pode gostar