You are on page 1of 55

Arba Minch University

Feb 11, 2024


Institute of Technology
Faculty of Computing & Software Engineering

Event Driven

Event Driven Programming


Programming
(SEngc351)
Mr. Addisu M. (Asst. Prof) G5 SE - Regular
1
Feb 11, 2024
Chapter 2

Event Driven Programming


Programming with
Event Driven
2
Outline

Feb 11, 2024


 Using Data Types, Constants, & Variables
 Making Statements in a Program

Event Driven Programming


 Working with Conditional Statements
 Working with Loops
 Working with Arrays
 Working with Strings and Typecasting 3
Language Fundamentals

Feb 11, 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, etc
 C# is also termed an event-driven programming

Event Driven Programming


language because you will write program code that 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
4
General Features of C#

Feb 11, 2024


 It is an object oriented programming language.
 C# has been inspired by earlier OOP languages.
 Provides a quick way to develop heavy duty applications in
a windowing environment.
 It is a useful tool for developing event driven programs.

Event Driven Programming


 Can be used to create both windows and web applications
 C# is case sensitive.
 When a line ends with the ~ character, this tells C# that the
code on that line is not complete.
 Comment can be written by preceding double slash(//)
5
Basic Concepts

Feb 11, 2024


 In order to work with C#, you need to understand some
terminologies as follows.
 Object:
• A thing or an entity in your application.
• Example: forms and controls you place on forms such as

Event Driven Programming


buttons, text boxes, and icons.
 Property:
• describes object behaviors.
• Objects have properties.
• Example: Text, Name, BackColor, Font and Size.
• Refer to a property by the notation called Dot Notation. 6
Basic Concepts

Feb 11, 2024


 Methods:
 are the actions that objects exhibit.
 Example: Show, Hide, Print and Close forms.
 you can refer to a method with the dot notation
 Events:

Event Driven Programming


 actions usually triggered by the system or user such as
clicking a button, key press, mouse mov’ts, etc., or some
occurrence such as system generated notifications
• applications need to respond to events when they occur
• For example, interrupts.
 Example: closing a form can trigger an event. 7
Basic Concepts

Feb 11, 2024


 Class:
 It is a sort of template for an object.
 Example:
• All forms belong to the Form class of object
• All buttons belong to the Button class of object
 include definitions for object properties, methods, and

Event Driven Programming


associated events
 Each new object you create is defined based on its class –
the new object is called a class instance
 Example:
class SampleClass{
// Code goes here
} 8
Basic Concepts

Feb 11, 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.
 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

Event Driven Programming


windows forms class with the name winForm
 Dot Notation
 Used to reference object's properties and methods in code
 Syntax ObjectName.PropertyName/ObjectName.MethodName
 Example:
 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

Feb 11, 2024


Variable
 Memory locations that hold data that can be changed
during program execution.
 has a type that determines what values can be stored
 name can be chosen by programmer in a meaningful way
 can be declared as follows: Data_Type var_Name;

Event Driven Programming


e.g., int i;
 can be initialized at the time of declaration like:
int i = 3;

10
Constants and Variables

Feb 11, 2024


Constant
 Memory locations that hold data that cannot be changed during
program execution.
 Ex: Sales tax percentage, pie (П),…
 to declare constant variables, 'const' keyword should be used before
the Type
 Constants are unchanged during the execution of a program but a

Event Driven Programming


variable may take different values at different times during the
execution of the program.
 can be declared as follows: const Data_Type const_Name;
 e.g., const int months = 12;
const int i=5 ;
const int j=i*5 ; No error
const int m=j*k ; Error
 Note: we can not use non constant value with constant value 11
Naming

Feb 11, 2024


 some rules to chose variable name by the programmer.
 must start with a letter, not a number or other character.
 should not be a keyword.
 can not start with a digits.
 identifier must start with a letter or an underscore
 Upper case and lower case are distinct.
 E.g., variable Height is not the same as height or HEIGHT.

Event Driven Programming


 White space is not allowed
 can be no longer than 255 characters
 can't contain a period
 must be unique within the current procedure or module (this
restriction depends on the scope of the name)

12
Naming

Feb 11, 2024


 Variable and Control Recommended Prefixes
Prefix Variable/Control Example
b Boolean bLightsOn
c Currency cAmount
d Double dAnnualBudget

Event Driven Programming


db Database dbStudent
dt Date+time dtDateDue
i Integer iCounter
l Long lNum
str String strMessage
a Array a_iMyArray
13
Naming

Feb 11, 2024


 Variable and Control Recommended Prefixes
Prefix Variable/Control Example
cbo Combo box cboMyList
chk Check box chkDoctorIn
btn Button btnLogin
frm Form frmMain
fra Frame fraTeams

Event Driven Programming


Hsb/vsb Horizontal/Vertical scroll bar hsbText/vsbCom
img Image imgMain
key Keyboard key keyJ
lbl Label lblLastName
lst List box lstStooges
mnu Menu mnuEdit
txt Text/edit box txtAddress
tmr Timer tmrBreak
14
Variables – Scope & Lifetime

Feb 11, 2024


Scope of Variables
 region of code within which the variable can be accessed
 depends on the types of the variable and place of its declaration
 There are two important scopes in C#:
 Local scope: names defined within a method or a block within a method
 Class-level scope: names defined within the current class
Lifetimes of objects and variables

Event Driven Programming


 Every object and variable in program has lifetime:
 It gets created (or instantiated) at some particular moment in time, and then at
some later time it dies.
 Variables that are defined within a method/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 when there are no longer any references
pointing to them.
 Periodically, C# runs a garbage collector. 15
Data Types

Feb 11, 2024


 specify the size and type of value that can be stored
 There are two types of Data types: Value & Reference Type
 Value type and reference type differ in two ways:
• Where they are stored in the memory.
• How they behave in the context of assignments statements.

Event Driven Programming


16
Data Types

Feb 11, 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'
128-bit precise decimal values with (-7.9 x 1028 to 7.9 x 1028) / 100 to 28 0.0M
decimal 28-29 significant digits

Event Driven Programming


64-bit double-precision floating (+/-)5.0 x 10-324 to (+/-)1.7 x 0.0D
double point type 10308
32-bit single-precision floating point -3.4 x 1038 to + 3.4 x 1038 0.0F
float type
32-bit signed integer type -2,147,483,648 to 2,147,483,647 0
int
64-bit signed integer type -923,372,036,854,775,808 to 0L
long 9,223,372,036,854,775,807
short 16-bit signed integer type -32,768 to 32,767 0 17
Declaration Statements

Feb 11, 2024


 A declaration-statement declares a local variable or constant
 CONST used to declare Named Constants
 Declaration includes
 Name, follow Naming Convention Rules
 Data Type

Event Driven Programming


Required Value for Constants
 Optional Initial Value for Variables
 Example
 String strName, strIdNo;
 Decimal decPayRate = 8.25
 DateTime hireDate;
 Boolean isFound;
 const Decimal PIE = 3.14m;
18
Program Flow Control

Feb 11, 2024


 used to alter the natural sequence of execution
 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
 They can be: Decision statements and Loops
 Decision Statements

Event Driven Programming


 help to conditionally execute program
if else:
if (condition){
Statements executed if condition is true
}
else{
Statements executed if condition is false
}
 can also have else if block in if else statements 19
Program Flow Control

Feb 11, 2024


 Decision Statements
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;
} 20
Program Flow Control

Feb 11, 2024


 Loops
 used to execute a code multiple times until a certain condition occurs
for loop
for (init; condition; increment){
statement(s);
}

Event Driven Programming


While Statement
while (condition){
Executable Statements;
}
Do ... While Statement - Unlike while loop do … while loop will be
executed at least once even if the condition does not satisfy.
do{
excutable statements;
}while (condition); 21
Arrays

Feb 11, 2024


 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


 Number of elements that an array contains is called the
length of the array
 Arrays can be single or multidimensional
• Single dimensional (1D) array is identified by only a single
subscript and
• Element in a two-dimensional (2D) array is identified by
two subscripts 22
Arrays

Feb 11, 2024


 Dimension has to be declared before using them
 Array declaration comprises the name of the array and the
number of elements the array can contain.
 Syntax of single dimension array:
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]; 23
String Manipulation

Feb 11, 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


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
24
String Manipulation

Feb 11, 2024


Removing Characters from a String
 TrimStart method
 Remove one or more characters from the beginning of a
string
 Syntax: string.TrimStart([trimChars])
 TrimEnd method

Event Driven Programming


 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])
25
String Manipulation

Feb 11, 2024


Removing Characters from a String
Functions Description
string.Trim Removes leading and trailing spaces
string.Trim(char) Removes leading and trailing char
string.TrimStart Removes leading spaces
string. TrimStart(char) Removes leading char

Event Driven Programming


string.TrimEnd Removes trailing spaces
string. TrimEnd(char) Removes trailing char

Removing Method
 remove one or more characters located anywhere in a string
 returns a string with the appropriate characters removed
 Syntax: string.Remove(startIndex, count) 26
String Manipulation

Feb 11, 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
 Syntax: string.StartsWith(subString)
 EndsWith method

Event Driven Programming


 Determine whether a specific sequence of characters occurs at the
end of a string
 Syntax: string.EndsWith(subString)
Accessing Characters Contained in a String
 Substring method - to access any # of characters in a string
 Syntax: string.Substring(startIndex, count)
 startIndex: index of the first character you want to access in string
 count (optional): specifies the # of characters you want to access 27
String Manipulation

Feb 11, 2024


Replacing Characters in a String
 Replace method - replace a sequence of characters in a string with
another sequence of characters
 Example: Replace batch code “13” with batch code “16” in a student
identity number
 Syntax: string.Replace(oldValue, newValue)

Event Driven Programming


 oldValue: sequence of characters that you want to replace
 newValue: replacement characters
Inserting Characters within a String
 Insert method - insert characters within a string
 Example: insert student’s middle name within his or her full name
 Syntax: string.Insert(startIndex, value)
 startIndex: specifies where in the string you want the value inserted
28
String Manipulation

Feb 11, 2024


Searching a String
 IndexOf method - to search a string to determine whether
it contains a specific sequence of characters
 Syntax: string.IndexOf(value, [startIndex])
 value: sequence of characters for which you are searching

Event Driven Programming


 startIndex: index of the character at which the search should
begin
 For example:
 Determine if ID code “RAMiT” appears in a student identity card
 Determine if the country code “+251” appears in a phone number

29
Methods and Their Types

Feb 11, 2024


 Method - 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
 Call the method

Event Driven Programming


 Defining Methods in C#
 Syntax for defining a method in C# is as follows:

<Access Specifier> <Return Type> <Method Name>(Parameter List) {


Method Body
}
30
Methods and Their Types

Feb 11, 2024


 Following are the various elements of a method:
 Access Specifier: determines the visibility of a variable or a method
from another class.
 Return type: 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: a unique identifier and it is case sensitive. It cannot be

Event Driven Programming


same as any other identifier declared in the class.
 Parameter list: Enclosed between parentheses, parameters are used to
pass and receive data from a method.
 Parameter list refers to type, order, and number of parameters of a
method
 Parameters are optional; that is, method may contain no parameters.
 Method body: contains set of instructions needed to complete
required activity 31
Methods and Their Types

Feb 11, 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 );
} }

32
Properties and Events

Feb 11, 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,…
33
Event Procedures

Feb 11, 2024


 Event - 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);
}
34
IntelliSense

Feb 11, 2024


 Automatically pops up to give the programmer help.

Event Driven Programming


35
Class and Objects

Feb 11, 2024


Classes
 Blue print or template for an object.
 Contains common properties (data members) and methods of an
object
 Example: Car, Person, Animal.

Event Driven Programming


Objects
 Instance of a class
 Gives life to a class
Examples:
 Abebe is an object belonging to the class Person
 D4D is an object belonging to the class Car
To create an object of a class
Class_Name obj_Name = new class_Name(); 36
Feb 11, 2024
Working with Strings and Typecasting
 Type Casting or Conversion – process to change one data
type value into another data type
 This is only possible if both data types are compatible with
each other else we will get compile time error saying cannot
implicitly convert one type to another type
 In C#, there are two types of casting:

Event Driven Programming


 Implicit Casting (automatically) - converting a smaller type
to a larger type size
char -> int -> long -> float -> double
 Explicit Casting (manually) - converting a larger type to a
smaller size type
double -> float -> long -> int -> char
37
Feb 11, 2024
Working with Strings and Typecasting
 Implicit Casting
• compiler will automatically convert one type to another
• done automatically when passing a smaller to a larger size type
• smaller data types like int (having less memory size) are automatically
converted to larger data types like long (having larger memory size)
• there will be no data loss

Event Driven Programming


• This casting happens when:
• two data types are compatible
• When we assign a value of a smaller data type to a bigger data type
• Example:
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
Console.WriteLine(myInt); // Outputs 9
Console.WriteLine(myDouble); // Outputs 9
38
Feb 11, 2024
Working with Strings and Typecasting
 Explicit Casting
• done manually by placing type in parentheses in front of value
• explicitly convert larger to a smaller data type, explicitly using
cast operator
• there is a chance of data loss or the conversion might not be
succeeded for some reason - an unsafe type of conversion

Event Driven Programming


• larger like double or long (having large memory size) are
converted to smaller data types like int, byte, short, float, etc.
(small memory size)
• Example: double myDouble = 9.78;
int myInt = (int)myDouble; // Manual casting: double to int
Console.WriteLine(myDouble); // Outputs 9.78
Console.WriteLine(myInt); // Outputs 9 39
Feb 11, 2024
Working with Strings and Typecasting
 Type Conversion Methods
• also possible to convert data types explicitly by using built-in
methods, such as Convert.ToBoolean, Convert.ToDouble,
Convert.ToString, Convert.ToInt32 (int)
and Convert.ToInt64 (long):

Event Driven Programming


int myInt = 10;
double myDouble = 5.25;
bool myBool = true;
Console.WriteLine(Convert.ToString(myInt)); // convert int to string
Console.WriteLine(Convert.ToDouble(myInt)); // convert int to double
Console.WriteLine(Convert.ToInt32(myDouble)); // convert double to int
Console.WriteLine(Convert.ToString(myBool)); // convert bool to string 40
Feb 11, 2024
Working with Strings and Typecasting
 Type Conversion using Parse() Method
• In C#, we can also use the built-in Parse() method to
perform type conversion.
• Used to perform type conversion between non-compatible
types like int and string
• Example:

Event Driven Programming


string str1 = "100";
int i = int.Parse(str1); //Converting string to int type
Console.WriteLine("Original String : {str1} and Converted int : {i}");
string str2 = "TRUE";
bool b= bool.Parse(str2); //Converting string to boolean type
Console.WriteLine("Original String : {str2} and Converted bool : {b}"); 41
Feb 11, 2024
Working with Strings and Typecasting
 Type Conversion using Parse() Method
• Like Convert class, at runtime, if the value is not compatible with
destination type, then you will also get a runtime error
• Example: string str1 = "Hello";
int i = int.Parse(str1); //Converting string to int
type

Event Driven Programming


42
Inheritance and Polymorphism
Inheritance
 relationship where one class is derived from another existing
class, by inheriting all the properties and methods of the original
class called base class
 Derived Class (child) - the class that inherits from another class

Intro to Distributed System


 Base Class (parent) - the class being inherited from
 possible to inherit fields and methods
 To inherit from a class, use the : symbol
 class Dog inheriting from the base class Animal
 Dog class can now access fields and methods
of Animal class 43
Inheritance and Polymorphism
Inheritance
 is-a relationship
• In C#, we use inheritance only if there is an is-a relationship
between two classes
• For example,
• Dog is an Animal (can derive Dog from Animal class)

Intro to Distributed System


• Apple is a Fruit (Apple from Fruit class )
• Car is a Vehicle (Car from Vehicle class)
 Types of inheritance

44
Inheritance and Polymorphism
Inheritance
 Types of inheritance
• Single Inheritance Multilevel Inheritance

• Hierarchical Inheritance

Intro to Distributed System


• Multiple - C# doesn't support multiple inheritance

• Hybrid

45
Inheritance and Polymorphism
Inheritance
 Example: Car class (child) inherits from Vehicle class (parent)
class Vehicle // base class (parent) {
public string brand = "Ford"; // Vehicle field
public void honk() // Vehicle method {

Intro to Distributed System


Console.WriteLine("Tuut, tuut!");
}
}
class Car : Vehicle // derived class (child) {
public string modelName = "Mustang"; // Car field
}
46
Inheritance and Polymorphism
Inheritance
 Example: Car class (child) inherits from Vehicle class (parent)
class Program {
static void Main(string[] args) {
// Create a myCar object

Intro to Distributed System


Car myCar = new Car();
// Call the honk() method (From Vehicle class) on myCar object
myCar.honk();
// Display value of the brand field (from Vehicle class) and
// the value of the modelName from the Car class
Console.WriteLine(myCar.brand + " " + myCar.modelName);
}
} 47
Inheritance and Polymorphism
Inheritance
 relationship where one class is derived from another existing class,
by inheriting all the properties and methods of the original class
called base class
 Derived Class (child) - the class that inherits from another class

Intro to Distributed System


 Base Class (parent) - the class being inherited from
 possible to inherit fields and methods from one class to another
Examples: Employee Class

Person Class Student Class

Customer Class
48
Inheritance and Polymorphism
Polymorphism
 poly means “Many,” and morph means “Forms”
• means “Many Forms”
 allows you to create multiple methods with the same name
but different signatures in the same class or in derived
classes

Intro to Distributed System


 There are two types of polymorphism
 Method Overloading
 Method Overriding

49
Inheritance and Polymorphism
Polymorphism
 Method Overloading
• has several names like “Compile Time Polymorphism” or
“Static Polymorphism”
• means creating multiple methods in a class with the same

Intro to Distributed System


names but different/unique signatures (Parameters)
• compiler automatically calls the required method to
check the number of parameters and their type passed
into that method
50
Inheritance and Polymorphism
Polymorphism
 Method Overloading
Example
public int Add(int num1, int num2) {
return (num1 + num2);
}

Intro to Distributed System


public float Add(float num1, float num2) {
return (num1 + num2);
}
public string Add(string value1, string value2) {
return (value1 + " " + value2);
} 51
Inheritance and Polymorphism
Polymorphism
 Method Overriding
• has several names like “Run Time Polymorphism” or
“Dynamic Polymorphism”
• having two methods with the same name and same
signatures [parameters]; one should be in the base class, and

Intro to Distributed System


another should be in a derived class [child class]
• You can override the functionality of base class method to
create the same name method with the same signature in a
derived class
• You can achieve method overriding using inheritance.
• Virtual and Override keywords are used to achieve method
overriding 52
Inheritance and Polymorphism
Polymorphism
 Method Overriding
class BaseClass { Example
public virtual int Add(int num1, int num2) {
return (num1 + num2);
}
}

Intro to Distributed System


class ChildClass: BaseClass {
public override int Add(int num1, int num2) {
if (num1 <= 0 || num2 <= 0) {
Console.WriteLine("Values could not be less than or equals to zero");
Console.WriteLine("Enter First value : ");
num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter Second value : ");
num2 = Convert.ToInt32(Console.ReadLine());
}
return (num1 + num2);
}
} 53
Inheritance and Polymorphism
Polymorphism
 Method Overriding
Example
class Program {
static void Main(string[] args) {
BaseClass baseClassObj = new BaseClass();

Intro to Distributed System


Console.WriteLine("Base class method Add :" + baseClassObj.Add(-3, 8));
baseClassObj = new ChildClass();
Console.WriteLine("Child class method Add :" + baseClassObj.Add(-2,
2));
Console.ReadLine();
}
}

54
Feb 11, 2024
The End!
Questions, Ambiguities,

Event Driven Programming


Doubts, … ???
55

You might also like