You are on page 1of 59

Chapter 3

Fundamentals of object-
oriented programming in
C#.
Outlines
• Object-oriented programming
• Variables and data types in C#
• Type conversion/ casting in C#
• C# operators
• C# statements
• C# Classes
• Encapsulation
• Inheritance
• Polymorphism

2
C# and Object-oriented programming
• Object-Oriented Programming is a programming methodology
• a program consists of various objects that interact with each other by means of
actions(methods).
• Object-oriented programming (OOP) is a computer programming model that
organizes software design around data, or objects, rather than functions and
logic.
• An object can be defined as a data field that has unique attributes and
behavior.
• Objects of the same kind are said to have the same type or, are said to be in
the same class.
• C# is an object-oriented programming language.
• It supports very advanced object-oriented concepts.
• Similar with c and c++ languages.
3
What is C#?
• C# is pronounced "C-Sharp".
• It is an object-oriented programming language created by Microsoft that runs on the .NET Framework.
• C# has roots from the C family, and the language is close to other popular languages like C++ and Java.
• The first version was released in year 2002. The latest version, C# 8, was released in September 2019.
C# is used for:
• Mobile applications
• Desktop applications
• Web applications
• Web services
• Web sites
• Games
• VR
• Database applications
• And much, much more!

4
Why Use C#?
• It is one of the most popular programming language in the world
• It is easy to learn and simple to use
• It has a huge community support
• C# is an object oriented language which gives a clear structure to programs
and allows code to be reused, lowering development costs.
• As C# is close to C, C++ and Java, it makes it easy for programmers to switch
to C# or vice versa

5
C# Syntax
Click icon to add picture

• use the following code to print "Hello Example explained


World" to the screen:
• Line 1: using System means that we can use
classes from the System namespace.
• Line 2: A blank line. C# ignores white space.
However, multiple lines makes the code more
readable.
• Line 3: namespace is a used to organize your
code, and it is a container for classes and other
namespaces.
• Line 4: The curly braces {} marks the beginning
and the end of a block of code.
• Line 5: class is a container for data and
methods, which brings functionality to your
program. Every line of code that runs in C# must
be inside a class. In our example, we named the
class Program.

6
Con’’’
• Line 7: Another thing that always appear in a C# program, is the Main method.
Any code inside its curly brackets {} will be executed.
• Line 9: Console is a class of the System namespace, which has
a WriteLine() method that is used to output/print text. In our example it will
output "Hello World!".
• If you omit the using System line, you would have to
write System.Console.WriteLine() to print/output text.
• Note: Every C# statement ends with a semicolon ;.
• Note: C# is case-sensitive: "MyClass" and "myclass" has different meaning.

7
Variables and data types in C#
• Variables are containers for storing data values.
• Each variable in C# has a specific type.

• Data type determines the size and layout of the variable's memory
• range of values to be stored in memory
• the set of operations applied to the value.

8
Cont’d… Integral types sbyte, byte, short,
ushort, int, uint, long,
ulong, and char

Floating point types float and double


• Syntax for variable definition
in C# is:
• <data_type> <variable_list>;
Decimal types decimal
• In VB.Net the variable is
defined as Dim variableName Boolean types true or false values, as
as DataType assigned

Nullable types Nullable data types

9
Cont’d…
• Datatype must be a valid C# or Vb.net data type.
• char, int, float, double, or any user-defined data type, and variable_list may consist of
one or more identifier names separated by commas.
• When defining a variable in C#, naming a variable should apply these rules.
• It must be less than 255 characters
• No spacing is allowed
• It must not begin with a number
• Special characters like ! # % $ & @ are not permitted except under score.
• Variable name must not be a reserved word (that is part of the code, like Dim, for
example).
• Variables can be initialized during definition.
• Accept values from user.
10
Cont’d…

11
Type conversion in C#

• After a variable is declared, it cannot be declared again or assigned a value of


another type
• unless that type is implicitly convertible to the variable's type.

• You can’t assign integer value to character variable.

• Type conversion is converting one type of data to another type.

• It is also known as Type Casting.

12
Cont’ d…

13
Cont’ d…

14
Cont’ d…

15
Cont’ d…

16
C# Operators
• An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations.
• C# provides a number of operators
• Arithmetic operators: that perform arithmetic operations with numeric operands
(+,-,*,/,%,++,--
• Comparison/ relational operators: that compare numeric operands (= =, <=,>=, !=,
<, >, )
• Boolean/ logical operators: that perform logical operations with bool operands (!,
&&,||)
• Bitwise and shift operators: that perform bitwise or shift operations with operands of
the integral types (&, |, ^, >>, <<)
• Equality/ Assignment operators: that check if their operands are equal or not or
assign values(=, +=, *=, - =, /=,)

17
Statements in C#
• The actions that a program takes are expressed in statements.
• declaring variables
• assigning values,
• calling methods
• looping through collections and
• branching to one or another block of code depending on a given condition
• A statement can consist of a single line of code that ends in a semicolon, or a
series of single-line statements in a block.
• A statement block is enclosed in {} brackets and can contain nested blocks.

18
Cont’d…
Statement type Description
Declaration statement A declaration statement introduces a new variable or constant.
A variable declaration can optionally assign a value to the
variable. In a constant declaration, the assignment is required.

Expression statement Expression statements that calculate a value must store the
value in a variable.
Selection statements Selection statements enable you to branch to different sections
of code, depending on one or more specified conditions.

 If  Switch
 Else  case

19
Cont’d…
Iteration statements Iteration statements enable you to loop through collections
like arrays, or perform the same set of statements
repeatedly until a specified condition is met.

 Do  forea
 for ch
 in
 while

Jump statements Jump statements transfer control to another section of


code.
Break, continue, default, goto, return, yield
Exception handling statements Exception handling statements enable you to gracefully
recover from exceptional conditions that occur at run
time.
Throw, try-catch, try-finally, try-catch-finally
20
Selection statements

• AKA decision making


statements.
• Requires the programmer to
specify one or more conditions
to be evaluated

21
If Condition
if (condition)
{
Console.WriteLine("The variable is set to true.");
}

22
If …Else condition
// if-else statement
if (condition)
{
then-statement;
}
else
{
else-statement;
}

23
Switch condition
• It allows a variable to be tested for equality against a list of values.
• It is an alternate to using the if..else statement when there are more than a
few options.
switch (expression)
{
case expression_value1:
Statement
break;
case expression_value2:
Statement
break;
case expression_value3:
Statement
break;
default:
Statement
break;
} 24
Loops or iteration statements in C#

• There may be a situation,


when you need to execute
a block of code several
number of times.
• A loop statement allows us
to execute a statement or a
group of statements
multiple times

25
Do statement
• Executes a statement or a block of statements while a specified Boolean
expression evaluates to true.
• Executes the statements one or more times.
int n = 0;
do
{
Console.WriteLine(n);
n++;
} while (n < 5);

26
Cont’d…
• You can jump to other statements by using the following jump statements.
• Break
• Continue
• Goto
• Return
• Throw

27
For statement
//Structure of the for loop statement
for (initializer; condition; iterator)
body
// example of the for loop statement
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}

28
The foreach, in statement
• Executes a statement or a block of statements for each element in an instance
of the type that implements the
• System.Collections.Ienumerable interface.

//foreach statement is used in this way


foreach (var item in collection) { }
// a collection can be any list of items like {1,2,3}
• GetEnumerator
• Structure
• List
• Dictionary

29
The while statement
int n = 0;
while (n < 5)
{
Console.WriteLine(n);
n++;
}
• Executes a statement or a block of statements while a specified Boolean
expression evaluates to true.
• Executes the statements inside the loop zero or more times

30
Exception handling statements
• When executing C# code, different errors can occur.
• Wrong input
• Wrong casting
• Wrong assignment or other errors.
• When an error occurs, C# will normally stop and generate an error message.
• The technical term for this is: C# will throw an exception (throw an error).

31
The throw statement
• It allows you to create a custom error.
• Statement is used together with an exception class.
• ArithmeticException
• FileNotFoundException
• IndexOutOfRangeException
• TimeOutException and other exception classes.

32
Cont’d…
• The syntax of throw is throw [e]; where e is an instance of a class derived
from System.Exception.
if (age < 18)
{
throw new ArithmeticException("Access denied - You
must be at least 18 years old.");
}
else
{ Console.WriteLine("Access granted - You are old
enough!");
}
33
C# try and catch
• The try statement allows you to define a block of code to be tested for errors while
it is being executed.
• The catch statement allows you to define a block of code to be executed, if an error
occurs in the try block.
try
{
// Block of code to try
}
catch (Exception e)
{
// Block of code to handle errors
}
34
Cont’d…

35
5. Classes in C#
C# - What are Classes and Objects?
• Classes and objects are the two main aspects of object-oriented programming.
• Look at the following illustration to see the difference between class and
objects:

36
Cont’d…
• Another example:

• So, a class is a template for objects, and an object is an instance of a class.


• When the individual objects are created, they inherit all the variables and
methods from the class.

37
Cont’d…
• Classes and structs are essentially a data structure that encapsulates a set of
data and behaviors that belong together as a logical unit.
• The data and behaviors are the members of the class or struct, and they
include its methods, properties, and events, and so on.
• If you define a class or struct called Person, Person is the name of the type.
• If you declare and initialize a variable p of type Person, p is said to be an
object or instance of Person.
• It is possible to create multiple instance for same type.

38
Cont’d…
• A class is a reference type.
• When an object of the class is created, the variable to which the object is
assigned holds only a reference to that memory.
• When the object reference is assigned to a new variable, the new variable
refers to the original object.
• Changes made through one variable are reflected in the other variable
because they both refer to the same data.

39
Cont’d…
• A struct is a value type.
• When a struct is created
• the variable to which the struct is assigned holds the struct's actual data.
• When the struct is assigned to a new variable, it is copied.
• The new variable and the original variable therefore contain two separate
copies of the same data.
• Changes made to one copy do not affect the other copy.

40
Cont’d
• classes are used to model more complex behavior, or data that is intended to
be modified after a class object is created.
• Structs are best suited for small data structures that contain primarily data that
isn't intended to be modified after the struct is created.

41
Cont’d
• Everything in C# is associated with classes and objects, along with its attributes
and methods.
• For example: in real life, a car is an object. The car has attributes, such as
weight and color, and methods, such as drive and brake.
• A Class is like an object constructor, or a "blueprint" for creating objects.

42
Cont’d

43
Cont’d
Multiple Objects
• You can create multiple objects of one class:

44
Cont’d

45
Cont’d

46
Cont’d

47
Properties and Encapsulation

48
Cont’d

49
Encapsulation
• It is defined as the process of enclosing one or more items within a physical
or logical package.
• prevents access to implementation details.
• A class or struct can specify how accessible each of its members is to code
outside of the class or struct.
• Methods and variables that are not intended to be used from outside of the
class or assembly can be hidden to limit the potential for coding errors or
malicious exploits.

50
Cont’d…
• Encapsulation is implemented by using access specifiers.
• An access specifier defines the scope and visibility of a class member.
• C# supports the following access specifiers.
• Public
• Private
• Protected
• Internal
• Protected internal

51
Cont’d…
• It is important to limit the accessibility of your code so that only the intended
client code can reach it.
• You specify how accessible your types and their members are to client code
by using the access modifiers.
• The default accessibility is private.

52
Inheritance
• Classes in C# support inheritance.
• A class that derives from another class (the base class) automatically contains
all the public, protected, and internal members of the base class.
• Classes can also be declared as sealed class therefore it will not be inherited.
• The base class is the parent class
• And the child class is derived class.
• inheritance is transitive

53
Cont’d…

54
Cont’d…

55
Polymorphism
• At run time, objects of a derived class may be treated as objects of a base
class in places such as method parameters and collections or arrays.
• When this polymorphism occurs, the object's declared type is no longer
identical to its run-time type.
• By creating virtual methods derived classes can override them.
• which means they provide their own definition and implementation
• Polymorphism concerns about multiple shaped/ featured functions.
• Or one interface.
• Implemented with function overloading

56
Function overloading
• You can have multiple definitions for the same function name in the same
scope.
• The definition of the function must differ from each other by the types and/or
the number of arguments in the argument list.
// from main class
public virtual double Area()
{
return 0;
}

57
Cont’d…
//from derived class

public override double Area()


{
return (3.14) * Math.Pow(Radius, 2);
}

58
The End !

59

You might also like