CHAPTER Three
Object-Oriented
Fundamentals in C#
Language Fundamentals
Jun 21, 2024
C# is an object-oriented language.
Means you work with objects in building an application.
Examples: Form objects, Button objects, TextBox objects, Label
objects, ListBox objects, PictureBox objects, and more.
C# is also termed an event-driven programming
language because you will write program code that
Event Driven Programming
responds to events that are controlled by the system user.
Example events include:
Clicking a button or menu.
Opening or Closing a form.
Moving the mouse over the top of an object such as a text box.
Moving from one text box to another.
2
General Features of C#
Jun 21, 2024
It is an object oriented programming language.
C# has been inspired by earlier object-oriented programming
languages.
Provides a quick way to develop heavy duty applications in a
windowing environment.
Event Driven Programming
It is a useful tool for developing event driven programs.
Can be used to create both windows applications and web
applications at the click of a mouse button.
C# is case sensitive.
When a line ends with the underscore (_) character, this tells C#
that the code on that line is not complete.
A comment can be written by preceding a double slash(//). 3
Basic Concepts
Jun 21, 2024
In order to work with C#, you need to understand "object"
terminology as defined as follows.
Object:
A thing or an entity in your application. Examples
include forms and controls you place on forms such as
Event Driven Programming
buttons, text boxes, and icons.
Property:
Objects have properties. Properties describe object
behaviors.
Examples of properties include Text, Name, BackColor,
Font and Size.
Refer to a property by the notation called Dot Notation. 4
Cont’d…
Jun 21, 2024
Methods:
These are the actions that objects exhibit.
Examples include methods to Show and Hide forms and
methods to Print and Close forms.
Like properties you can refer to a method with the dot
Event Driven Programming
notation.
Events:
Events are actions usually triggered by the system user
such as clicking a button; however, events can also be
triggered by the actions of objects.
For example, closing a form can trigger an event. 5
Cont’d…
Jun 21, 2024
Class:
It is a sort of template for an object.
For example:
All forms belong to the Form class of object.
All buttons belong to the Button class of object.
Classes include definitions for object properties, methods, and associated
events.
Event Driven Programming
Each class is assigned an identifying namespace within the .NET Framework
Class Library.
Each new object you create is defined based on its class – the new object is called
a class instance.
Example Code:
class SampleClass
{
// Code goes here. 6
Cont’d…
Jun 21, 2024
Instance:
It is an object created from a class and represents current
state.
An instance of a class can be created using the New
keyword.
Event Driven Programming
The New command tells the compiler to create an instance
of that class.
Example Code:
Form winForm = new Form ();
The above C# code creates a windows form which is an
instance of windows forms class with the name winForm
7
Cont’d…
Jun 21, 2024
Solution:
In C# the programming applications you will design
and develop are called solutions.
A solution can actually contain more than
one project.
Event Driven Programming
Each solution is stored in a folder identified by the
solution name.
Me:
Is a reference to the instance of the object within
which a method is executing.
8
Cont’d…
Jun 21, 2024
Dot Notation
Used to reference object's properties and methods in code
Syntax
ObjectName.PropertyName/ObjectName.MethodName
Example:
Event Driven Programming
Object dot Property
frmForm.Text, txtTextBox.Text;
Object dot Method
frmForm.Hide( ), txtTextBox.Focus( )
To reference an object's events use an underscore instead of
a dot
Button_Click, ListBox_TextChanged
9
Constants and Variables
Jun 21, 2024
Variable
Memory locations that hold data that can be changed
during program execution.
Ex: midResult, total,…
Variables in C# can be declared as follows:
Event Driven Programming
Data_Type var_Name;
e.g., int i;
They can also be initialized at the time of declaration as
follows:
int i = 3; 10
Cont’d…
Jun 21, 2024
Constant
Memory locations that hold data that cannot be changed
during program execution.
Ex: Sales tax percentage, pie (П),…
Constants in C# can be declared as follows:
Event Driven Programming
const Data_Type const_Name;
e.g., const int months = 12;
Data Types
Are used to specify the type of data/information that a
variables holds.
It also determines how much memory is allocated to store
data in. 11
Data Types
Jun 21, 2024
Type Represents Range Default Value
bool Boolean value True or False False
byte 8-bit unsigned integer 0 to 255 0
char 16-bit Unicode character U +0000 to U +ffff '\0'
decimal 128-bit precise decimal values with 28- (-7.9 x 1028 to 7.9 x 1028) / 100 to 28 0.0M
29 significant digits
double 64-bit double-precision floating point (+/-)5.0 x 10-324 to (+/-)1.7 x 10308 0.0D
type
Event Driven Programming
float 32-bit single-precision floating point type -3.4 x 1038 to + 3.4 x 1038 0.0F
int 32-bit signed integer type -2,147,483,648 to 2,147,483,647 0
long 64-bit signed integer type -923,372,036,854,775,808 to 0L
9,223,372,036,854,775,807
sbyte 8-bit signed integer type -128 to 127 0
short 16-bit signed integer type -32,768 to 32,767 0
uint 32-bit unsigned integer type 0 to 4,294,967,295 0
ulong 64-bit unsigned integer type 0 to 18,446,744,073,709,551,615 0
ushort 16-bit unsigned integer type 0 to 65,535 0
12
Naming Rules
Jun 21, 2024
There are technical rules you must follow when
creating variable and constant names.
An identifier must start with a letter or an
underscore
Event Driven Programming
After the first character, it may contain numbers,
letters, connectors, etc
If the identifier is a keyword, it must be prepended
with “@”
13
Jun 21, 2024
Naming Rules...
Always use standard names for objects
Numbers, letters, & underscore
Must start with letter or underscore
No spaces or punctuation marks
3 letter lowercase prefix identifies control type
Event Driven Programming
Button-btn
Label-lbl
Form-frm
If multiple words capitalize 1st letter of each word – Camel casing
btnExitProgram
14
Jun 21, 2024
Recommended Naming Conventions
Object Class Prefix Example
Form frm frmDataEntry
Button btn btnExit
TextBox txt txtUserName
Label lbl lblName
Event Driven Programming
Radio Button rad radBold
CheckBox chk chkMale
Horizontal ScrollBar hsb hsbRate
Vertical ScrollBar vsb vsbTemprature
PictureBox pic picLandscape
ComboBox cbo cboBookList
ListBox lst lstCourse 15
Declaration Statements
Jun 21, 2024
A declaration-statement declares a local variable or
constant.
CONST used to declare Named Constants
Declaration includes
Event Driven Programming
Name, follow Naming Convention Rules
Data Type
Required Value for Constants
Optional Initial Value for Variables
16
Declaration Examples
Jun 21, 2024
• String strName, strIdNo;
• Decimal decPayRate = 8.25
• DateTime hireDate;
Event Driven Programming
• Boolean isFound;
• Long population;
• const Decimal PIE = 3.14m;
17
Variables – Scope & Lifetime
Jun 21, 2024
There are two important scopes in C#:
Local scope refers to names defined within a method or a within a block
within a method.
Class-level scope refers to all the names defined within the current class (but
this excludes any local names that are defined inside methods of the class.)
Lifetimes of objects and variables
Every object and variable in program has lifetime: It gets created (or
Event Driven Programming
instantiated) at some particular moment in time, and then at some later time it
dies.
Variables that are defined within a method or a block only live while the
method or block is being executed.
Class-level instance variables (i.e. not variables that are static) have a lifetime
that is the same as the lifetime of the object they belong to.
Objects become inaccessible when45 there are no longer any references
pointing to them.
Periodically, C# runs a garbage collector. 18
Program Flow Control
Jun 21, 2024
Are used to alter the natural sequence of execution in a
program.
They act as a direction signal to control the path a program
takes.
The process of performing one statement after another is
called flow of execution or flow of control.
Event Driven Programming
They can be:
Decision statements
Loops.
19
Decision Statements
Jun 21, 2024
Decision statements will help you to conditionally execute
program.
if else:
if (condition)
{
Statements executed if condition is true
Event Driven Programming
}
else
{
Statements executed if condition is false
}
We can also have Else If block in If Else
statements 20
Cont’d…
Jun 21, 2024
Switch Statement:
switch (caseSwitch)
{
case 1:
stmt1 ‘ executed if var = 1;
Event Driven Programming
break;
case 2
stmt2 ‘ executed if var = 2;
break;
default:
stmt3 ‘ executed if var is other than 1 and 2
break;
} 21
Loops
Jun 21, 2024
Are used to execute a code multiple times until a
certain condition occurs.
for loop
for ( init; condition; increment )
Event Driven Programming
{
statement(s);
}
22
Cont’d…
Jun 21, 2024
• Here is the flow of control in a for loop:
The init step is executed first, and only once.
Next, the condition is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and
flow of control jumps to the next statement just after the for loop.
Event Driven Programming
After the body of the for loop executes, the flow of control jumps
back up to the increment statement.
The condition is now evaluated again. If it is true, the loop executes
and the process repeats itself (body of loop, then increment step,
and
23
Cont’d…
Jun 21, 2024
While Statement
The While statement is used to repeat set of
executable statements as long as the condition is
true.
while (condition)
Event Driven Programming
{
Executable Statements
}
In this if the condition is satisfied then the
statements are executed. Else it will not enter the
While condition at all. 24
Cont’d…
Jun 21, 2024
Do ... While Loop Statement
The Do…While Loop Statement is similar to While.
Unlike the while loop the do … while loop will be
executed at least once even if the condition does not
satisfy.
Event Driven Programming
do
{
excutable statements
}while (condition);
25
Arrays
Jun 21, 2024
An Array is a memory location that is used to store
multiple values of the same data types.
All the values in an array are referenced by their
index or subscript number.
These values are called the elements of the array.
Event Driven Programming
The number of elements that an array contains is
called the length of the array.
Arrays can be single or multidimensional.
A single dimensional array is identified by only a
single subscript and an element in a two-dimensional
array is identified by two subscripts. 26
Cont’d…
Jun 21, 2024
The dimension has to be declared before using them in a
program. The array declaration comprises the name of the
array and the number of elements the array can contain.
The Syntax of single dimension array is as follows.
Data_type[] ArrayName = new Data_type[number of elements];
Event Driven Programming
Example:
int[] values = new int[3];
int[] array = {10, 30, 50};
string[,] array = new string[2, 2];
int[,] two = new int[2, 2]; 27
String Manipulation
Jun 21, 2024
Access characters from the beginning, middle, and end of a
string
Replace one or more characters in a string
Insert characters within a string
Search a string for one or more characters
Event Driven Programming
Programming with Microsoft Visual C# .NET
Determining Number of Characters Contained in String
In many applications, it is necessary to determine the
number of characters contained in a string
Use a string’s Length property to determine the number of
characters contained in the string
Syntax of the Length property: string.Length 28
String Manipulation
Jun 21, 2024
Removing Characters from a String
TrimStart method
Remove one or more characters from the beginning of a
string
Syntax: string.TrimStart([trimChars])
Event Driven Programming
TrimEnd method
Remove one or more characters from the end of a string
Syntax: string.TrimEnd([trimChars])
Trim method
Remove one or more characters from both the beginning
and end of a string
Syntax: string.Trim([trimChars]) 29
String Manipulation
Jun 21, 2024
Removing Characters from a String
Functions Description
string.Trim Removes leading and trailing spaces
Event Driven Programming
string.Trim(char) Removes leading and trailing char
string.TrimStart Removes leading spaces
string. TrimStart(char) Removes leading char
string.TrimEnd Removes trailing spaces
string. TrimEnd(char) Removes trailing char
30
String Manipulation
Jun 21, 2024
The Removing Method
Use the Remove method to remove one or more
characters located anywhere in a string
The Remove method returns a string with the
appropriate characters removed
Event Driven Programming
Syntax: string.Remove(startIndex, count)
31
String Manipulation
Jun 21, 2024
Determining Whether a String Begins or Ends
with a Specific Sequence of Characters
StartsWith method
Determine whether a specific sequence of characters
occurs at the beginning of a string
Event Driven Programming
Syntax: string.StartsWith(subString)
EndsWith method
Determine whether a specific sequence of characters
occurs at the end of a string
Syntax: string.EndsWith(subString)
32
String Manipulation
Jun 21, 2024
Accessing Characters Contained in a String
Use the Substring method to access any number of
characters in a string
Syntax: string.Substring(startIndex, count)
startIndex: the index of the first character you want
Event Driven Programming
to access in the string
count (optional): specifies the number of
characters you want to access
33
String Manipulation
Jun 21, 2024
Replacing Characters in a String
Use Replace to replace a sequence of characters in a string
with another sequence of characters
For example:
Replace area code “800” with area code “877” in a phone
Event Driven Programming
number
Replace the dashes in a Social Security number with the
empty string
Syntax: string.Replace(oldValue, newValue)
oldValue is the sequence of characters that you want to
replace in the string
newValue is the replacement characters
34
String Manipulation
Jun 21, 2024
Inserting Characters within a String
Use the Insert method to insert characters
within a string
For example: insert an employee’s middle
initial within his or her name
Event Driven Programming
Syntax: string.Insert(startIndex, value)
startIndex specifies where in the string you want
the value inserted
35
String Manipulation
Jun 21, 2024
Searching a String
Use the IndexOf method to search a string to determine
whether it contains a specific sequence of characters
Syntax: string.IndexOf(value[, startIndex])
value: the sequence of characters for which you are
Event Driven Programming
searching in the string
startIndex: the index of the character at which the search
should begin
For example:
Determine if the ID code “RAMiT” appears in a student
identity card
Determine if the country code “+251” appears in a phone
36
String Manipulation
Jun 21, 2024
Searching a String
Event Driven Programming
37
Methods and Their Types
Jun 21, 2024
A method is a group of statements that together perform a
task.
Every C# program has at least one class with a method
named Main.
To use a method, you need to:
Define the method
Event Driven Programming
Call the method
Defining Methods in C#
When you define a method, you basically declare the
elements of its structure. The syntax for defining a method
in C# is as follows:
38
Cont’d…
Jun 21, 2024
The syntax for defining a method in C# is as follows:
<Access Specifier> <Return Type> <Method Name>(Parameter List)
{
Method Body
}
Following are the various elements of a method:
Access Specifier: determines the visibility of a variable or a method from another
Event Driven Programming
class.
Return type: A method may return a value. The return type is the data type of the
value the method returns. If the method is not returning any values, then the return
type is void.
Method name: Method name is a unique identifier and it is case sensitive. It cannot
be same as any other identifier declared in the class.
Parameter list: Enclosed between parentheses, the parameters are used to pass and
receive data from a method. The parameter list refers to the type, order, and number
of the parameters of a method. Parameters are optional; that is, a method may
contain no parameters.
Method body: contains set of instructions needed to complete required activity 39
Cont’d…
Jun 21, 2024
class NumManip
{
public int FindMax(int num1, int num2)
{ /* local variable declaration */
int result;
Event Driven Programming
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
...
} 40
Cont’d…
Jun 21, 2024
Calling Methods in C# static void Main(string[] args)
public int FindMax(int n1, int n2) {/* local variable definition */
{ int a = 100;
//localvariable declaration int b = 200;
int result; int ret;
if (num1 > num2)
Event Driven Programming
NumManip n = new NumManip();
result = num1; //calling FindMax method
else ret = n.FindMax(a, b);
result = num2; MessageBox.Show("Max value is :"
return result; + ret );
} }
41
Properties and Events
Jun 21, 2024
Every Control has a set of properties, methods and events associated
with it.
Example: Form
Properties
Name (program will use this name to refer)
Text (title of the form),…
Event Driven Programming
Methods
Show
Hide
Close,…
Events
Load
UnLoad,… 42
Event Procedures
Jun 21, 2024
An event is an action, such as the user clicking on a button.
Usually, nothing happens until the user does something and
generates an event.
Structure of an Event Procedure:
private return_type objectName_event(...)
{
Event Driven Programming
statements
}
Example:
private void btnShow_Click(object sender, EventArgs e)
{
int mark = int.Parse(txtMark.Text);
} 43
IntelliSense
Jun 21, 2024
Automatically pops up to give the programmer help.
Event Driven Programming
44
Class and Objects
Jun 21, 2024
Classes
Blue print or template for an object.
Has data members and methods.
Contains the common properties and methods of an object.
Few examples are Car, Person, Animal.
Event Driven Programming
To create a user defined class in VS.NET:
Right click on the project name
Point on ADD
Choose CLASS
45
Cont’d…
Jun 21, 2024
Objects
Instance of a class
Gives life to a class
Examples:
Abebe is an object belonging to the class Person
Event Driven Programming
D4D is an object belonging to the class Car
To create an object of a class
Class_Name obj_Name = new class_Name();
Example:
NumberManipulator n = new NumberManipulator(); 46
Inheritance and Overloading
Jun 21, 2024
Inheritance
Is a relationship where one class is derived from another
existing class, by inheriting all the properties and methods
of the original class called the base class.
It the way of merging functionality from an existing class
Event Driven Programming
into your new subclass.
Employee Class
Examples:
Person Class Student Class
Customer Class
47
Cont’d…
Jun 21, 2024
Implementing Inheritance
Start with an existing/base class from which you
will drive your new class.
Implement one or more subclasses/child classes
based on the base class.
Event Driven Programming
Add new methods, properties and events for the new
class.
You can replace the methods and properties
of the base class with its own new
implementation.
48
Overloading
Jun 21, 2024
–Used to extend the functionality of the base class by
adding methods to the subclass that have the same
name but with different parameter list.
–Example:
public baseClass{ public newClass Inherites
Event Driven Programming
---------------- baseClass{
public showInfo(){ ----------------
----- public showInfo(ByVal x As
} String){
---------------- -----
} } 49
Class Vs Components
Jun 21, 2024
Can be used interchangeably.
A component is really a little more than a regular class, it
supports a graphical designer within the VS.NET IDE.
We can use drag and drop to provide the code in our
Event Driven Programming
component with access to items from the server explorer or
from the toolbox.
To create a user defined class in VS.NET:
Right click on the project name
Point on ADD
Choose COMPONENT
50