0% found this document useful (0 votes)
0 views31 pages

08 - Object.oriented.programming Windows Programming With C#

Uploaded by

roberatech
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views31 pages

08 - Object.oriented.programming Windows Programming With C#

Uploaded by

roberatech
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Windows Programming with C#

Using Visual Studio IDE, Visual Basic .NET, Visual Studio Code + Mono
Windows Console Application

Instructor : Eyasu G.
Telegram : @JoshKiyakoo
Email : [email protected]
Object Oriented Programming

<date/time> <footer> 2
What Is Object-Oriented Programming?
Object-oriented programming (OOP) is a programming paradigm, which uses
objects and their interactions for building computer programs.
Object-oriented programming (OOP) is an approach to programming that
breaks a programming problem into objects that interact with each other.
Thus an easy way to understand, simple model of the subject area is achieved,
which gives an opportunity to the programmer to solve intuitively (by simple
logic) many of the problems, which occur in the real world entities.
Objects are created from templates known as classes. You can think of a
class as the blueprint of a building. An object is the actual “building” that we
build based on the blueprint.

<date/time> <footer> 3
Fundamental Principles of OOP
In order for a programming language to be object-oriented, it has to enable
working with classes and objects as well as the implementation and use of
the fundamental object-oriented principles and concepts: inheritance,
abstraction, encapsulation and polymorphism.
- Encapsulation
- Inheritance
- Abstraction
- Polymorphism

<date/time> <footer> 4
Fundamental Principles of OOP
Inheritance
Inheritance is a fundamental principle of object-oriented programming. It
allows a class to "inherit" (behavior or characteristics) of another, more
general class.
For example, a lion belongs to the biological family of cats. All cats that have
four paws, are predators and hunt their prey. This functionality can be coded
once in the Cat class and all its predators can reuse it – Tiger , Puma, lion ,
Bobcat , etc.
Inheritance is described as is-kind-of relationship, e.g. Tiger is kind of Animal .

<date/time> <footer> 5
Fundamental Principles of OOP
Abstraction
The next core principle of object-oriented programming we are about to
examine is "abstraction". Abstraction means working with something we
know how to use without knowing how it works internally. This is an action,
which obscures all details of a certain object that do not concern us and only
uses the details, which are relevant to the problem we are solving.

<date/time> <footer> 6
Fundamental Principles of OOP
Encapsulation
Encapsulation is one of the main concepts in OOP. It is also called "data
hiding". An object has to provide its users only with the essential information
for manipulation, without the internal details.
The person writing the class has to decide what should be hidden and what
not. When we program, we must define as private every method or field which
other classes should not be able to access.

<date/time> <footer> 7
Fundamental Principles of OOP
Polymorphism
The next fundamental principle of Object-Oriented Programming is
"Polymorphism". Polymorphism allows treating objects of a derived class as
objects of its base class.
Polymorphism can bear strong resemblance to abstraction, but it is mostly
related to overriding methods in derived classes, in order to change their
original behavior inherited from the base class. Abstraction is associated with
creating an interface of a component or functionality (defining a role).

<date/time> <footer> 8
What Is a Class?
A class in C# is defined by the keyword class , followed by an identifier (name)
of the class and a set of data members (Data Fields) and methods in a
separate code block.
The class defines abstract characteristics of objects. It provides a structure for
objects or a pattern which we use to describe the nature of something (some
object). Classes are building blocks of OOP and are inseparably related to the
objects. Furthermore, each object is an instance of exactly one specific class.
We are going to give as an example a class and an object, which is its instance.
We have a class Dog and an object Timon , which is an instance of the class
Dog (we say it is an object of type Dog). The class Dog describes the
characteristics of all dogs whereas Timon is a certain dog.

<date/time> <footer> 9
What Is an Object?
Real-World objects are people, cars, goods, purchases, etc. abstract objects are concepts in an
object area, which we have to model and use in a computer program. In objects from the real
world (as well as in the abstract objects) we can distinguish the following two groups of their
characteristics:
- States – these are the characteristics of the object which define it in a way and describe it in
general or in a specific moment
- Behavior – these are the specific distinctive actions, which can be done by the object.
An object from the real world – "dog". The states of the dog can be "name" and "fur-color",
and its behavior – "barking", "sitting" and "walking".
They correspond to objects in real world and contain data and actions:
- Data members – embedded in objects variables, which describe their states.
- Methods – we have already considered them in details. They are a tool for building the
objects.

<date/time> <footer> 10
Classes, Attributes and Behavior
The class defines the characteristics of an object (which we are going to call attributes)
and its behavior (actions that can be performed by the object). The attributes of the class
are defined as its own variables in its body (called member variables). The behavior of
objects is modeled by the definition of methods in classes.
Creating the object of a defined class is called instantiation (creation). The instance is the
object itself, which is created at run-time. Each object is in instance of a specific class. This
instance is characterized by state – set of values, associated with class attributes.
We are going to illustrate the foregoing explanations through an example of a real-world
definition of a class. Let’s return to the example with the dog. We would like to define a
class Dog that models the real object "dog". The class is going to include characteristics
which are common for all dogs (such as name and fur-color), as well as typical for the dog
behavior (such are barking, sitting, walking). In this case we are going to have attributes
name and fur-Color, and the behavior is going to be implemented by the methods Bark() ,
Sit() and Walk() .

<date/time> <footer> 11
Elements of the Class – (Simple OOP based)
Now, we will go through the main elements of every class, and we will explain
them in details latter. The main elements of a C# classes are the following:
- Class declaration – this is the line where we declare the name of the class, e.g.:
public class Dog
- Class body – similar to the method idioms in the language, the classes also have
single class body. It is defined right after the class declaration, enclosed in curly
brackets " { " and " } ". The content inside the brackets is known as body of the
class. The elements of the class, which are numbered below, are part of the body.
public class Dog {
// … The body of the class comes here …
}

<date/time> <footer> 12
Elements of the Class – (Simple OOP based)
- Constructor – it is used for creating new objects. Here is a typical constructor:
public Dog () {
// … Some code …
}
- Data Fields – they are variables, declared inside the class (also known as member-
variables). The data of the object, which these variables represent, and are retained into
them, is the specific state of an object, and one is required for the proper work of
object’s methods. The values, which are in the fields, reflect the specific state of the
given object, but despite of this there are other types of fields, called static, which are
shared among all the objects.
// Field definition
private string name;

<date/time> <footer> 13
Elements of the Class – (Simple OOP based)
- Properties – this is the way to describe the characteristics of a given class.
Usually, the value of the characteristics is kept in the fields of the object.
Similar to the fields, the properties may be held by certain object or to be
shared among the rest of the objects.
// Property definition
private string Name { get; set; }
- Methods – Methods perform particular actions and through them the objects
achieve their behavior based on the class type. Methods execute the
implemented programming logic (algorithms) and the handling of data.

<date/time> <footer> 14
What Is a Constructor?
Constructor of a class is a pseudo-method, which does not have a return type, has the name of
the class and is called using the keyword new . The task of the constructor is to initialize the
memory, allocated for the object, where its fields will be stored (those which are not static ones).

Calling a Constructor

The only one way to call a constructor in C# is through the keyword new . It allocates memory for
the new object, calls their constructors (or chain of constructors, formed in succession), and at
the end returns a reference to the newly created object.

Dog Timon = new Dog();


Constructor Overloading

We can declare constructors with parameters. This gives us a possibility to declare constructors
with different signatures (number and order of the parameters) with the purpose of providing
convenience to those who will create objects from our class. Creating constructors with different
signatures is called constructor overloading.

<date/time> <footer> 15
Modifiers and Access Levels (Visibility Mode)
In C# there are four access modifiers: public , private , protected and
internal. The access modifiers can be used only in front the following
elements of the class: class declaration, fields, properties and methods.
Access Level "public"
When we use the modifier public in front of some element, we are telling the
compiler, that this element can be accessed from every class, no matter from
the current project (assembly), from the current namespace. The access level
public defines the miss of restrictions regarding the visibility. This access level
is the least restricted access level in C#.

<date/time> <footer> 16
Modifiers and Access Levels (Visibility Mode)
Access Level "private"
The access level private is the one, which defines the most restrictive level of
visibility of the class and its elements. The modifier private is used to indicate, that
the element, to which is issued, cannot be accessed from any other class (except
the class, in which it is defined), even if this class exists in the same namespace. This
is the default access level, i.e. it is used when there is no access level modifier in
front of the respective element of a class (this is true only for elements inside a
class).
Access Level "internal"
The modifier internal is used to limit the access to the elements of the class only to
files from the same assembly, i.e. the same project in Visual Studio. When we create
several projects in Visual Studio, the classes from will be compiled in different
assemblies.

<date/time> <footer> 17
Modifiers and Access Levels (Visibility Mode)
Assembly
.NET assemblies are collections of compiled types (classes and other types) and resources, which
form a logical unit. Assemblies are stored in a binary file of type .exe or .dll . All types in C# and as
general in .NET Framework can reside only inside assemblies. By every compilation of a .NET
application one or several assemblies are created by the C# compiler and each assembly is stored
inside an .exe or .dll file.
The Reserved Word "this"
The reserved word this in C# is used to reference the current object, when one is used from
method in the same class. This is the object, which method or constructor is called. The reserved
word can be deemed as an address (reference), given priory from the language authors, with which
we access the elements (fields, methods, constructor) of the own class:
this.myField; // access a field in the class
this.DoMyMethod(); // access a method in the class
this(3, 4); // access a constructor with two int parameters

<date/time> <footer> 18
Access to Fields of an Object
The access to the fields and properties of a given object is done by the operator .
(dot) placed between the names of the object and the name of the field (or the
property). The operator . (dot) is not necessary in case we access field or property of
given class in the body of a method of the same class.
We can access the fields and the properties either to extract data from them, or to
assign new data. In the case of a property the access is implemented in exactly the
same way as in the case of a field – C# give us this ability. This is achieved by the
keywords get and set in the definition of the property, which perform respectively
extraction of the value of the property and assignment of a new value. In the definition
of the class Cat the properties are Name and Color.

<date/time> <footer> 19
Creating and Releasing Objects
The creation of objects from preliminarily defined classes during program execution is
performed by the operator new . The newly created object is usually assigned to the variable
from type coinciding with the class of the object. We are going to note that in this assignment
the object is not copied, and only a reference to the newly created object is recorded in the
variable (its address in the memory). Here is a simple example of how it works:
Cat someCat = new Cat();
The variable someCat of type Cat we assign the newly created instance of the class Cat .

Creating Objects with Set Parameters


Now we are going to consider a slightly different variant of the example above in which we set
parameters when creating the object:
Cat someCat = new Cat ("Sassy", "Blue");

<date/time> <footer> 20
Creating and Releasing Objects
Releasing the Objects
An important feature of working with objects in C# is that usually there is no need to
manually destroy them and release the memory taken up by them. This is possible
because of the embedded in .NET CLR system for cleaning the memory (garbage
collector) which takes care of releasing unused objects instead of us.
Objects to which there is no reference in the program at certain moment are
automatically released and the memory they take up is released. This way many
potential bugs and problems are prevented. If we would like to manually release a
certain object, we have to destroy the reference to it, for example this way:
someCat = null;

<date/time> <footer> 21
Class Naming Convention
Equal to the methods, for creation of the class names there are the following
common standards:
1. The names of the classes begin with capital letter, and the rest of the letters
are lower case.
- If the name of the class consists of several words, every word begins
with capital letter, without separator to be used. This is the well-known
PascalCase convention.
2. For name of the classes nouns are usually used.
3. It is recommended the name of the class to be in English language.

<date/time> <footer> 22
Example in C# Class
public class Cat { public string Color { // Parameterized Constructor

// Field name // Getter of the property public Cat(string name, string color) {
"Color"
private string name; this.name = name;
get { return this.color; }
// Field color this.color = color;
private string color;
// Setter of the property "Color" }
public string Name { // Method SayMiau
set { this.color = value; }
// Getter of the property "Name" } public void SayMiau() {
get { return this.name; } // Default constructor Console.WriteLine("Cat {0} said:
Miauuuuuu!", name);
public Cat() {
this.name = "Unnamed"; }
// Setter of the property "Name"

set { this.name = value; } this.color = "gray"; }

}
}

<date/time> <footer> 23
Example in C# Class
The example class Cat defines the properties Name and Color , which keep their values in the hidden
(private) fields name and color . Furthermore, two constructors are defined for creating instances of
the class Cat , respectively with and without parameters, and a method of the class SayMiau() .

After the example class is defined we can now use it in the following way:
static void Main() {
Cat firstCat = new Cat();
firstCat.Name = "Sassy";

firstCat.SayMiau();
Cat secondCat = new Cat("Nalla", "Green");
secondCat.SayMiau();
Console.WriteLine("Cat {0} is {1}.", secondCat.Name, secondCat.Color);

<date/time> <footer> 24
Assignment 8
1. Create a class called vehicle with the following members:
Data fields: manufacturer, model, year, miles, vehicle type
Behaviors: Start Engine, Stop Engine, turn right, turn left, go forward, go backward
Create an instance of the vehicle class named myCar and assign data to each of the
members. Populate each in the array with your favorite car model information. Use a
for loop to print each object detail in the array.

2. Create a program that uses a class array to hold contact information for your
friends like Full Name, Phone, email, Company, Position, contact category.
The program should allow the user to enter up to ten (10) friends and print
the phone book’s current entries. Create functions to add entries in the
phone book and to print valid phone book entries. Do not display phone
book entries that are invalid or NULL (0).

<date/time> <footer> 25
Course Project
Select one (1) from the list of course project titles and form a group that contains only
up to five (5) members.
1. College Record Manager (student, department, instructor, Assigned Courses,
Result and Grade)
2. Supermarket Store Manager (Customer, Item, Sales, Prices, location, inventory)
3. Human Resource Manager (Employee, Department, HR Head, Payroll)
4. Bank Account Manager (Customer, Deposit, Withdrawal, New, Loan, Balance)
5. Pharm acyDrugStore Manager( Cust omer , It em, Pr ic es, sales, locati on, inventor y)

5. Garage Auto- Mechani csManager( v


ehi cl es, cust omer s, i tem s, suppli ers , repl aced it ems, inventor y)

<date/time> <footer> 26
Course Project - continued
General Instructions to Follow:
1. the group should contain minimum of one (1) up to five (5) members only, but no more than
specified.
2. your final compiled course project must be submitted by email at [email protected]
until Saturday, August 21, 2021.
- subject should mention Course Name - Project Title
- content of the email must be member’s name, ID number and Section
3. your source code project should be sent with zipped file in the following format.
Course.Project_YourProjectTitle_RD2CS4.zip/rar
4. including your C# course level project you will submit a paper in pdf format, that elaborates
the purposes of the CLASSs, FIELDs and BEHAVIORs in your source code and provides a
scenario on each selected tasks.

<date/time> <footer> 27
Course Project - continued
Your Source Code Implementation:
1. Display all data
2. Display Single requested data
3. Add new data
4. Search data by name and id
5. Sort data by name and id
6. Specific Tasks based on your project (Business Logic)
7. Delete data based on request
8. Update data based on request

<date/time> <footer> 28
Course Project - continued
Evaluations:
1. may use conditional statements, iterative statements, function calling, class
templates and overloading and (inheritance if possible)
2. handling possible exceptions.
3. well use of naming (variables, classes and methods), formatting (source code) and
source code documentation.
4. You must deliver your project on the spotted date as specified and each and every
member of the group must participate and must know how the their system operates.
NB
*** Your C# Program will be developed using Console Application

<date/time> <footer> 29
Exception Handling
Reading Assignment

<date/time> <footer> 30
Thank You !!!

<date/time> <footer> 31

You might also like