How to Empower the future of UX Design with Gen AI
Event Driven programming(ch1 and ch2).pdf
1. Chapter 1: Event Drive Fundamentals:
Introduction:
Program: is sequences of instructions in order to organize the work of
the computer to perform something.
Programming: is the process of creating a set of instructions that tell a
computer how to perform a task.
Everything a computer does is done by using a computer program.
Programming can be done using a variety of computer “languages”.
Example :C#, C++, Java, PHP, Python ..so on.
2. Chapter 1: Event Drive Fundamentals:
What’s an event driven program?:
Is a programming paradigm in which the flow of the program is
determined by events.
That means, what a program does depends on what events have taken
place.
During event driven program, code is executed upon activation of
events.
An event act as a trigger to make the program to do something.
Example: user actions such as mouse clicks, key presses…
3. Chapter 1: Event Drive Fundamentals:
What’s an event driven program?:
Most of the programs are event driven programs, such as GUI
Operating system (windows), spreadsheet etc.
Event driven program can be developed using c#(c sharp),visual
basic,java,java script etc.
4. Chapter 1: Event Drive Fundamentals:
Key features of Event driven program:
1. Form: is a container which group together all the controls(objects)
which a user can use.
Controls: are objects on the form that can have events. Such as
button, menu etc
2. Event loops: is a program which is built into programming language to
keep checking to find out if an event has occurred.
5. Chapter 1: Event Drive Fundamentals:
Key features of Event driven program…
3. Trigger functions: used by event loops to identify which code run when
a particular event happens.
4.Event handlers: piece of code to be run when a particular trigger has
occurred.
6. Chapter 1: Event Drive Fundamentals:
Key features of Event driven program:
When a form is opened, event loop will be run as a background process
of every application.
When we click on a given control of a form, trigger function will be
invoked and identify which code to be run.
7. Chapter 1: Event Drive Fundamentals:
Key features of Event driven program…
Finally, a piece of code which will be identified by trigger function will
be an event handler.
Example: GUI Form(Opened)Event loop(run as back ground
process) Control(clicked from Form)Trigger
function(invoked)Event handler( Handle the event).
8. Chapter 1: Event Drive Fundamentals:
Working in the Programming Environment :
Programming environment: is a working platform which
combines hardware and software that allows a developer to build
applications.
Developers typically work in integrated development environments or
IDEs.
9. Chapter 1: Event Drive Fundamentals:
Working in the Programming Environment …
One of the IDE which can be used as a programming environment is
Visual Studio developed by Microsoft.
Visual Studio offers a great deal of versatility, providing users with an
expansive library of extensions that allows for more customization than
other environments.
10. Chapter 1: Event Drive Fundamentals:
Working in the Programming Environment…
Visual studio environment is well-suited for in-depth projects. But, it
takes a lot of memory to open and run.
One of the programming language which is available for visual studio IDE
is c#(c sharp).
C sharp is an object-oriented programming language provided by
Microsoft that runs on both .NET standards called .NET core and .NET
Framework.
11. Chapter 1: Event Drive Fundamentals:
Working in the Programming Environment…
A framework is a structure that you can build software on it.
It serves as a foundation, so you're not starting entirely from scratch.
Frameworks are typically associated with a specific programming
language and are suited to different types of tasks.
In software development, a framework is designed and tested by other
Software Developers, so you know it's a solid foundation.
A framework in software development is a starting point, but you add
higher-level functionality to it to make it work.
12. Chapter 1: Event Drive Fundamentals:
.NET Core vs. .NET Framework:
.NET core: is a type of .NET Standard which is a free, open-source,
general-purpose development platform to build cloud-based software
applications on Windows, Linux, and macOS .
.NET Framework: is a software development platform for building and
running Windows applications.
We need either of the two platform, depending on the type of project that
we are going to develop.
13. Chapter 1: Event Drive Fundamentals:
How C# Code Gets Compiled and Executed in .NET Framework?:
Step 1: Write a C# code.
Step 2: Compile the code using a C# compiler.
Step 3: Now compiler checks if the code contains an error or not.
14. Chapter 1: Event Drive Fundamentals:
How C# Code Gets Compiled and Executed in .NET Framework?:
In C# there are two types of errors:
Compiler error: Errors that occur when the developer violates the rules
of writing syntax .
Example: missing semicolon, missing parenthesis, etc.
Runtime error: Errors that occur during program execution(run-time)
after successful compilation.
Example: Division by zero.
15. Chapter 1: Event Drive Fundamentals:
How C# Code Gets Compiled and Executed in .NET Framework?:
Step 4: Languages such as Java or C# are not directly converted or
compiled into machine-level language or machine instructions.
These languages need to be converted to an intermediate code first, which
is a half compiled code.
16. Chapter 1: Event Drive Fundamentals:
How C# Code Gets Compiled and Executed in .NET Framework?...
For C#, the source code is converted to an intermediate code which is
known as common intermediate language(CIL) or Intermediate
Language Code (ILC).
This CIL or IL Code can run on any operating system. Because, C# is
a Platform Independent Language.
17. Chapter 1: Event Drive Fundamentals:
How C# Code Gets Compiled and Executed in .NET Framework?:
Step 5: After converting C# source code to Common Intermediate
Language (CIL),the intermediate code needs to be converted to machine
understandable code.
In C#, common language runtime is the basic and Virtual Machine
component of the .NET Framework.
18. Chapter 1: Event Drive Fundamentals:
How C# Code Gets Compiled and Executed in .NET Framework?...
This virtual machine component translates the common intermediate
language to machine understandable code.
This process is called just in time compilation (JIC) or Dynamic
Compilation which is the way of compiling code during the execution of a
program at run time only.
19. Chapter 1: Event Drive Fundamentals:
How C# Code Gets Compiled and Executed in .NET Framework?:
Step 6: Once the C# programs are compiled, they’re physically packaged
into Assemblies.
An assembly is a file that contains one or more namespaces and classes.
20. Chapter 1: Event Drive Fundamentals:
How C# Code Gets Compiled and Executed in .NET Framework?...
As the number of classes and namespaces in program grows, it is
physically separated by related namespaces into separate assemblies.
Assemblies typically have the file extension .exe or .dll, depending on
whether we implement applications or libraries respectively.
Step 7: Now, the C# compiler returns the output of the given c# code.
21. Chapter 1: Event Drive Fundamentals:
How C# Code Gets Compiled and Executed in .NET Framework?:
22. Chapter 1: Event Drive Fundamentals:
Building Your First Application:
The C# programs consist of one or several files with a .cs extension, which
contain definitions of classes and other types.
These files are compiled by the C# compiler (csc) to executable code and
as a result assemblies are created, which are files with the same name but
with a different extension (.exe or .dll).
23. Chapter 1: Event Drive Fundamentals:
Building Your First Application…
Example, if we compile HelloCSharp.cs, we will get a file with the name
HelloCSharp.exe and some additional files will be created as well.
We can run the compiled code like any other program on our computer by
double clicking it.
If we try to execute the compiled C# code on a computer that does not
have the .NET Framework, we will receive an error message.
24. Chapter 1: Event Drive Fundamentals:
Compile and Run C# program on windows using CLI:
Install.NET Framework .
Add C:windowsMicrosoft.NETFrameworkv4.0.xxx to the system
path for executable files.
To compile, write C:windowsMicrosoft.NETFrameworkv4.0.xxx csc
HelloCsharp.cs on CLI.
To execute, write HelloCsharp.exe on CLI.
25. Chapter 1: Event Drive Fundamentals:
Building Your First Application:
using System;
1. namespace FirstApp{ [ a namespace-used for file organization]
2. class First{ [a class-has member(such as instance variable,
methods)]
3. public static void Main(string[] args){
4. Console.WriteLine(“Hello World!!);
}}
}
26. Chapter 1: Event Drive Fundamentals:
Building Your First Application:
Namespaces: in C# namespaces are like a container which holds groups
of classes, other namespace, interface and structure which are logically
related without any specific requirement on how to be placed in the file
system.
Syntax of Namespace:
1. namespace Namespace-Name
2. {
3. //Body of namespace
4. }
27. Chapter 1: Event Drive Fundamentals:
Building Your First Application:
using System;
1. namespace FirstApp { [a namespace-used for file organization]
2. class First{ [a class-has member(such as instance variable,
methods)]
3. public static void Main(string[] args){
4. Assembly assembly = Assembly.GetExecutingAssembly();
5. Console.WriteLine("Entry Point :"+assembly.EntryPoint); [Main
method]
6. Console.WriteLine("Locaton : "+assembly.Location); [Location of a
file]
7. Console.WriteLine("Executable File : " + assembly.CodeBase); [Base
executable file]
8. Console.WriteLine(“Full Name:”+assembly.FullName); } }} [Full
Name]
28. Chapter 1: Event Drive Fundamentals:
Building Your First Application…
An assembly is a file that is automatically generated by the compiler
upon successful compilation of every .NET application.
It can be either a Dynamic Link Library or an executable file.
It is generated only once for an application and upon each subsequent
compilation the assembly gets updated.
The entire process will run in the background of your application; there is
no need for you to learn deeply about assemblies.
29. Chapter 1: Event Drive Fundamentals:
Building Your First Application…
An Assembly contains Intermediate Language (IL) code, which is
similar to Java byte code.
In the .NET language, it consists of metadata.
In addition to metadata, assemblies also have a special file called
Manifest.
It contains information about the current version of the assembly and
other related information.
30. Chapter 1: Event Drive Fundamentals:
Using the intrinsic Controls:
In c#, forms are the foundations you generally use to build programs.
A form is where you put all the things that people interact with as they
use your program.
Those things you put on the form are controls, which enable the people
who use your program to do things, such as enter text and click buttons.
31. Chapter 1: Event Drive Fundamentals:
Using the intrinsic Controls…
Intrinsic Controls: are controls which are visible at the tool box of
visual studio.
Controls which are not visible on toolbox are called extrinsic controls.
The intrinsic controls are available whenever you use c#.
During design time, you can access them from the Toolbox.
Example:
Timer: to perform action in real time without user interaction
OpenFileDialog: used to display dialog box that prompts the user to open
a file etc. we will discuss about these and other control on the coming ch
32. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events:
Fields: are member variables of any type that is declared directly in the
class.
Example:
1. namespace CsharpChapterOne{
2. public class Cat{
3. private string name; //field
4. private string color; //field
5. public static void Main(string[] args){
}}}
33. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
Properties: are members of a class that provides a flexible mechanism to
read, write or compute the value of a private field.
Example:
1. string Name { //Property
2. get{return this.name;}
3. set { this.name = value; }}
4. public string Color{
5. get{ return this.color;} //Property
6. set { this.color = value;}}
34. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
Method: is a basic part of a program.
It can solve a certain problem, eventually take parameters and return
a result.
A method represents all data conversion a program does, to resolve a
particular task.
35. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
Methods consist of the program’s logic.
Moreover they are the place where the “real job” is done.
That is why methods can be taken as a base unit for the whole program.
Method gives us the opportunity, by using a simple block, to build bigger
programs, which resolve more complex and sophisticated problems.
36. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
There are different types of methods in c#. Some of them are:
Call by value method:
value type parameters are passed a copy of the original value to the
method.
It doesn’t modify the original value.
A change made in passed value does not alter the actual value.
37. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
Example: Call by value method:
1. Class test{
2. Static void Change( int a){
3. a=4; Console.WriteLine(a); }
4. Static void Main(string[]args){
5. int n = 12;
6. Change(n); //pass copy of n to change method not n’s address
7. Console.Writeline(n);}
}
38. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
There are different types of methods in c#. Some of them are:
Reference method:
The ref keyword is used to pass and return the reference value.
Any value change that passed as a reference also changes and reflect it.
39. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
Example: Reference method:
1. Class test{
2. Static void Change(ref int a){
3. a=4; Console.WriteLine(a); }
4. Static void Main(string[]args){
5. int n = 12;
6. Change(ref n);
7. Console.Writeline(n);}}
40. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
There are different types of methods in c#. Some of them are:
Out parameter method:
The out keyword is used to pass the argument as out parameter.
It is same as with reference type except that it does not require
initialization before it passes to the method.
It is useful when we need to return multiple values in a method.
41. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
Example: Out parameter method
1. Class test{
2. Static void Change(out int a,out int b){
3. a=4; b=5; Console.WriteLine(a); Console.WriteLine(b); }
4. Static void Main(string[]args){
5. int a = 12;int b; //with out initialization
6. Change(out a,out b);
}}
42. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
There are different types of methods in c#. Some of them are:
Anonymous method:
Is inline unnamed method in the code.
It is created using the delegate keyword and doesn’t require the name
and return type.
43. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
Example: Anonymous method
1. Namespace other{
2. public delegate void print(int vav);
3. public class Anonymous {
4. static void Main(){
5. print p = delegate (int vv){
6. Console.WriteLine(vv); };
7. p(12);
8. Console.ReadLine(); }}}
44. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
Delegate Method:
Delegate is a reference type variable that can hold a reference to the
methods.
It provides a way which tells which method is to be called when an event
is triggered.
Properties about delegate method:
It is a type safe pointer of any method.
Delegates can also be used in anonymous methods invocation.
45. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
Example: Delegate method
1. Namespace abc{
2. public delegate void Delegateprint(int vav);
3. public class Anonymous {
4. public static void print(int a){
5. Console.Writeline(a);}
6. static void Main(){
7. Delegateprint p = new Delegateprin(print);
8. p(12); or p.invoke(12);}}}
46. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
Event: is a notification sent by an object to signal the occurrence of an
action.
The class who raises events is called Publisher, and the class who
receives the notification is called Subscriber.
There can be multiple subscribers of a single event.
Typically, a publisher raises an event when some action occurred.
The subscribers, who are interested in getting a notification when an
action occurred, should register with an event and handle it.
47. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
In C#, an event is an encapsulated delegate. It is dependent on the
delegate.
The delegate defines the signature for the event handler method of the
subscriber class.
48. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
An event can be declared in two steps:
Declare a delegate.
Declare a variable of the delegate with event keyword.
Example:
1. Namespace EventData{
2. public delegate void Notify(); // delegate
3. public class ProcessBusinessLogic{ //This class is called publisher
4. public event Notify ProcessCompleted; }}//ProcessCompleted is custom event of
delegate type Notify using "event" keyword.
49. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
Notify delegate specifies the signature for the ProcessCompleted event
handler.
It specifies that the event handler method in subscriber class must have
a void return type and no parameters.
50. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
Example: Raising an event
public delegate void Notify();{ // delegate
1. public class AA{
2. public event Notify ProcessCompleted; // event creation
3. public void StartProcess() {
4. Console.WriteLine("Process Started!");
5. OnProcessCompleted(); }
6. protected virtual void OnProcessCompleted() {
7. ProcessCompleted.Invoke(); } }
51. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
the StartProcess() method calls the method onProcessCompleted() at
the end, which raises an event.
Typically, to raise an event, protected and virtual method should be
defined with the name On<EventName>.
Protected and virtual enable derived classes to override the logic for
raising the event.
However, A derived class should always call
the On<EventName> method of the base class to ensure that registered
delegates receive the event.
52. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
OnProcessCompleted() method invokes the delegate
using ProcessCompleted.Invoke();.
This will call all the event handler methods registered with
the ProcessCompleted event.
The subscriber class must register to ProcessCompleted event and handle
it with the method whose signature matches Notify delegate.
53. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
Example : Event registration by subscribers
1. class Program { //subscriber class
2. public static void Main() {
3. AA bl = new AA();
4. bl.ProcessCompleted += bl_ProcessCompleted; // register with an event
5. bl.StartProcess(); }
6. public static void bl_ProcessCompleted(){ // event handler
7. Console.WriteLine("Process Completed!"); } }
54. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
Built-in EventHandler Delegate: .NET Framework includes built-in
delegate types EventHandler and EventHandler <TEventArgs> for the
most common events.
Typically, any event should include two parameters: the source of the
event and event data.
Use the EventHandler delegate for all events that do not include event
data.
Use EventHandler <TEventArgs> delegate for events that include data
to be sent to handlers.
55. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
Example: Built-in EventHandler Delegate
1. public class AA{
2. public event EventHandler ProcessCompleted; //event declaration using built-in
EventHandler
3. public void StartProcess() {
4. Console.WriteLine("Process Started!");
5. OnProcessCompleted(EventArgs.Empty);} //No event data
6. protected virtual void OnProcessCompleted(EventArgs e) {
7. ProcessCompleted.Invoke(this, e); } }
56. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
Passing an Event Data: Most events send some data to the subscribers.
The EventArgs class is the base class for all the event data classes.
.NET includes many built-in event data classes such
as SerialDataRecievedEventArgs.
It follows a naming pattern of ending all event data classes with
EventArgs.
You can create your custom class for event data by deriving EventArgs
class.
57. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
Example: Passing an Event Data:
1. namespace EventData{
2. public class ProcessEventArgs :EventArgs{ //creating custom EventArgs
3. public bool IsSuccessful { get; set; }
4. public DateTime CompletionTime { get; set; }
}}
58. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
Example: Passing an Event Data…
1. public class AA{
2. public event EventHandler<ProcessEventArgs> ProcessCompleted; //
event using built-in EventHandler
3. public void StartProcess(){
4. var data = new ProcessEventArgs();
5. data.IsSuccessful = true;
6. data.CompletionTime = DateTime.Now;
7. OnProcessCompleted(data);}
8. protected virtual void OnProcessCompleted(ProcessEventArgs e){
9. ProcessCompleted.Invoke(this, e);}}
59. Chapter 1: Event Drive Fundamentals:
Working with Fields, Properties, Methods, and Events…
Example: Passing an Event Data…
1. class EventMain{
2. public static void Main() {
3. AA bl = new AA();
4. bl.ProcessCompleted += bl_ProcessCompleted; // register an event
5. bl.StartProcess();}
6. public static void bl_ProcessCompleted(object sender, ProcessEventArgs
e) {// event handler
7. Console.WriteLine("Process"+(e.IsSuccessful?"CompletedSuccessfully"
:”failed"));
8. Console.WriteLine("CompletionTime:"+e.CompletionTime.ToLongDate
String());}}
60. End of Chapter 1
Working with Projects in event driven Programming
Group Assignment
1. Make a group of 10 students
2. Select any title
3. Do an event driven project which contains contents of chapter one
61. Chapter 2:Programming with Event Driven
Using Data Types, Constants, and Variables
Data type: is simply the type of data.
In c# we must declare the type of a variable that indicates the kind of
values it is going to store, such as integer, float, decimal, text, etc.
C# mainly categorized data types in two types: Value types and
Reference types.
Value types include simple types (such as int, float, bool, and char),
enum types, struct types, and Nullable value types(data types which can
hold null value).
Reference types include class types, interface types, delegate types,
and array types.
62. Chapter 2:Programming with Event Driven
Using Data Types, Constants, and Variables…
Some c# predefined value types and reference types are:
Type Description Range Suffix
Byte 8 bit unsigned integer 0 to 255
Sbyte 8 bit signed integer -128 to 127
int 32 bit unsigned integer -2,147,483,648 to
2,147,483,647
float 32-bit Single-precision floating
point type
-3.402823e38 to
3.402823e38
f
String A sequence of Unicode characters
Bool 8-bit logical true/false value True or false
object Base type of all other types.
double 64-bit double-precision floating
point type
-1.79769313486232e308 to
1.79769313486232e308
d
63. Chapter 2:Programming with Event Driven
Using Data Types, Constants, and Variables…
From the previous table, each data type (except string and object)
includes value range.
The compiler will give an error if the value goes out of data type's
permitted range.
For example, int data type's range is -2,147,483,648 to 2,147,483,647.
So if you assign a value which is not in this range, then the compiler
would give an error.
64. Chapter 2:Programming with Event Driven
Using Data Types, Constants, and Variables…
The value of unsigned integers, long, float, double, and decimal type
must be suffix by u,l,f,d, and m, respectively.
Example:
1. uint ui = 100u;
2. float fl = 10.2f;
3. long l = 45755452222222l;
4. ulong ul = 45755452222222ul;
5. double d = 11452222.555d;
6. decimal mon = 1000.15m;
65. Chapter 2:Programming with Event Driven
Using Data Types, Constants, and Variables…
The predefined data types are alias to their .NET type name.
Some Example:
Note: that means for example, whether you define a variable of int or Int32,
both are the same.
Alias .NET type Type
byte System.Byte Struct
String System.string Class
Sbyte System.SByte Struct
int System.Int32 Struct
short System.Int16 Struct
long System.Int64 Struct
66. Chapter 2:Programming with Event Driven
Using Data Types, Constants, and Variables…
Every data type has a default value.
Numeric type is 0, boolean has false, and char has '0' as default value.
Use the default(typename) to assign a default value of the data type.
Example:
1. int i = default(int); // 0
2. float f = default(float);// 0
3. decimal d = default(decimal);// 0
4. bool b = default(bool);// false
5. char c = default(char);// '0'
67. Chapter 2:Programming with Event Driven
Using Data Types, Constants, and Variables…
The values of certain data types are automatically converted to different
data types in C#. This is called an implicit conversion.
Conversions from int, uint, long, or ulong to float and from long or
ulong to double may cause a loss of precision.
No data type implicitly converted to the char type.
int type cannot be converted to uint implicitly. It must be specified
explicitly.
Example: int i = 100; uint u = (uint) i;
68. Chapter 2:Programming with Event Driven
Using Data Types, Constants, and Variables…
Variables are the names used for the storage areas that are manipulated
by the programs to obtain various results.
There are different types of variables such as integral, floating-point,
boolean, character etc.
The variable type determines the size and layout of the variable memory.
69. Chapter 2:Programming with Event Driven
Using Data Types, Variables, and constants…
The variable naming conventions in C# are as follows:
A variable should only start with an alphabet or underscore. It should
not start with a digit.
A variable may contain alphabets, digits as well as underscore.
There can be no whitespace in a variable name.
A variable name cannot contain any keywords such as int, const, switch
etc.
70. Chapter 2:Programming with Event Driven
Using Data Types, Constants, and Variables…
Constants in c# program are fixed values that cannot be altered once they
are given.
They can be an integer constant, floating constant, character constant or
string literal.
Constants can be defined using the const keyword.
Syntax: const DataType ConstantName = value;
Example:
const int bb=90; we can’t give other value for bb like bb=88.
71. Chapter 2:Programming with Event Driven
Working with Conditional Statements
Conditional statements: a statement that can be executed based on a
condition is known as a “Conditional Statement”.
The statement is often a block of code.
In c# there are 2 types of conditional statements. Such as
Conditional Branching: this statement allows you to branch your code
depending on whether or not a certain condition is met.
If statements and switch statements are examples of conditional
branching statements.
72. Chapter 2:Programming with Event Driven
Working with Conditional Statements…
The if statement allows you to test whether or not a specific condition is met.
Syntax
If(<Condition>)
<statements>;
Elseif(<Condition>)
<statements>;
Else
<statements>;
73. Chapter 2:Programming with Event Driven
Working with Conditional Statements…
Example: if statement
1. class ifdemo {
2. public static void Main() { int a,b;
3. Console.WriteLine("enter 2 no ");
4. a=Int.Parse (Console.ReadLine());
5. b=Int.Parse(Console.ReadLine());
6. if(a>b) { Console.WriteLine("a is greather"); }
7. else If(a< b) { Console.WriteLine("b is greather"); }
8. else { Console.WriteLine("both are Equals"); }
9. Console.ReadLine(); }
74. Chapter 2:Programming with Event Driven
Working with Conditional Statements…
The switch statement compares two logical expressions.
Syntax
Switch(<Expression>){
Case<Value>:<stmts>Break;
------------------------
Default :
<stmts>Break; }
Note: In the case of the C# Language, using a break after every case block is
mandatory, even for the default.
75. Chapter 2:Programming with Event Driven
Working with Conditional Statements…
Example : Switch statement
1. class Switchdemo { int ch;
2. public void getdata() {
3. Console.WriteLine("choose the following color");
4. ch = int.Parse(Console.ReadLine());
5. switch (ch) {
6. case 1: Console.WriteLine("you choose Red"); break;
7. case 2 : Console.WriteLine("you choose Green"); break;
8. default: Console.WriteLine("you cant choose correct color"); break; }}
9. public static void Main() {
10.Switchdemo obj = new Switchdemo();
11.obj.getdata(); Console.ReadLine(); }}
76. Chapter 2:Programming with Event Driven
Working with Conditional Statements…
Conditional Loops: C# provides 4 loops that allow you to execute a
block of code repeatedly until a certain condition is met; they are:
For Loop,While loop,Do ... While Loop,and Foreach Loop
Each and every loop requires the following 3 things in common.
Initialization: that sets a starting point of the loop
Condition: that sets an ending point of the loop
Iteration: that provides each level, either in the forward or backward
direction
77. Chapter 2:Programming with Event Driven
Working with Conditional Statements…
For Loop: Syntax
For(initializar;conition;iterator)
{
statement
}
78. Chapter 2:Programming with Event Driven
Working with Conditional Statements…
Example: for loop
1. class ForLoop {
2. public void getdata() {
3. for (int i = 0; i <= 50; i++) {
4. Console.WriteLine(i); } }
5. public static void Main() {
6. ForLoop f = new ForLoop();
7. f.getdata();
8. Console.ReadLine(); }}
79. Chapter 2:Programming with Event Driven
Working with Conditional Statements…
While Loop:Syntax
While(Condition)
{
statement
}
80. Chapter 2:Programming with Event Driven
Working with Conditional Statements…
Example : While loop
1. class WhileDemo { int x;
2. public void whiledemo() {
3. while (x <= 50) {
4. Console.WriteLine(x); x++;}}
5. public static void Main() {
6. WhileDemo obj = new WhileDemo();
7. obj.whiledemo();
8. Console.ReadLine(); }}
81. Chapter 2:Programming with Event Driven
Working with Conditional Statements…
Do ... While Loop :Syntax
Do
{
statement
}
While(Condition);
82. Chapter 2:Programming with Event Driven
Working with Conditional Statements…
Example: Do While
1. class DoWhileDemo { int x;
2. public void does() {
3. do { Console.WriteLine(x); x++; }
4. while (x <= 50); }
5. public static void Main() {
6. DoWhileDemo obj = new DoWhileDemo();
7. obj.does();
8. Console.ReadLine(); } }
83. Chapter 2:Programming with Event Driven
Working with Conditional Statements…
In the case of a for and a while loop from the first execution there will be
condition verification.
But in the case of a do .. while, the condition is verified only after the first
execution, so a minimum number of executions occur.
In the case of for and while the minimum number of executions will be
zero whereas it is 1 in the case of a do-while loop.
84. Chapter 2:Programming with Event Driven
Working with Conditional Statements…
Foreach Loop:It is specially designed for accessing the values of an array
and collection.
Syntax
Foreach(type var in collections/Array)
{
statement ;
}
85. Chapter 2:Programming with Event Driven
Working with Conditional Statements
Example:Foreach Loop
1. namespace Loop {
2. class ForEachLoop {
3. public static void Main(string[] args) {
4. char[] myArray = {'H','e','l','l','o'};
5. foreach(char ch in myArray) {
6. Console.WriteLine(ch); } } } }
86. Chapter 2:Programming with Event Driven
Working with Arrays…
Like other programming languages, array in C# is a group of similar types
of elements that have contiguous memory location.
In C#, array is an object of base type System. Array.
In C#, array index starts from 0.
We can store only fixed set of elements in C# array.
Stack memory: stores all local variables and value types
Heap memory: stores all instances and reference types.
Array is a reference type variable which Is stored in heap memory
87. Chapter 2:Programming with Event Driven
Working with Arrays…
Advantages of C# Array
Code Optimization (less code)
Random Access
Easy to traverse/display data
Easy to manipulate data
Easy to sort data etc.
Disadvantages of C# Array
Fixed size
88. Chapter 2:Programming with Event Driven
Working with Arrays…
There are 3 types of arrays in C# programming:
Single Dimensional Array: to create single dimensional array, you need
to use square brackets [] after the type.
You cannot place square brackets after the identifier.
Example:
1. int[] arr = new int[5];//creating array
2. int arr[] = new int[5];//compile time error
3. int[] arr = new int[5]{ 10, 20, 30, 40, 50 };//declaration and initialization
at same time
89. Chapter 2:Programming with Event Driven
Working with Arrays…
Example: Single Dimensional Array
1. public class ArrayExample {
2. public static void Main(string[] args) {
3. int[] arr = new int[5];//creating array
4. arr[0] = 10;//initializing array
5. arr[2] = 20;
6. for (int i = 0; i < arr.Length; i++) { //traversing array
7. Console.WriteLine(arr[i]); }}
}
90. Chapter 2:Programming with Event Driven
Working with Arrays…
C# Multidimensional Arrays
The multidimensional array is also known as rectangular arrays in C#.
It can be two dimensional or three dimensional.
The data is stored in tabular form (row * column) which is also known
as matrix.
To create multidimensional array, we need to use comma inside the
square brackets.
Example:
int[,] arr=new int[3,3];//declaration of 2D array
int[,,] arr=new int[3,3,3];//declaration of 3D array (Block, row and column size)
91. Chapter 2:Programming with Event Driven
Working with Arrays…
Memory allocation of Multi dimensional array(2 D)
Base Address
Memory address value Index
40000 23 Aa[0,0]
40004 12 Aa[0,1]
40008 4 Aa[0,2]
40012 5 Aa[1,0]
40016 1 Aa[1,1]
40020 60 Aa[1,2]
40024 8 Aa[2,0]
40028 7 Aa[2,1]
40032 3 Aa[2,2]
92. Chapter 2:Programming with Event Driven
Working with Arrays…
Example: Multi Dimensional Array
1. public class MultiArrayExample {
2. public static void Main(string[] args) {
3. int[,] arr=new int[3,3];//declaration of 2D array
4. arr[0,1]=10;//initialization
5. arr[1,2]=20;
6. for(int i=0;i<3;i++){ //traversal
7. for(int j=0;j<3;j++){
8. Console.Write(arr[i,j]+" "); }
9. Console.WriteLine(); }}}
93. Chapter 2:Programming with Event Driven
Working with Arrays …
Jagged Arrays: in C#, jagged array is also known as "array of arrays"
because its elements are arrays.
The element size of jagged array can be different.
Declaration of jagged array:
int[][] arr = new int[2][];
Declaration and Initialization of jagged array at same time:
arr[0] = new int[4] { 11, 21, 56, 78 };
94. Chapter 2:Programming with Event Driven
Working with Arrays…
Memory allocation of Jagged array in heap memory
95. Chapter 2:Programming with Event Driven
Working with Arrays…
Example: Jagged array
1. public class JaggedArrayTest {
2. public static void Main() {
3. int[][] arr = new int[3][]{ //initialization upon declaration
4. new int[] { 11, 21, 56, 78 },
5. new int[] { 2, 5, 6, 7, 98, 5 },
6. new int[] { 2, 5 }
7. };
8. for (int i = 0; i < arr.Length; i++) { // Traverse array elements
9. for (int j = 0; j < arr[i].Length; j++) { arr[i]=length of single row
10. System.Console.Write(arr[i][j]+" "); }
11. System.Console.WriteLine(); }}}
96. Chapter 2:Programming with Event Driven
Working with Strings and Typecasting
In C#, string is an object of System.String class that represent sequence
of characters.
We can perform many operations on strings such as concatenation,
comparison, substring, replacement etc.
In C#, string is keyword which is an alias for System.String class.
That is why string and String are equivalent.
string s1 = "hello";//creating string using string keyword
String s2 = "welcome";//creating string using String class
97. Chapter 2:Programming with Event Driven
Working with Strings and Typecasting …
Example:
1. public class StringExample {
2. public static void Main(string[] args) {
3. string s1 = "hello";
4. char[] ch = { 'c', 's', 'h', 'a', 'r', 'p' };
5. string s2 = new string(ch); //object creation
6. Console.WriteLine(s1);
7. Console.WriteLine(s2); }}
98. Chapter 2:Programming with Event Driven
Working with Strings and Typecasting
There are different types of C# String methods, Such as
Compare(first String, second String):used to compares two specified
String objects based on their alphabetical order.
It returns an integer that indicates their relative position in the sort
order.
If both strings are equal, it returns 0.
If first string is greater than second string, it returns 1
If first string is less than second string, it returns -1.
99. Chapter 2:Programming with Event Driven
Working with Strings and Typecasting
Example: Compare(first string, second string):
1. public class StringExample {
2. public static void Main(string[] args) {
3. string s1 = "hello";
4. string s2 = "csharp";
5. Console.WriteLine(string.Compare(s1,s2)); }}
Note: Compare() is static method.
100. Chapter 2:Programming with Event Driven
Working with Strings and Typecasting
There are different types of C# String methods, Such as
Concat(first String,second String): used to concatenate two specified
instances of String.
There are many overloaded methods of Concat().
Example:
1. public class StringExample {
2. public static void Main(string[] args) {
3. string s1 = "Hello "; string s2 = "C#";
4. Console.WriteLine(string.Concat(s1,s2)); }}
101. Chapter 2:Programming with Event Driven
Working with Strings and Typecasting
There are different types of C# String methods, Such as
Substring(int start index, int length): used to retrieve a substring from
this instance.
The substring starts at a specified character position and continues to the
end of the string.
102. Chapter 2:Programming with Event Driven
Working with Strings and Typecasting
There are different types of C# String methods, Such as
Example: Substring(int index, int length):
1. public class StringExample {
2. public static void Main(string[] args) {
3. string s1 = "Hello C Sharp";
4. string s2 = s1.Substring(5);
5. Console.WriteLine(s2); }}
103. Chapter 2:Programming with Event Driven
Working with Strings and Typecasting
There are different types of C# String methods, Such as
Replace() method: is used to get a new string in which all occurrences of
a specified Unicode character in this string are replaced with another
specified Unicode character.
Signature:
public string Replace(Char first, Char second)
public string Replace(String firstString, String secondString)
104. Chapter 2:Programming with Event Driven
Working with Strings and Typecasting
There are different types of C# String methods, Such as
Example: Replace():
1. public class StringExample {
2. public static void Main(string[] args) {
3. string s1 = "Hello C#, Hello .Net, Hello Javatpoint";
4. string s2 = s1.Replace("Hello","Cheers");
5. Console.WriteLine(s2); }}
Output: Cheers C#, Cheers .Net, Cheers Javatpoint";
105. Chapter 2:Programming with Event Driven
Working with Strings and Typecasting
Type casting: is a way of converting one data type to another type.
In C#, there are two types of casting:
Implicit Casting (automatically) :converting a smaller type to a larger
type size.
char to int to long to float to double (long=8,float=4)
Explicit Casting (manually) :converting a larger type to a smaller size
type.
double to float to long to int to char
Note: to get the size of data type use sizeof().sizeof(int),sizeof(double) etc.
106. Chapter 2:Programming with Event Driven
Working with Strings and Typecasting
It is also possible to convert data types explicitly by using built-in
methods, such as
Convert.ToBoolean(data type),
Convert.ToDouble(Convert.ToBoolean(data type),
Convert.ToString(Convert.ToBoolean(data type),
Convert.ToInt32 (data type)
(Convert.ToBoolean(data type)
Convert.ToInt64 (Convert.ToBoolean(data type)
107. Chapter 2:Programming with Event Driven
Working with Strings and Typecasting
1. Example: Type casting:
2. public class Casting {
3. public static void Main(string[] args) {
4. int value1=8; long value2=value1; ,double value3=4.6;
5. Console.WriteLine(value2); //Implicit casting
6. bool myBool = true;
7. Console.WriteLine(Convert.ToString(myBool)); //Casting using method
8. int value4 = (int)value3; }} //Explicit Casting