SlideShare a Scribd company logo
Berhanu Fetene (MSc.)
Chapter Two:
C# (C-sharp) programming language
5/5/2021 1
C# Programming
īƒ˜ C# is an object-oriented programming language.
īƒ˜ In Object-Oriented Programming methodology, a program consists of various
objects that interact with each other by means of actions.
īƒ˜ The actions that an object may take are called methods.
īƒ˜ Objects of the same kind are said to have the same type or are said to be in the
same class.
īƒ˜ C# is case sensitive
īƒ˜ All statements and expression must end with a semicolon(;).
īƒ˜ The program execution starts at the main method.
īƒ˜ Unlike Java, program file name could be different from the class name.
5/5/2021 2
C# Program Structure
īƒ˜ A C# program consists of the following parts:
īƒŧ Namespace declaration
īƒŧ A class
īƒŧ Class methods
īƒŧ Class attributes
īƒŧ A main method
īƒŧ Statements and expressions
īƒŧ Comments (optional)
5/5/2021 3
7
Sample C# program:
using System;
class HelloCSharp
{
static void Main()
{
Console.WriteLine("Hello, C#");
}
}
C# Code – How It Works?
using System;
class HelloCSharp
{
static void Main()
{
Console.WriteLine("Hello, C#");
}
}
Include the standard
namespace "System"
Define a class called
"HelloCSharp"
Define the Main()
method – the
program entry point
8
Print a text on the console by calling
the method "WriteLine" of the class
"Console"
C# Code Should Be Well
Formatted
using System;
class HelloCSharp
{
s
st
ta
at
ti
ic
c v
vo
oi
id
d M
Ma
ai
in
n(
()
)
{
{
C
Co
on
ns
so
ol
le
e.
.W
Wr
ri
it
te
eL
Li
in
ne
e(
("
"H
He
el
ll
lo
o,
, C
C#
#"
")
);
;
}
}
}
The {symbol should be
alone on a new line.
The block after the
{symbol should be
indented by a TAB.
The }symbol should be
under the
corresponding {.
Class names should use PascalCaseand
start with a CAPITALletter.
9
Important features of C#
īƒ˜ It is important to note the following points:
īƒŧ C# is case sensitive.
īƒŧ All statements and expression must end with a semicolon (;).
īƒŧ The program execution starts at the Main method.
īƒŧ Unlike Java, program file name could be different from the class name.
Compiling and Executing the Program
īƒŧ If you are using Visual Studio. Net for compiling and executing C# programs,
take the following steps:
īƒŧ Start Visual Studio.
īƒŧ On the menu bar, choose File -> New -> Project.
5/5/2021 7
Compiling and Executing the Program (Cont’d)
īƒ˜ Choose Visual C# from templates, and then choose Windows.
īƒ˜ Choose Console Application.
īƒ˜ Specify a name for your project and click OK button. This creates a new
project in Solution Explorer.
īƒ˜ Write code in the Code Editor.
īƒ˜ Click the Run button or press F5 key to execute the project.
īƒ˜ A Command Prompt window appears that contains the line H
He
el
ll
lo
o,
, C
C#
#"
“.
5/5/2021 8
īƒ˜ The variables in C#, are categorized into one of the following three categories:
īƒŧ Value types
īƒŧ Refence types
īƒŧ Pointer types
1. Value Type
īƒ˜ Value type variables can be assigned a value directly.
īƒ˜ They are derived from the class System.ValueType.
īƒ˜ The value types directly contain data.
5/5/2021 9
Data Types
īƒ˜ Some examples are int, char, and float which stores numbers, alphabets, and
floating point numbers respectively.
īƒ˜ When you declare an int type, the system allocates memory to store the value.
īƒ˜ The following table lists the available value types in C# .
5/5/2021 10
Data Types (Cont’d)
Type Represent 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-29
significant digits
(-7.9 x 1028
to 7.9 x 1028
)
/ 100
to 1028 0.0M
5/5/2021 11
Data Types (Cont’d)
Type Represent Range Default Value
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
9,223,372,036,854,775,807
0L
sbyte 8-bit signed integer type -128 to 127 0
short 16-bit signed integer type -32,768 to 32,767 0
uint 16-bit signed 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
īƒ˜ To get the exact size of a type or a variable on a particular platform, you can
use the sizeof method.
īƒ˜ The expression sizeof(type) yields the storage size of the object or type in
bytes.
īƒ˜ The following is an example to get the size of data types we defined in the
above tables.
5/5/2021 12
Data Types (Cont’d)
5/5/2021 13
using System;
namespace DataTypeSize{
class Program{
static void Main(string[] args){
Console.WriteLine("Size of bool is : {0}", sizeof(bool));
Console.WriteLine("Size of byte is : {0}", sizeof(byte));
Console.WriteLine("Size of char is : {0}", sizeof(char));
Console.WriteLine("Size of decimal is : {0}", sizeof(decimal));
Console.WriteLine("Size of float is : {0}", sizeof(float));
Console.WriteLine("Size of int is : {0}", sizeof(int));
Console.WriteLine("Size of long is : {0}", sizeof(long));
Console.WriteLine("Size of sbyte is : {0}", sizeof(sbyte));
Console.WriteLine("Size of short is : {0}", sizeof(short));
Console.WriteLine("Size of uint is : {0}", sizeof(uint));
Console.WriteLine("Size of ulong is : {0}", sizeof(ulong));
Console.WriteLine("Size of ushort is : {0}", sizeof(ushort));
Console.ReadKey();
}}}
5/5/2021 14
īƒ˜ When the above code is compiled and executed, it produces the following
result:
Size of bool is : 1
Size of byte is : 1
Size of char is : 2
Size of decimal is : 16
Size of float is : 4
Size of int is : 4
Size of long is : 8
Size of sbyte is : 1
Size of short is : 2
Size of uint is : 4
Size of ulong is : 8
Size of ushort is : 2
5/5/2021 15
2. Refence Type
īƒ˜ The reference types do not contain the actual data stored in a variable, but
they contain a reference to the variables.
īƒ˜ In other words, they refer to a memory location.
īƒ˜ Using multiple variables, the reference types can refer to a memory location.
īƒ˜ If the data in the memory location is changed by one of the variables, the
other variable automatically reflects this change in value.
īƒ˜ Example of built-in reference types are: object, dynamic, and string.
Data Types (Cont’d)
5/5/2021 16
A. Object Type
īƒ˜ The Object Type is the ultimate base class for all data types in C# Common
Type System (CTS). Object is an alias for System.Object class.
īƒ˜ The object types can be assigned values of any other types, value types,
reference types, predefined or user-defined types.
īƒ˜ However, before assigning values, it needs type conversion.
īƒ˜ When a value type is converted to object type, it is called boxing and on the
other hand, when an object type is converted to a value type, it is called
unboxing. Example:
Reference Types (Cont’d)
object obj;
obj = 100; // this is boxing
5/5/2021 17
B. Dynamic Type
īƒ˜ You can store any type of value in the dynamic data type variable.
īƒ˜ Type checking for these types of variables takes place at run-time.
īƒ˜ Syntax for declaring a dynamic type is:
īƒ˜ For example:
īƒ˜ Dynamic types are similar to object types except that type checking for object
type variables takes place at compile time, whereas that for the dynamic type
variables takes place at run time.
Reference Types (Cont’d)
dynamic number = 100;
dynamic <variable_name> = value;
5/5/2021 18
B. Dynamic Type
īƒ˜ The String Type allows you to assign any string values to a variable.
īƒ˜ The string type is an alias for the System.String class.
īƒ˜ It is derived from object type.
īƒ˜ The value for a string type can be assigned using string literals in two forms:
quoted and @quoted.
īƒ˜ For example:
īƒ˜ A @quoted string literal looks as follows:
īƒ˜ The user-defined reference types are: class, interface, or delegate. We will
discuss these types in later chapter in details.
Reference Types (Cont’d)
string name= “Rift Valley University";
@“Rift Valley University";
5/5/2021 19
2. Pointer Type
īƒ˜ Pointer type variables store the memory address of another type.
īƒ˜ Pointers in C# have the same capabilities as the pointers in C or C++.
īƒ˜ Syntax for declaring a pointer type is:
īƒ˜ For example:
īƒ˜ We will discuss more about pointer types in the subsections.
Data Types (Cont’d)
type* identifier;
char* cptr;
int* iptr;
īƒ˜ Keywords are reserved words predefined to the C# compiler.
īƒ˜ These keywords cannot be used as identifiers.
īƒ˜ However, if you want to use these keywords as identifiers, you may prefix
them with the @ character.
īƒ˜ In C#, some identifiers have special meaning in context of code, such as get
and set, these are called contextual keywords.
īƒ˜ The following TABLE lists the reserved keywords and contextual keywords
in C# .
5/5/2021 20
C# Keywords
5/5/2021 21
Reserved Keywords
abstract as base bool break byte case
catch char checked class const continue decimal
default delegate do double else enum event
explicit extern false finally fixed float for
foreach goto if implicit in volatile int
interface internal is lock long namespace new
null object operator out private override params
protected public readonly ref return sbyte while
sealed short sizeof stackalloc static string struct
switch this throw true try typeof uint
ulong unchecked unsafe ushort using virtual void
5/5/2021 22
Contextual Keywords
add alias ascending descending dynamic
from get global group into
join let orderby partial (type)
partial (method) remove select set
Identifiers
5/5/2021 23
īƒ˜ An identifier is a name used to identify a class, variable, function, or any
other user-defined item.
īƒ˜ The basic rules for naming identifiers in C# are as follows:
īƒŧ A name must begin with a letter that could be followed by a sequence of letters,
digits (0 - 9), or underscore.
īƒŧ The first character in an identifier cannot be a digit.
īƒŧ It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ]
{ } . ; : " ' / and .
īƒŧ However, an underscore ( _ ) can be used.
īƒŧ It should not be a C# keyword.
digit.
C# Variables
5/5/2021 24
īƒ˜ A variable is a name given to a storage area that is used to store values of
various data types.
īƒ˜ Each variable in C# needs to have a specific type, which determines the size
and layout of the variable's memory.
īƒ˜ Based on the data type, specific operations can be carried out on the variable.
īƒ˜ One can declare multiple variables in a program.
īƒ˜ Example1: // age is variable that can store integer value.
// value 30 is assigned to variable age which is declared
before.
Example2: //mulptiple variable declaration
int age;
age =30;
int length, width, area;
C# Operators
5/5/2021 25
1. Arithmetic Operators
īƒ˜ are operators used for performing mathematic operations on numbers.
īƒ˜Below is the list of arithmetic operators available in C#.
Operator Description
+ Adds two operands
- Subtracts the second operand from the first
* Multiplies both operands
/ Divides the numerator by de-numerator
% Modulus Operator and a remainder of after an integer division
++ Increment operator increases integer value by one
-- Decrement operator decreases integer value by one
5/5/2021 26
// C# code to demonstrate the use of arithmetic operators
using System;
namespace ArithmeticOperator{
class Program {
static void Main(string[] args){
int a = 30, b=5;
Console.WriteLine("Sum of a and b is : {0}", a + b);
Console.WriteLine("Difference of a and b is : {0}", a - b);
Console.WriteLine("Product of a and b is : {0}", a * b);
Console.WriteLine("quetient of a and b is : {0}", a / b);
Console.WriteLine("Remander of a and b is : {0}", a % b);
Console.WriteLine("Incerement of a by 1 is : {0}", ++a); // pre-increment
Console.WriteLine("Decrement of b by 1 is : {0}", --b); // post-decrement
Console.WriteLine("Incerement of a by 1 is : {0}", a++); // post-increment
Console.WriteLine("Decrement of b by 1 is : {0}", b--); // post-decrement
Console.WriteLine("Press any key to continue ...");
Console.ReadKey();
} }}
5/5/2021 27
Sum of a and b is : 35
Difference of a and b is : 25
Product of a and b is : 150
quotient of a and b is : 6
Reminder of a and b is : 0
Increment of a by 1 is : 31
Decrement of b by 1 is : 4
Increment of a by 1 is : 31
Decrement of b by 1 is : 4
Press any key to continue ...
īƒ˜ When the above code is compiled and executed, it produces the following
result:
C# Operators(Cont’d)
5/5/2021 28
2. Relational Operators
īƒ˜ These are operators used for performing Relational operations on numbers.
īƒ˜ Below is the list of relational operators available in C#.
Operator Description
== Checks if the values of two operands are equal or not, if yes then condition becomes true.
!= Checks if the values of two operands are equal or not, if values are not equal then condition
becomes true.
> Checks if the value of left operand is greater than the value of right operand, if yes then
condition becomes true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition
becomes true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes
then condition becomes true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes
then condition becomes true.
5/5/2021 29
// C# code to demonstrate the use of Relational Operators
using System;
namespace RelationalOperator{
class Program{
static void Main(string[] args){
int a = 30, b = 5;
Console.WriteLine(" a is equal to b {0}", a==b);
Console.WriteLine(" a is not equal to b {0}", a!= b);
Console.WriteLine(" a is greater than b {0}", a>b);
Console.WriteLine(" a is less than b {0}", a<b);
Console.WriteLine(" a is greater than or equal to b {0}", a>=b);
Console.WriteLine(" a is less than or equal to b {0}", a<=b);
Console.WriteLine("Press any key to continue ...");
Console.ReadKey();
}}}
5/5/2021 30
a is equal to b False
a is not equal to b True
a is greater than b True
a is less than b False
a is greater than or equal to b True
a is less than or equal to b False
Press any key to continue ...
īƒ˜ When the above code is compiled and executed, it produces the following
result:
C# Operators (Cont’d)
5/5/2021 31
3. Logical Operators
īƒ˜ These are operators used for performing Logical operations on values.
īƒ˜ Below is the list of logical operators available in C#.
Operator Description
&& This is the Logical AND operator. If both the operands are
true, then condition becomes true.
|| This is the Logical OR operator. If any of the operands are
true, then condition becomes true.
! This is the Logical NOT operator.
5/5/2021 32
// C# code to demonstrate the use of Logical Operators
using System;
namespace RelationalOperator{
class Program{
static void Main(string[] args){
int a = 30, b = 5;
bool c = false;
Console.WriteLine(" Logical AND {0}", (a == b)&&(a!=b));
Console.WriteLine(" Logical OR {0}", (a != b)||(a>b));
Console.WriteLine(" Logical Negation {0}", !(c));
Console.WriteLine("Press any key to continue ...");
Console.ReadKey();
}}}
5/5/2021 33
īƒ˜ When the above code is compiled and executed, it produces the following
result:
Logical AND False
Logical OR True
Logical Negation True
Press any key to continue ...
5/5/2021 34
īƒ˜ An enumeration is used in any programming language to define a constant set
of values.
īƒ˜ For example, the days of the week can be defined as an enumeration and used
anywhere in the program.
īƒ˜ In C#, the enumeration is defined with the help of the keyword 'enum’.
īƒ˜ enum is a value type data type. The enum is used to declare a list of named
integer constants.
C# Enum Syntax:
enum enum_name{enumeration list}
īƒ˜ The enum is used to give a name to each constant so that the constant integer
can be referred using its name.
īƒ˜ In our example, we will define an enumeration called days, which will be
used to store the days of the week.
C# Enumeration
5/5/2021 35
// C# code to demonstrate the use of enumeration.
using System;
namespace Enumeration{ // enum declaration
enum days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } ;
class Program{
static void Main(string[] args){
Console.WriteLine("Value of Monday is " + (int)days.Monday);
Console.WriteLine("Value of Tuesday is " + (int)days.Tuesday);
Console.WriteLine("Value of Wednesday is " + (int)days.Wednesday);
Console.WriteLine("Value of Thursday is " + (int)days.Thursday);
Console.WriteLine("Value of Friday is " + (int)days.Friday);
Console.WriteLine("Value of Saturday is " + (int)days.Saturday);
Console.WriteLine("Value of Sunday is " + (int)days.Sunday);
Console.WriteLine("Press any key to continue ...");
Console.ReadKey();
}}}
5/5/2021 36
īƒ˜ When the above code is compiled and executed, it produces the following
result:
Value of Monday is 0
Value of Tuesday is 1
Value of Wednesday is 2
Value of Thursday is 3
Value of Friday is 4
Value of Saturday is 5
Value of Sunday is 6
Press any key to continue ...
Conditional Statements
5/5/2021 37
1. if statement
īƒ˜In c#, if statement or condition is used to execute the block of code or
statements when the defined condition is true.
īƒ˜Generally, in c# the statement that can be executed based on the condition is
known as a “Conditional Statement” and the statement is more likely a block
of code.
īƒ˜Syntax of C# if Statement:
īƒ˜The statements inside of if condition will be executed only when the
“expression” returns true otherwise the statements inside of if condition will
be ignored for execution.
if (expression) {
// Statements to Executed if condition is true
}
5/5/2021 38
īƒ˜ Following is the example of defining if statement in c# programming language to execute
the block of code or statements based on expression.
// C# code to demonstrate if statement.
using System;
namespace IfStatement{
class Program{
static void Main(string[] args){
int x = 20;
if(x>0)
Console.WriteLine(" x is positve number ");
Console.WriteLine(" Press any key to Exit...");
Console.ReadKey();
}}}
x is positve number
Press any key to Exit...
īƒ˜ When this code is compiled and executed,
it produces the following result:
Conditional Statements (Cont’d)
5/5/2021 39
2. if-else statement
īƒ˜In c#, if-else statement or condition is having an optional else statements and
these else statements will be executed whenever the if condition is fails to
execute.
īƒ˜ Generally, in c# if-else statement, whenever the expression returns true,
then if statements will be executed otherwise else block of statements will be
executed.
īƒ˜Syntax of C# if-else Statement
if (expression){
// Statements to Executed if expression is True
}
else {
// Statements to Executed if expression is False
}
5/5/2021 40
// C# code to demonstrate if-else statement
using System;
namespace IfElse{
class Program{
static void Main(string[] args){
int x = -20;
if(x>0)
Console.WriteLine(" x is Positve number ");
else
Console.WriteLine(" x is Negative number ");
Console.WriteLine(" Press any key to Exit...");
Console.ReadKey();
}}}
When this code is compiled and executed, it produces the following result:
x is Negative number
Press any key to Exit...
5/5/2021 41
3. if-else if statement (nested if-else statement)
īƒ˜In c#, if-else-if statement or condition is used to define multiple conditions
and execute only one matched condition based on our requirements.
īƒ˜Generally, in c# if statement or if-else statement is useful when we have a
one condition to validate and execute the required block of statements.
īƒ˜In case, if we have a multiple conditions to validate and execute only one
block of code, then if-else-if statement is useful.
Conditional Statements (Cont’d)
5/5/2021 42
īƒ˜Syntax of C# if Statement:
if (condition_1){
// Statements to Execute if condition_1 is True
}
else if (condition_2){
// Statements to Execute if condition_2 is True
}
....
else{
// Statements to Execute if all conditions are False
}
īƒ˜Syntax of C# if-else if Statement:
īƒ˜ The execution of if-else-if statement will starts from top to bottom and as soon as the
condition returns true, then the code inside of if or else if block will be executed and
control will come out of the loop.
īƒ˜ In case, if none of the conditions return true, then the code inside of else block will be
executed.
5/5/2021 43
// C# code to demonstrate nested if-else statement
using System;
namespace NestedIfElse{
class Program{
static void Main(string[] args){
int x = 0;
if(x>0)
Console.WriteLine(" x is Positve number ");
else if (x==0)
Console.WriteLine(" x is Zero ");
else
Console.WriteLine(" x is Negative number ");
Console.WriteLine(" Press any key to Exit...");
Console.ReadKey();
}}}
x is Negative number
Press any key to Exit...
When this code is compiled and executed, it
produces the following result:
5/5/2021 44
3. C# Ternary Operator (?:)
īƒ˜In c#, Ternary Operator (?:) is a decision making operator and it is a substitute of if-else-
if statement in c# programming language.
īƒ˜ By using Ternary Operator, we can replace multiple lines of if-else-if statement code into
single line in c# programming language.
īƒ˜ The Ternary operator we will help you to execute the statements based on the defined
conditions using decision making operator (?:).
īƒ˜In c#, the Ternary Operator will always work with 3 operands.
īƒ˜ Syntax of C# Ternary Operator:
īƒ˜In Ternary Operator, the condition expression must be evaluated to either true or false.
If condition is true, the first_expression result returned by the ternary operator.
īƒ˜In case, if condition is false, then the second_expression result returned by the operator.
Conditional Statements (Cont’d)
condition_expression ? first_expression : second_expression;
5/5/2021 45
x value less than y
Press any key to Exit...
// C# code to demonstrate C# Ternary Operator (?:)
using System;
namespace TernaryOperator{
class Program{
static void Main(string[] args){
int x =10, y=20;
string result;
result = (x > y) ? "x value greater than y" : (x < y) ? "x value less than y" : "x value equals to y";
Console.WriteLine(result);
Console.WriteLine(" Press any key to Exit...");
Console.ReadKey();
}}} īƒ˜ When this code is compiled and executed, it
produces the following result:
5/5/2021 46
4. Switch statement
īƒ˜In c#, Switch is a selection statement and it will execute a single case
statement from the list of multiple case statements based on the pattern match
with the defined expression.
īƒ˜ By using switch statement in c#, we can replace the functionality if –else if
statement to provide a better readability for the code.
īƒ˜Generally, in c# switch statement is a collection of multiple case statements
and it will execute only one single case statement based on the matching value
of expression.
Conditional Statements (Cont’d)
5/5/2021 47
switch(variable/expression){
case value1:
// Statements to Execute
break;
case value2:
//Statements to Execute
break;
....
default:
// Statements to Execute if No Case Matches
break;
}
Syntax of C# Switch Statement
5/5/2021 48
// C# code to demonstrate switch statement
using System;
namespace SwitchStatement{
class Program{
static void Main(string[] args){
char op;
int a=20, b=10;
int result=0;
Console.WriteLine("Enter an operator");
op = (char)Console.Read();
//op = Console.ReadLine();
switch (op){
case '+':
result = a + b;
Console.WriteLine("Sum of a and b is :{0} ",result);
break;
case '-':
result = a - b;
Console.WriteLine("Difference of a and b is :{0} ", result);
break; //code continue on the next pageâ€Ļ..
.
Enter an operator
+
Sum of a and b is :30
Press any key to exit...
īƒ˜ When this code is compiled and executed,
it produces the following result:
5/5/2021 49
case '*':
result = a * b;
Console.WriteLine("Product of a and b is :{0} ", result);
break;
case '/':
result = a / b;
Console.WriteLine("Quetient of a and b is :{0} ", result);
break;
case '%':
result = a % b;
Console.WriteLine("Remiender of a and b is :{0} ", result);
break;
default:
Console.WriteLine("Invalid Operator");
break;
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}}}
5/5/2021 50
īƒ˜Looping statement are the statements execute one or more statement
repeatedly several number of times.
1. For Loop
īƒ˜for loop is useful to execute a statement or a group of statements repeatedly
until the defined condition returns true.
īƒ˜Generally, for loop is useful in c# applications to iterate and execute the
certain block of statements repeatedly until the specified number of times.
īƒ˜Syntax of C# For Loop
Looping Statements
for(initialization; test-condition; iterator(increment/decrement)){
//statements to execute
}
5/5/2021 51
1 2 3 4 5 6 7 8 9 10
Press any key to exit..
// C# code to demonstrate for loop statement
using System;
namespace ForLoop{
class Program {
static void Main(string[] args){
for (int i = 1; i <= 10; i++){
Console.Write(" "+i);
}
Console.WriteLine("n Press any key to exit..");
Console.ReadKey();
}}}
â€ĸ If you observe this code,
â€ĸ we defined a for loop to iterate
over 10 times to print the value of
variable i and following are the main
parts of for loop.
â€ĸ Here,
â€ĸ int i = 1 is the initialization part
â€ĸ i <= 10 is the test-condition part
â€ĸ i++ is the iterator part
īƒ˜When the above code is compiled and executed, it produces the following result:
5/5/2021 52
For Loop without Initialization & Iterators
īƒ˜Generally, the initializer, condition and iterator parameters are optional to
create for loop in c# programming language.
īƒ˜ Syntax of for loop without initialization and iterator
īƒ˜Following is the example of creating a for loop in c# programming language
without initializer and iterator. â€Ļ on the next pageâ€Ļ
Looping Statements(Cont’d)
initialization;
for(;test-condition;){
// statements to execute
iterator;
}
5/5/2021 53
// C# code to demonstrate for loop statement without initialization and iterator
using System;
namespace ForLoop1{
class Program{
static void Main(string[] args){
int i=1;
for (; i <= 10; ){
Console.Write(" " + i);
i++;
}
Console.WriteLine("n Press any key to exit..");
Console.ReadKey();
}}}
īƒ˜ When the above code is compiled and executed, it produces the following result:
1 2 3 4 5 6 7 8 9 10
Press any key to exit..
5/5/2021 54
īƒ˜C# Infinite For Loop
īƒ˜In case, if the condition parameter in for loop always returns true, then
the for loop will be an infinite and runs forever.
īƒ˜Even if we miss the condition parameter in for loop automatically that loop
will become an infinite loop.
īƒ˜ Following are the different ways to make for loop as an infinite loop in c#
programming language.
Looping Statements(Cont’d)
for (initializer; ; iterator) {
// Statements to Execute
}
or (initializer; ; iterator) {
// Statements to Execute
}
or
for ( ; ; ){
// Statements to Execute
}
5/5/2021 55
//Following is the example of making a for loop as an infinite in c# programming language.
using System;
namespace InfiniteForLoop{
class Program{
static void Main(string[] args){
for (int i = 1; i > 0; i++){
Console.Write(" " + i);
i++;
}
Console.WriteLine("n Press any key to exit..");
Console.ReadKey();
}}}
5/5/2021 56
C# Nested For Loop
īƒ˜In c#, we can create one for loop within another for loop based on our
requirements.
Looping Statements(Cont’d)
//Following is the example of creating a nested for loop in c# programming language.
using System;
namespace NestedForLoop{
class Program{
static void Main(string[] args){
for (int i = 1; i <=3; i++){
for (int j = 1; j <=2; j++){
Console.Write(" {0} {1}, ", i, j);
}}
Console.WriteLine("nPress Enter Key to Exit..");
Console.ReadKey();
}}}
1 1, 1 2, 2 1, 2 2, 3 1, 3 2,
Press Enter Key to Exit..
īƒ˜ When this code is compiled and executed, it
produces the following result:
Note: the inner for loop evaluated first. Until the test condition of
inner loop becomes false execution of code stay at inner loop.
5/5/2021 57
2. While Loop
īƒ˜In c#, While loop is used to execute a block of statements until the specified
expression return as a true.
īƒ˜ Generally, the for loop is useful when we are sure about how many times we
need to execute the block of statements. In case, if we are unknown about the
number of times to execute the block of statements, then while loop is the best
solution.
īƒ˜Syntax of C# While Loop:
īƒ˜ if expression returns true, then the statements inside of while loop will be
executed.
while (expression) {
// Statements to Execute
}
Looping Statements(Cont’d)
5/5/2021 58
//C# code to demonstrate while loop statement
using System;
namespace WhileLoop{
class Program{
static void Main(string[] args){
int i = 1;
while (i<=5){
Console.Write(" " + i);
i++;
}
Console.Write("nPress any key to exit...");
Console.ReadKey();
}}}
īƒ˜ When this code is compiled and executed,
it produces the following result:
1 2 3 4 5
Press any key to exit..
5/5/2021 59
3. Do While Loop
īƒ˜In c#, Do-While loop is used to execute a block of statements until the specified
expression return as a true.
īƒ˜ Generally, in c# the do-while loop is same as while loop but only the difference
is while loop will execute the statements only when the defined condition
returns true, but do-while loop will execute the statements at least once, because
first it will execute the block of statements and then it will checks the condition.
īƒ˜Syntax of C# Do-While Loop:
īƒ˜The body of do-while loop will be executed first, then the expression will be
evaluated. if expression returns true, then again the statements inside of do-while
loop will be executed.
īƒ˜In case, the expression is evaluated to false, then the do-while loop stops the
execution of statements and the program comes out of the loop.
do{
// Statements to Execute
}while (expression);
Looping Statements(Cont’d)
5/5/2021 60
// C# code to demonstrate do-while loop statement.
using System;
namespace WhileLoop{
class Program{
static void Main(string[] args){
int i = 1;
do{
Console.Write(" " + i);
i++;
}while (i<=5);
Console.Write("nPress any key to exit...");
Console.ReadKey();
}}}
īƒ˜ When this code is compiled and
executed, it produces the following
result:
1 2 3 4 5
Press any key to exit..
5/5/2021 61
4. Foreach Loop
īƒ˜In c#, Foreach loop is used to loop through an each item in array or collection
object to execute the block of statements repeatedly.
īƒ˜ Generally, in c# Foreach loop will work with the collection objects such as
arrays, list, etc. to execute the block of statements for each element in the array
or collection.
īƒ˜After completion of iterating through an each element in collection, control is
transferred to the next statement following the foreach block.
īƒ˜ In c#, we can use break, continue, goto and return statements
within foreach loop to exit or continue to the next iteration of the loop based on
our requirements.
īƒ˜Syntax of C# Foreach Loop:
Looping Statements(Cont’d)
foreach (Type var_name in Collection_Object) {
// Statements to Execute
}
5/5/2021 62
īƒ˜ When the above code is compiled
and executed, it produces the
following result:
//C# code to demonstrate foreach loop statement
using System;
namespace ForeachLoop{
class Program{
static void Main(string[] args){
string[] names = new string[4] { "Computer Science", "Accounting ",
"Economics","Information Technology" };
foreach (string name in names){
Console.WriteLine(name);
}
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}}}
5/5/2021 63
īƒ˜5.
1. Break Statement
īƒ˜In c#, Break statement is used to break or terminate the execution of loops (for,
while, do-while, etc.) or
īƒ˜ switch statement and the control is passed immediately to the next statements
that follows a terminated loops or statements.
īƒ˜ In c# nested loops also we can use break statement to stop or terminate the
execution of inner loops based on our requirements.
īƒ˜Syntax of C# Break Statement:
īƒ˜In our applications, we can use break statement whenever we want to stop the
execution of particular loop or statement based on our requirements.
Jumping Statements(Cont’d)
break;
5/5/2021 64
// C# code to demonstrate break statement with for loop statement
using System;
namespace BreakStatement{
class Program{
static void Main(string[] args){
for (int i = 1; i <= 5; i++){
if (i == 3)
break;
Console.Write(" " + i);
}
Console.WriteLine("n Press any key to exit..");
Console.ReadKey();
}}}
īƒ˜ When the above code is compiled
and executed, it produces the
following result:
1 2
Press any key to exit..
5/5/2021 65
6. Continue Statement
īƒ˜In c#, Continue statement is used to pass a control to the next iteration of loops
such as for, while, do-while or foreach from the specified position by skipping
the remaining code.
īƒ˜ The main difference between break statement and continue statement is,
the break statement will completely terminate the loop or statement execution
but the continue statement will pass a control to the next iteration of loop.
īƒ˜Syntax of C# Continue Statement:
īƒ˜In our applications, we can use continue statement whenever we want to skip
the execution of code from the particular position and send back the control to
next iteration of loop based on our requirements.
Looping Statements(Cont’d)
continue;
5/5/2021 66
// C# code to demonstrate continue statement with for loop statement
using System;
namespace BreakStatement{
class Program{
static void Main(string[] args){
for (int i = 1; i <=5; i++){
if (i == 3)
continue;
Console.Write(" " + i);
}
Console.WriteLine("n Press any key to exit..");
Console.ReadKey();
}}}
īƒ˜ When this code is compiled and
executed, it produces the
following result:
1 2 4 5
Press any key to exit..
5/5/2021 67
6. Goto Statement
īƒ˜In c#, Goto statement is used to transfer a program control to the defined labeled
statement and it is useful to get out of the loop or exit from a deeply nested loops
based on our requirements.
īƒ˜ Generally, in c# the defined labeled statement must always exists in the scope
of goto statement and we can define multiple goto statements in our application
to transfer the program control to specified labeled statement.
īƒ˜Syntax of C# goto Statement:
īƒ˜a goto statement by using goto keyword and with labeled_statement. Here
the labeled_statement is used to transfer the program control to
specified labeled_statement position.
Looping Statements(Cont’d)
goto labeled_statement;
5/5/2021 68
// C# code to demonstrate continue statement with for loop statement
using System;
namespace GotoStatement{
class Program{
static void Main(string[] args){
for (int i = 1; i <= 5; i++){
if (i == 3)
goto m;
Console.Write(" " + i);
}
m:Console.WriteLine("n The end");
Console.WriteLine("n Press any key to exit..");
Console.ReadKey();
}}}
īƒ˜ When the above code is compiled
and executed, it produces the
following result:
1 2
The end
Press any key to exit..
5/5/2021 69
6. Return Statement
īƒ˜ In c#, Return statement is used to terminate the execution of method in which
it appears and returns the control back to the calling method.
īƒ˜Generally, in c# the return statement is useful whenever we want to get a some
value from the other methods and we can omit the usage of return statement in
our methods by using void as a return type.
īƒ˜Syntax of C# return Statement:
Looping Statements(Cont’d)
return return_val;
5/5/2021 70
// C# code to demonstrate return statement with function or method
using System;
namespace ReturnStatement{
class Program{
static void Main(string[] args){
int i = 10, j = 20, result = 0;
result = add(i, j);
Console.WriteLine("Sum of i and J is : {0}", result);
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadKey();
}
public static int add(int a, int b){
int x = a + b;
return x;
}}}
īƒ˜ When the above code is compiled
and executed, it produces the
following result:
Sum of i and J is : 30
Press Enter Key to Exit..
5/5/2021 71
īƒ˜A method (Function) is a group of statements that together perform a task.
īƒ˜Every C# program has at least one class with a method named Main.
īƒ˜Methods are generally the block of codes or statements in a program that
gives the user the ability to reuse the same code which ultimately saves the
excessive use of memory, acts as a time saver and more importantly, it
provides a better readability of code.
īƒ˜ So basically, a method is a collection of statements that perform some
specific task and return the result to the caller.
īƒ˜ A method can also perform some specific task without returning anything.
īƒ˜To use a method, you need to:
â€ĸ Define the method
â€ĸ Call the method
Method in C#
5/5/2021 72
īƒ˜Method Declaration
īƒ˜Method declaration means the way to construct method including its naming.
Syntax :
Method (Cont’d)
<access-modifier> <return-type> <method-name>([parameter-lists])
5/5/2021 73
īƒ˜In C# a method declaration consists of following components as follows :
īƒ˜Modifier : It defines access type of the method i.e. from where it can be
accessed in your application.
īƒ˜ In C# there are Public, Protected, Private, static access modifiers.
īƒ˜Name of the Method : It describes the name of the user defined method by
which the user calls it or refer it. Eg. add()
īƒ˜Return type: It defines the data type returned by the method.
īƒ˜It depends upon user as it may also return void value i.e return nothing
īƒ˜Body of the Method : It refers to the line of code of tasks to be performed
by the method during its execution.
īƒ˜ It is enclosed between braces.
Method (Cont’d)
5/5/2021 74
īƒ˜Parameter list : Comma separated list of the input parameters are defined,
preceded with their data type, within the enclosed parenthesis.
īƒ˜If there are no parameters, then empty parentheses () have to use out.
īƒ˜The Method Body : consists of statements of code which a user wants to perform.
īƒ˜After the method has been declared, it is dependent on the user whether to define
its implementation or not.
īƒ˜Not writing any implementation, makes the method not to perform any task.
īƒ˜ However, when the user wants to perform certain tasks using method then it must
write the statements for execution in the body of the method.
īƒ˜The below syntax describes the basic structure of the method body :
Method (Cont’d)
<return_type> <method_name>(<parameter_list>){
// Implementation of the method code goes here.....
}
5/5/2021 75
Method Calling
īƒ˜Method Invocation or Method Calling is done when the user wants to
execute the method.
īƒ˜ The method needs to be called for using its functionality.
īƒ˜A method returns to the code that invoked it when:
â€ĸ It completes all the statements in the method
â€ĸ It reaches a return statement
â€ĸ Throws an exception
īƒ˜The next code example shows a function add that takes two integer values
and returns the sum of the two integers.
īƒ˜It has public access specifier, so it can be accessed from outside the class
using an instance of the class.
Method (Cont’d)
5/5/2021 76
// C# program to returns the sum of two numbers using method
using System;
namespace Method{
class Program {
public int add(int x, int y){
int result=0;
result = x + y;
return result;
}
static void Main(string[] args){
Program n=new Program();
int a = 10, b = 20, c=0;
c = n.add(a, b);
Console.WriteLine("The sum of a and b is: " + c);
Console.WriteLine("Press any key to exit..");
Console.ReadKey();
}}}
īƒ˜ When this code is compiled and
executed, it produces the
following result:
The sum of a and b is: 30
Press any key to exit..
5/5/2021 77
Advantages of using the Methods :
īƒ˜ Some of the advantages of methods are listed below:
īƒŧIt makes the program well structured.
īƒŧMethods enhance the readability of the code.
īƒŧIt provides an effective way for the user to reuse the existing code.
īƒŧIt optimizes the execution time and memory space.
Method (Cont’d)
5/5/2021 78
īƒ˜Properties are named members of classes, structures, and interfaces.
īƒ˜ Member variables or methods in a class or structures are called Fields.
īƒ˜Properties are an extension of fields and are accessed using the same syntax.
īƒ˜They use accessors through which the values of the private fields can be read,
written or manipulated.
īƒ˜The accessor of a property contains the executable statements that helps in
getting (reading or computing) or setting (writing) the property.
īƒ˜The accessor declarations can contain a get accessor, a set accessor, or both.
C# Properties
5/5/2021 79
using System;
namespace Properties{
class Program {
private string code = "N.A";
private string name = "not known";
private int age = 0;
public string Code{ // Declare a Code property of type string:
get{
return code;
}
set{
code = value;
} }
public string Name{ // Declare a Name property of type string:
get {
return name;
}
set{
name = value;
}}
// code continue on the next pageâ€Ļ
5/5/2021 80
public int Age{ // Declare a Age property of type int:
get{
return age;
}
set{
age = value;
}}
public override string ToString() {
return "Code = " + Code +", Name = " + Name + ", Age = " + Age;
}}
class ExampleDemo {
public static void Main() {
Program s = new Program(); // Create a new Student object:
s.Code = "RET/858/02"; // Setting code, name and the age of the student
s.Name = "Lalise";
s.Age = 20;
Console.WriteLine("Student Info: {0}", s);
s.Age += 1;
Console.WriteLine("Student Info: {0}", s);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
} }}
īƒ˜ When this code is compiled and
executed, it produces the
following result:
Student Info: Code = RET/858/02, Name = Lalise, Age = 20
Student Info: Code = RET/858/02, Name = Lalise, Age = 21
Press any key to exit...
5/5/2021 81
Errors
īƒ˜ Programming errors are generally broken down into three types:
1. Design-time,
2. Runtime, and
3. Logic errors.
1. Design Time Errors
īƒ˜ A Design-time error is also known as a syntax error.
īƒ˜ These occur when the environment you're programming in doesn't understand your
code.
īƒ˜ These are easy to track down in C#, because you get a blue wiggly line pointing them
out.
īƒ˜ If you try to run the program, you'll get a dialogue box popping up telling you that there
were Build errors.
Exception (Error) Handling in C#
5/5/2021 82
2. Run Time Errors
īƒ˜ Runtime errors are a lot harder to track down. As their name suggests, these errors occur
when the program is running.
īƒ˜ They happen when your program tries to do something it shouldn't be doing.
īƒ˜ An example is trying to access a file that doesn't exist.
īƒ˜ Runtime errors usually cause your program to crash. You should write code to trap
runtime errors.
3. Logic Errors
īƒ˜ Logic errors also occur when the program is running.
īƒ˜ They happen when your code doesn't quite behave the way you thought it would.
īƒ˜ A classic example is creating an infinite loop of the type "Do While x is greater than 10".
If x is always going to be greater than 10, then the loop has no way to exit, and just keeps
going round and round.
īƒ˜ Logic errors tend not to crash your program. But they will ensure that it doesn't work
properly.
Exceptionâ€Ļ(Cont’d)
5/5/2021 83
Exceptions
īƒ˜ Are events which may be considered exceptional or unusual.
īƒ˜ They are conditions that are detected by an operation, that cannot be resolved within the
local context of the operation and must be brought to the attention of the operation
invoker.
Exception Handler
īƒ˜ Is a procedure or code that deals with the exceptions in your program.
Raising Exceptions
īƒ˜ The process of noticing exceptions, interrupting the program and calling the exception
handler.
Propagating the Exceptions
īƒ˜ Reporting the problem to higher authority (the calling program) in your program.
Handling the Exceptions
īƒ˜ The process of taking appropriate corrective action.
Exceptionâ€Ļ(Cont’d)
5/5/2021 84
Example of exceptions
1. Array out of bound
2. Divide by zero
3. Implicit type casting
4. Input/output exception
5. File not found exception
Structured Exception Handling
īƒ˜ C# has a built-in class that deals with errors.
īƒ˜ The class is called Exception. When an exception error is found, an exception object is
created. The exception object contains information relevant to the error exposed as
properties of the object.
īƒ˜ The object is an instance of a class that derived from a class named System.Exception.
īƒ˜ The coding structure C# uses to deal with such Exceptions is called the Try â€Ļ Catch
structure.
Exceptionâ€Ļ(Cont’d)
5/5/2021 85
īƒ˜ Depends on several key words.
Try:
īƒ˜ Begins a section of a code in which an exception might be generated from a code error.
īƒ˜ This section is called the Try Block. And it means "Try to execute this code".
īƒ˜ A trapped exception is automatically routed to the Catch statement.
Catch:
īƒ˜ Begins an exception handler for a type of exception.
īƒ˜ One or more catch code blocks follow a try block, with each catch block catching a
different type of exception.
Finally:
īƒ˜ Contains code that runs when the try block finishes normally, or when a catch block
receives control then finishes.
īƒ˜ Is a block that always runs regardless of whether an exception is detected or not.
ī‚§ Example: closing a database connection.
Exceptionâ€Ļ(Cont’d)
5/5/2021 86
Implementing Exception Handling
īƒ˜ Exception handlers are implemented for specific methods.
īƒ˜ The following three general steps are involved in creating exception handler.
īƒ˜ Wrap the code with which the handler will be associated in a Try block
īƒ˜ Add one or more Catch block to handle the possible exceptions
īƒ˜ Add any code that is always executed regardless of whether or not an exception is thrown to a Finally
block
īƒ˜ Structure
Try
' normal program code goes here
Catch
' catch block goes here (error handling)
Finally
' finally block goes here
End Try
Exceptionâ€Ļ(Cont’d)
5/5/2021 87
// C# divide by zero exception handling program
using System;
namespace ExceptionHandling{
class Program {
static void Main(string[] args){
try{
int x = 10, y = 0, result = 0;
result = x / y;
Console.WriteLine("Result = " + result);
}
catch{
}
finally{
Console.WriteLine("End of Execution");
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}}}
īƒ˜ When this code is compiled and
executed, it produces the
following result:
End of Execution
Press any key to exit...

More Related Content

What's hot

Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
OpenSource Technologies Pvt. Ltd.
 
Learn C# Programming - Data Types & Type Conversion
Learn C# Programming - Data Types & Type ConversionLearn C# Programming - Data Types & Type Conversion
Learn C# Programming - Data Types & Type Conversion
Eng Teong Cheah
 
Character set of c
Character set of cCharacter set of c
Character set of c
Chandrapriya Rediex
 
Introduction To C#
Introduction To C#Introduction To C#
Introduction To C#
SAMIR BHOGAYTA
 
Introduction to C# Programming
Introduction to C# ProgrammingIntroduction to C# Programming
Introduction to C# Programming
Sherwin Banaag Sapin
 
Vb.net class notes
Vb.net class notesVb.net class notes
Vb.net class notes
priyadharshini murugan
 
Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programming
TejaswiB4
 
structured programming Introduction to c fundamentals
structured programming Introduction to c fundamentalsstructured programming Introduction to c fundamentals
structured programming Introduction to c fundamentals
OMWOMA JACKSON
 
History of c++
History of c++ History of c++
History of c++
Ihsan Wassan
 
C# programming language
C# programming languageC# programming language
C# programming language
swarnapatil
 
Visual Programming
Visual ProgrammingVisual Programming
Visual Programming
Bagzzz
 
Programming in c
Programming in cProgramming in c
Programming in c
indra Kishor
 
Differences between c and c++
Differences between c and c++Differences between c and c++
Differences between c and c++
starlit electronics
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
Veerabadra Badra
 
C Language
C LanguageC Language
C Language
Aakash Singh
 
Declaration of variables
Declaration of variablesDeclaration of variables
Declaration of variables
Maria Stella Solon
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
Dr.Neeraj Kumar Pandey
 
What is identifier c programming
What is identifier c programmingWhat is identifier c programming
What is identifier c programming
Rumman Ansari
 
C# in depth
C# in depthC# in depth
C# in depth
Arnon Axelrod
 

What's hot (20)

Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
Learn C# Programming - Data Types & Type Conversion
Learn C# Programming - Data Types & Type ConversionLearn C# Programming - Data Types & Type Conversion
Learn C# Programming - Data Types & Type Conversion
 
Character set of c
Character set of cCharacter set of c
Character set of c
 
Introduction To C#
Introduction To C#Introduction To C#
Introduction To C#
 
Introduction to C# Programming
Introduction to C# ProgrammingIntroduction to C# Programming
Introduction to C# Programming
 
Vb.net class notes
Vb.net class notesVb.net class notes
Vb.net class notes
 
Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programming
 
structured programming Introduction to c fundamentals
structured programming Introduction to c fundamentalsstructured programming Introduction to c fundamentals
structured programming Introduction to c fundamentals
 
History of c++
History of c++ History of c++
History of c++
 
C# programming language
C# programming languageC# programming language
C# programming language
 
Visual Programming
Visual ProgrammingVisual Programming
Visual Programming
 
Programming in c
Programming in cProgramming in c
Programming in c
 
Differences between c and c++
Differences between c and c++Differences between c and c++
Differences between c and c++
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
C Language
C LanguageC Language
C Language
 
C sharp
C sharpC sharp
C sharp
 
Declaration of variables
Declaration of variablesDeclaration of variables
Declaration of variables
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
What is identifier c programming
What is identifier c programmingWhat is identifier c programming
What is identifier c programming
 
C# in depth
C# in depthC# in depth
C# in depth
 

Similar to Chapter 2 c#

Dot net programming concept
Dot net  programming conceptDot net  programming concept
Dot net programming concept
sandeshjadhav28
 
LEARN C# PROGRAMMING WITH GMT
LEARN C# PROGRAMMING WITH GMTLEARN C# PROGRAMMING WITH GMT
LEARN C# PROGRAMMING WITH GMT
Tabassum Ghulame Mustafa
 
Keywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.netKeywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.net
Jaya Kumari
 
Unit 1 question and answer
Unit 1 question and answerUnit 1 question and answer
Unit 1 question and answer
Vasuki Ramasamy
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
InfinityWorld3
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
PriyadarshiniS28
 
2 programming with c# i
2 programming with c# i2 programming with c# i
2 programming with c# i
siragezeynu
 
Data Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# ProgrammingData Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# Programming
Sherwin Banaag Sapin
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01Zafor Iqbal
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
Vishwa Mohan
 
C#
C#C#
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
Mufaddal Nullwala
 
csharp.docx
csharp.docxcsharp.docx
csharp.docx
LenchoMamudeBaro
 
CSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdfCSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdf
ssusera0bb35
 
C# note
C# noteC# note
434090527-C-Cheat-Sheet. pdf C# program
434090527-C-Cheat-Sheet. pdf  C# program434090527-C-Cheat-Sheet. pdf  C# program
434090527-C-Cheat-Sheet. pdf C# program
MAHESHV559910
 
Basic Structure Of C++
Basic Structure Of C++Basic Structure Of C++
Basic Structure Of C++
DevangiParekh1
 
2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)
Shoaib Ghachi
 

Similar to Chapter 2 c# (20)

Dot net programming concept
Dot net  programming conceptDot net  programming concept
Dot net programming concept
 
LEARN C# PROGRAMMING WITH GMT
LEARN C# PROGRAMMING WITH GMTLEARN C# PROGRAMMING WITH GMT
LEARN C# PROGRAMMING WITH GMT
 
Keywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.netKeywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.net
 
Unit 1 question and answer
Unit 1 question and answerUnit 1 question and answer
Unit 1 question and answer
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
2 programming with c# i
2 programming with c# i2 programming with c# i
2 programming with c# i
 
Data Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# ProgrammingData Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# Programming
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
 
C#
C#C#
C#
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
 
csharp.docx
csharp.docxcsharp.docx
csharp.docx
 
Objects and Types C#
Objects and Types C#Objects and Types C#
Objects and Types C#
 
CSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdfCSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdf
 
C# note
C# noteC# note
C# note
 
434090527-C-Cheat-Sheet. pdf C# program
434090527-C-Cheat-Sheet. pdf  C# program434090527-C-Cheat-Sheet. pdf  C# program
434090527-C-Cheat-Sheet. pdf C# program
 
Basic Structure Of C++
Basic Structure Of C++Basic Structure Of C++
Basic Structure Of C++
 
2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)
 
c# at f#
c# at f#c# at f#
c# at f#
 

Recently uploaded

Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
Celine George
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
Delivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and TrainingDelivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and Training
AG2 Design
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
goswamiyash170123
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
Wasim Ak
 
Assignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docxAssignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docx
ArianaBusciglio
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
āĻŦāĻžāĻ‚āĻ˛āĻžāĻĻā§‡āĻļ āĻ…āĻ°ā§āĻĨāĻ¨ā§ˆāĻ¤āĻŋāĻ• āĻ¸āĻŽā§€āĻ•ā§āĻˇāĻž (Economic Review) ā§¨ā§Ļā§¨ā§Ē UJS App.pdf
āĻŦāĻžāĻ‚āĻ˛āĻžāĻĻā§‡āĻļ āĻ…āĻ°ā§āĻĨāĻ¨ā§ˆāĻ¤āĻŋāĻ• āĻ¸āĻŽā§€āĻ•ā§āĻˇāĻž (Economic Review) ā§¨ā§Ļā§¨ā§Ē UJS App.pdfāĻŦāĻžāĻ‚āĻ˛āĻžāĻĻā§‡āĻļ āĻ…āĻ°ā§āĻĨāĻ¨ā§ˆāĻ¤āĻŋāĻ• āĻ¸āĻŽā§€āĻ•ā§āĻˇāĻž (Economic Review) ā§¨ā§Ļā§¨ā§Ē UJS App.pdf
āĻŦāĻžāĻ‚āĻ˛āĻžāĻĻā§‡āĻļ āĻ…āĻ°ā§āĻĨāĻ¨ā§ˆāĻ¤āĻŋāĻ• āĻ¸āĻŽā§€āĻ•ā§āĻˇāĻž (Economic Review) ā§¨ā§Ļā§¨ā§Ē UJS App.pdf
eBook.com.bd (āĻĒā§āĻ°āĻ¯āĻŧā§‹āĻœāĻ¨ā§€āĻ¯āĻŧ āĻŦāĻžāĻ‚āĻ˛āĻž āĻŦāĻ‡)
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 

Recently uploaded (20)

Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
Delivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and TrainingDelivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and Training
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
 
Assignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docxAssignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docx
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
āĻŦāĻžāĻ‚āĻ˛āĻžāĻĻā§‡āĻļ āĻ…āĻ°ā§āĻĨāĻ¨ā§ˆāĻ¤āĻŋāĻ• āĻ¸āĻŽā§€āĻ•ā§āĻˇāĻž (Economic Review) ā§¨ā§Ļā§¨ā§Ē UJS App.pdf
āĻŦāĻžāĻ‚āĻ˛āĻžāĻĻā§‡āĻļ āĻ…āĻ°ā§āĻĨāĻ¨ā§ˆāĻ¤āĻŋāĻ• āĻ¸āĻŽā§€āĻ•ā§āĻˇāĻž (Economic Review) ā§¨ā§Ļā§¨ā§Ē UJS App.pdfāĻŦāĻžāĻ‚āĻ˛āĻžāĻĻā§‡āĻļ āĻ…āĻ°ā§āĻĨāĻ¨ā§ˆāĻ¤āĻŋāĻ• āĻ¸āĻŽā§€āĻ•ā§āĻˇāĻž (Economic Review) ā§¨ā§Ļā§¨ā§Ē UJS App.pdf
āĻŦāĻžāĻ‚āĻ˛āĻžāĻĻā§‡āĻļ āĻ…āĻ°ā§āĻĨāĻ¨ā§ˆāĻ¤āĻŋāĻ• āĻ¸āĻŽā§€āĻ•ā§āĻˇāĻž (Economic Review) ā§¨ā§Ļā§¨ā§Ē UJS App.pdf
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 

Chapter 2 c#

  • 1. Berhanu Fetene (MSc.) Chapter Two: C# (C-sharp) programming language 5/5/2021 1
  • 2. C# Programming īƒ˜ C# is an object-oriented programming language. īƒ˜ In Object-Oriented Programming methodology, a program consists of various objects that interact with each other by means of actions. īƒ˜ The actions that an object may take are called methods. īƒ˜ Objects of the same kind are said to have the same type or are said to be in the same class. īƒ˜ C# is case sensitive īƒ˜ All statements and expression must end with a semicolon(;). īƒ˜ The program execution starts at the main method. īƒ˜ Unlike Java, program file name could be different from the class name. 5/5/2021 2
  • 3. C# Program Structure īƒ˜ A C# program consists of the following parts: īƒŧ Namespace declaration īƒŧ A class īƒŧ Class methods īƒŧ Class attributes īƒŧ A main method īƒŧ Statements and expressions īƒŧ Comments (optional) 5/5/2021 3
  • 4. 7 Sample C# program: using System; class HelloCSharp { static void Main() { Console.WriteLine("Hello, C#"); } }
  • 5. C# Code – How It Works? using System; class HelloCSharp { static void Main() { Console.WriteLine("Hello, C#"); } } Include the standard namespace "System" Define a class called "HelloCSharp" Define the Main() method – the program entry point 8 Print a text on the console by calling the method "WriteLine" of the class "Console"
  • 6. C# Code Should Be Well Formatted using System; class HelloCSharp { s st ta at ti ic c v vo oi id d M Ma ai in n( () ) { { C Co on ns so ol le e. .W Wr ri it te eL Li in ne e( (" "H He el ll lo o, , C C# #" ") ); ; } } } The {symbol should be alone on a new line. The block after the {symbol should be indented by a TAB. The }symbol should be under the corresponding {. Class names should use PascalCaseand start with a CAPITALletter. 9
  • 7. Important features of C# īƒ˜ It is important to note the following points: īƒŧ C# is case sensitive. īƒŧ All statements and expression must end with a semicolon (;). īƒŧ The program execution starts at the Main method. īƒŧ Unlike Java, program file name could be different from the class name. Compiling and Executing the Program īƒŧ If you are using Visual Studio. Net for compiling and executing C# programs, take the following steps: īƒŧ Start Visual Studio. īƒŧ On the menu bar, choose File -> New -> Project. 5/5/2021 7
  • 8. Compiling and Executing the Program (Cont’d) īƒ˜ Choose Visual C# from templates, and then choose Windows. īƒ˜ Choose Console Application. īƒ˜ Specify a name for your project and click OK button. This creates a new project in Solution Explorer. īƒ˜ Write code in the Code Editor. īƒ˜ Click the Run button or press F5 key to execute the project. īƒ˜ A Command Prompt window appears that contains the line H He el ll lo o, , C C# #" “. 5/5/2021 8
  • 9. īƒ˜ The variables in C#, are categorized into one of the following three categories: īƒŧ Value types īƒŧ Refence types īƒŧ Pointer types 1. Value Type īƒ˜ Value type variables can be assigned a value directly. īƒ˜ They are derived from the class System.ValueType. īƒ˜ The value types directly contain data. 5/5/2021 9 Data Types
  • 10. īƒ˜ Some examples are int, char, and float which stores numbers, alphabets, and floating point numbers respectively. īƒ˜ When you declare an int type, the system allocates memory to store the value. īƒ˜ The following table lists the available value types in C# . 5/5/2021 10 Data Types (Cont’d) Type Represent 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-29 significant digits (-7.9 x 1028 to 7.9 x 1028 ) / 100 to 1028 0.0M
  • 11. 5/5/2021 11 Data Types (Cont’d) Type Represent Range Default Value 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 9,223,372,036,854,775,807 0L sbyte 8-bit signed integer type -128 to 127 0 short 16-bit signed integer type -32,768 to 32,767 0 uint 16-bit signed 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. īƒ˜ To get the exact size of a type or a variable on a particular platform, you can use the sizeof method. īƒ˜ The expression sizeof(type) yields the storage size of the object or type in bytes. īƒ˜ The following is an example to get the size of data types we defined in the above tables. 5/5/2021 12 Data Types (Cont’d)
  • 13. 5/5/2021 13 using System; namespace DataTypeSize{ class Program{ static void Main(string[] args){ Console.WriteLine("Size of bool is : {0}", sizeof(bool)); Console.WriteLine("Size of byte is : {0}", sizeof(byte)); Console.WriteLine("Size of char is : {0}", sizeof(char)); Console.WriteLine("Size of decimal is : {0}", sizeof(decimal)); Console.WriteLine("Size of float is : {0}", sizeof(float)); Console.WriteLine("Size of int is : {0}", sizeof(int)); Console.WriteLine("Size of long is : {0}", sizeof(long)); Console.WriteLine("Size of sbyte is : {0}", sizeof(sbyte)); Console.WriteLine("Size of short is : {0}", sizeof(short)); Console.WriteLine("Size of uint is : {0}", sizeof(uint)); Console.WriteLine("Size of ulong is : {0}", sizeof(ulong)); Console.WriteLine("Size of ushort is : {0}", sizeof(ushort)); Console.ReadKey(); }}}
  • 14. 5/5/2021 14 īƒ˜ When the above code is compiled and executed, it produces the following result: Size of bool is : 1 Size of byte is : 1 Size of char is : 2 Size of decimal is : 16 Size of float is : 4 Size of int is : 4 Size of long is : 8 Size of sbyte is : 1 Size of short is : 2 Size of uint is : 4 Size of ulong is : 8 Size of ushort is : 2
  • 15. 5/5/2021 15 2. Refence Type īƒ˜ The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables. īƒ˜ In other words, they refer to a memory location. īƒ˜ Using multiple variables, the reference types can refer to a memory location. īƒ˜ If the data in the memory location is changed by one of the variables, the other variable automatically reflects this change in value. īƒ˜ Example of built-in reference types are: object, dynamic, and string. Data Types (Cont’d)
  • 16. 5/5/2021 16 A. Object Type īƒ˜ The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an alias for System.Object class. īƒ˜ The object types can be assigned values of any other types, value types, reference types, predefined or user-defined types. īƒ˜ However, before assigning values, it needs type conversion. īƒ˜ When a value type is converted to object type, it is called boxing and on the other hand, when an object type is converted to a value type, it is called unboxing. Example: Reference Types (Cont’d) object obj; obj = 100; // this is boxing
  • 17. 5/5/2021 17 B. Dynamic Type īƒ˜ You can store any type of value in the dynamic data type variable. īƒ˜ Type checking for these types of variables takes place at run-time. īƒ˜ Syntax for declaring a dynamic type is: īƒ˜ For example: īƒ˜ Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at run time. Reference Types (Cont’d) dynamic number = 100; dynamic <variable_name> = value;
  • 18. 5/5/2021 18 B. Dynamic Type īƒ˜ The String Type allows you to assign any string values to a variable. īƒ˜ The string type is an alias for the System.String class. īƒ˜ It is derived from object type. īƒ˜ The value for a string type can be assigned using string literals in two forms: quoted and @quoted. īƒ˜ For example: īƒ˜ A @quoted string literal looks as follows: īƒ˜ The user-defined reference types are: class, interface, or delegate. We will discuss these types in later chapter in details. Reference Types (Cont’d) string name= “Rift Valley University"; @“Rift Valley University";
  • 19. 5/5/2021 19 2. Pointer Type īƒ˜ Pointer type variables store the memory address of another type. īƒ˜ Pointers in C# have the same capabilities as the pointers in C or C++. īƒ˜ Syntax for declaring a pointer type is: īƒ˜ For example: īƒ˜ We will discuss more about pointer types in the subsections. Data Types (Cont’d) type* identifier; char* cptr; int* iptr;
  • 20. īƒ˜ Keywords are reserved words predefined to the C# compiler. īƒ˜ These keywords cannot be used as identifiers. īƒ˜ However, if you want to use these keywords as identifiers, you may prefix them with the @ character. īƒ˜ In C#, some identifiers have special meaning in context of code, such as get and set, these are called contextual keywords. īƒ˜ The following TABLE lists the reserved keywords and contextual keywords in C# . 5/5/2021 20 C# Keywords
  • 21. 5/5/2021 21 Reserved Keywords abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach goto if implicit in volatile int interface internal is lock long namespace new null object operator out private override params protected public readonly ref return sbyte while sealed short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using virtual void
  • 22. 5/5/2021 22 Contextual Keywords add alias ascending descending dynamic from get global group into join let orderby partial (type) partial (method) remove select set
  • 23. Identifiers 5/5/2021 23 īƒ˜ An identifier is a name used to identify a class, variable, function, or any other user-defined item. īƒ˜ The basic rules for naming identifiers in C# are as follows: īƒŧ A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9), or underscore. īƒŧ The first character in an identifier cannot be a digit. īƒŧ It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ] { } . ; : " ' / and . īƒŧ However, an underscore ( _ ) can be used. īƒŧ It should not be a C# keyword. digit.
  • 24. C# Variables 5/5/2021 24 īƒ˜ A variable is a name given to a storage area that is used to store values of various data types. īƒ˜ Each variable in C# needs to have a specific type, which determines the size and layout of the variable's memory. īƒ˜ Based on the data type, specific operations can be carried out on the variable. īƒ˜ One can declare multiple variables in a program. īƒ˜ Example1: // age is variable that can store integer value. // value 30 is assigned to variable age which is declared before. Example2: //mulptiple variable declaration int age; age =30; int length, width, area;
  • 25. C# Operators 5/5/2021 25 1. Arithmetic Operators īƒ˜ are operators used for performing mathematic operations on numbers. īƒ˜Below is the list of arithmetic operators available in C#. Operator Description + Adds two operands - Subtracts the second operand from the first * Multiplies both operands / Divides the numerator by de-numerator % Modulus Operator and a remainder of after an integer division ++ Increment operator increases integer value by one -- Decrement operator decreases integer value by one
  • 26. 5/5/2021 26 // C# code to demonstrate the use of arithmetic operators using System; namespace ArithmeticOperator{ class Program { static void Main(string[] args){ int a = 30, b=5; Console.WriteLine("Sum of a and b is : {0}", a + b); Console.WriteLine("Difference of a and b is : {0}", a - b); Console.WriteLine("Product of a and b is : {0}", a * b); Console.WriteLine("quetient of a and b is : {0}", a / b); Console.WriteLine("Remander of a and b is : {0}", a % b); Console.WriteLine("Incerement of a by 1 is : {0}", ++a); // pre-increment Console.WriteLine("Decrement of b by 1 is : {0}", --b); // post-decrement Console.WriteLine("Incerement of a by 1 is : {0}", a++); // post-increment Console.WriteLine("Decrement of b by 1 is : {0}", b--); // post-decrement Console.WriteLine("Press any key to continue ..."); Console.ReadKey(); } }}
  • 27. 5/5/2021 27 Sum of a and b is : 35 Difference of a and b is : 25 Product of a and b is : 150 quotient of a and b is : 6 Reminder of a and b is : 0 Increment of a by 1 is : 31 Decrement of b by 1 is : 4 Increment of a by 1 is : 31 Decrement of b by 1 is : 4 Press any key to continue ... īƒ˜ When the above code is compiled and executed, it produces the following result:
  • 28. C# Operators(Cont’d) 5/5/2021 28 2. Relational Operators īƒ˜ These are operators used for performing Relational operations on numbers. īƒ˜ Below is the list of relational operators available in C#. Operator Description == Checks if the values of two operands are equal or not, if yes then condition becomes true. != Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. >= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. <= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.
  • 29. 5/5/2021 29 // C# code to demonstrate the use of Relational Operators using System; namespace RelationalOperator{ class Program{ static void Main(string[] args){ int a = 30, b = 5; Console.WriteLine(" a is equal to b {0}", a==b); Console.WriteLine(" a is not equal to b {0}", a!= b); Console.WriteLine(" a is greater than b {0}", a>b); Console.WriteLine(" a is less than b {0}", a<b); Console.WriteLine(" a is greater than or equal to b {0}", a>=b); Console.WriteLine(" a is less than or equal to b {0}", a<=b); Console.WriteLine("Press any key to continue ..."); Console.ReadKey(); }}}
  • 30. 5/5/2021 30 a is equal to b False a is not equal to b True a is greater than b True a is less than b False a is greater than or equal to b True a is less than or equal to b False Press any key to continue ... īƒ˜ When the above code is compiled and executed, it produces the following result:
  • 31. C# Operators (Cont’d) 5/5/2021 31 3. Logical Operators īƒ˜ These are operators used for performing Logical operations on values. īƒ˜ Below is the list of logical operators available in C#. Operator Description && This is the Logical AND operator. If both the operands are true, then condition becomes true. || This is the Logical OR operator. If any of the operands are true, then condition becomes true. ! This is the Logical NOT operator.
  • 32. 5/5/2021 32 // C# code to demonstrate the use of Logical Operators using System; namespace RelationalOperator{ class Program{ static void Main(string[] args){ int a = 30, b = 5; bool c = false; Console.WriteLine(" Logical AND {0}", (a == b)&&(a!=b)); Console.WriteLine(" Logical OR {0}", (a != b)||(a>b)); Console.WriteLine(" Logical Negation {0}", !(c)); Console.WriteLine("Press any key to continue ..."); Console.ReadKey(); }}}
  • 33. 5/5/2021 33 īƒ˜ When the above code is compiled and executed, it produces the following result: Logical AND False Logical OR True Logical Negation True Press any key to continue ...
  • 34. 5/5/2021 34 īƒ˜ An enumeration is used in any programming language to define a constant set of values. īƒ˜ For example, the days of the week can be defined as an enumeration and used anywhere in the program. īƒ˜ In C#, the enumeration is defined with the help of the keyword 'enum’. īƒ˜ enum is a value type data type. The enum is used to declare a list of named integer constants. C# Enum Syntax: enum enum_name{enumeration list} īƒ˜ The enum is used to give a name to each constant so that the constant integer can be referred using its name. īƒ˜ In our example, we will define an enumeration called days, which will be used to store the days of the week. C# Enumeration
  • 35. 5/5/2021 35 // C# code to demonstrate the use of enumeration. using System; namespace Enumeration{ // enum declaration enum days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } ; class Program{ static void Main(string[] args){ Console.WriteLine("Value of Monday is " + (int)days.Monday); Console.WriteLine("Value of Tuesday is " + (int)days.Tuesday); Console.WriteLine("Value of Wednesday is " + (int)days.Wednesday); Console.WriteLine("Value of Thursday is " + (int)days.Thursday); Console.WriteLine("Value of Friday is " + (int)days.Friday); Console.WriteLine("Value of Saturday is " + (int)days.Saturday); Console.WriteLine("Value of Sunday is " + (int)days.Sunday); Console.WriteLine("Press any key to continue ..."); Console.ReadKey(); }}}
  • 36. 5/5/2021 36 īƒ˜ When the above code is compiled and executed, it produces the following result: Value of Monday is 0 Value of Tuesday is 1 Value of Wednesday is 2 Value of Thursday is 3 Value of Friday is 4 Value of Saturday is 5 Value of Sunday is 6 Press any key to continue ...
  • 37. Conditional Statements 5/5/2021 37 1. if statement īƒ˜In c#, if statement or condition is used to execute the block of code or statements when the defined condition is true. īƒ˜Generally, in c# the statement that can be executed based on the condition is known as a “Conditional Statement” and the statement is more likely a block of code. īƒ˜Syntax of C# if Statement: īƒ˜The statements inside of if condition will be executed only when the “expression” returns true otherwise the statements inside of if condition will be ignored for execution. if (expression) { // Statements to Executed if condition is true }
  • 38. 5/5/2021 38 īƒ˜ Following is the example of defining if statement in c# programming language to execute the block of code or statements based on expression. // C# code to demonstrate if statement. using System; namespace IfStatement{ class Program{ static void Main(string[] args){ int x = 20; if(x>0) Console.WriteLine(" x is positve number "); Console.WriteLine(" Press any key to Exit..."); Console.ReadKey(); }}} x is positve number Press any key to Exit... īƒ˜ When this code is compiled and executed, it produces the following result:
  • 39. Conditional Statements (Cont’d) 5/5/2021 39 2. if-else statement īƒ˜In c#, if-else statement or condition is having an optional else statements and these else statements will be executed whenever the if condition is fails to execute. īƒ˜ Generally, in c# if-else statement, whenever the expression returns true, then if statements will be executed otherwise else block of statements will be executed. īƒ˜Syntax of C# if-else Statement if (expression){ // Statements to Executed if expression is True } else { // Statements to Executed if expression is False }
  • 40. 5/5/2021 40 // C# code to demonstrate if-else statement using System; namespace IfElse{ class Program{ static void Main(string[] args){ int x = -20; if(x>0) Console.WriteLine(" x is Positve number "); else Console.WriteLine(" x is Negative number "); Console.WriteLine(" Press any key to Exit..."); Console.ReadKey(); }}} When this code is compiled and executed, it produces the following result: x is Negative number Press any key to Exit...
  • 41. 5/5/2021 41 3. if-else if statement (nested if-else statement) īƒ˜In c#, if-else-if statement or condition is used to define multiple conditions and execute only one matched condition based on our requirements. īƒ˜Generally, in c# if statement or if-else statement is useful when we have a one condition to validate and execute the required block of statements. īƒ˜In case, if we have a multiple conditions to validate and execute only one block of code, then if-else-if statement is useful. Conditional Statements (Cont’d)
  • 42. 5/5/2021 42 īƒ˜Syntax of C# if Statement: if (condition_1){ // Statements to Execute if condition_1 is True } else if (condition_2){ // Statements to Execute if condition_2 is True } .... else{ // Statements to Execute if all conditions are False } īƒ˜Syntax of C# if-else if Statement: īƒ˜ The execution of if-else-if statement will starts from top to bottom and as soon as the condition returns true, then the code inside of if or else if block will be executed and control will come out of the loop. īƒ˜ In case, if none of the conditions return true, then the code inside of else block will be executed.
  • 43. 5/5/2021 43 // C# code to demonstrate nested if-else statement using System; namespace NestedIfElse{ class Program{ static void Main(string[] args){ int x = 0; if(x>0) Console.WriteLine(" x is Positve number "); else if (x==0) Console.WriteLine(" x is Zero "); else Console.WriteLine(" x is Negative number "); Console.WriteLine(" Press any key to Exit..."); Console.ReadKey(); }}} x is Negative number Press any key to Exit... When this code is compiled and executed, it produces the following result:
  • 44. 5/5/2021 44 3. C# Ternary Operator (?:) īƒ˜In c#, Ternary Operator (?:) is a decision making operator and it is a substitute of if-else- if statement in c# programming language. īƒ˜ By using Ternary Operator, we can replace multiple lines of if-else-if statement code into single line in c# programming language. īƒ˜ The Ternary operator we will help you to execute the statements based on the defined conditions using decision making operator (?:). īƒ˜In c#, the Ternary Operator will always work with 3 operands. īƒ˜ Syntax of C# Ternary Operator: īƒ˜In Ternary Operator, the condition expression must be evaluated to either true or false. If condition is true, the first_expression result returned by the ternary operator. īƒ˜In case, if condition is false, then the second_expression result returned by the operator. Conditional Statements (Cont’d) condition_expression ? first_expression : second_expression;
  • 45. 5/5/2021 45 x value less than y Press any key to Exit... // C# code to demonstrate C# Ternary Operator (?:) using System; namespace TernaryOperator{ class Program{ static void Main(string[] args){ int x =10, y=20; string result; result = (x > y) ? "x value greater than y" : (x < y) ? "x value less than y" : "x value equals to y"; Console.WriteLine(result); Console.WriteLine(" Press any key to Exit..."); Console.ReadKey(); }}} īƒ˜ When this code is compiled and executed, it produces the following result:
  • 46. 5/5/2021 46 4. Switch statement īƒ˜In c#, Switch is a selection statement and it will execute a single case statement from the list of multiple case statements based on the pattern match with the defined expression. īƒ˜ By using switch statement in c#, we can replace the functionality if –else if statement to provide a better readability for the code. īƒ˜Generally, in c# switch statement is a collection of multiple case statements and it will execute only one single case statement based on the matching value of expression. Conditional Statements (Cont’d)
  • 47. 5/5/2021 47 switch(variable/expression){ case value1: // Statements to Execute break; case value2: //Statements to Execute break; .... default: // Statements to Execute if No Case Matches break; } Syntax of C# Switch Statement
  • 48. 5/5/2021 48 // C# code to demonstrate switch statement using System; namespace SwitchStatement{ class Program{ static void Main(string[] args){ char op; int a=20, b=10; int result=0; Console.WriteLine("Enter an operator"); op = (char)Console.Read(); //op = Console.ReadLine(); switch (op){ case '+': result = a + b; Console.WriteLine("Sum of a and b is :{0} ",result); break; case '-': result = a - b; Console.WriteLine("Difference of a and b is :{0} ", result); break; //code continue on the next pageâ€Ļ.. . Enter an operator + Sum of a and b is :30 Press any key to exit... īƒ˜ When this code is compiled and executed, it produces the following result:
  • 49. 5/5/2021 49 case '*': result = a * b; Console.WriteLine("Product of a and b is :{0} ", result); break; case '/': result = a / b; Console.WriteLine("Quetient of a and b is :{0} ", result); break; case '%': result = a % b; Console.WriteLine("Remiender of a and b is :{0} ", result); break; default: Console.WriteLine("Invalid Operator"); break; } Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }}}
  • 50. 5/5/2021 50 īƒ˜Looping statement are the statements execute one or more statement repeatedly several number of times. 1. For Loop īƒ˜for loop is useful to execute a statement or a group of statements repeatedly until the defined condition returns true. īƒ˜Generally, for loop is useful in c# applications to iterate and execute the certain block of statements repeatedly until the specified number of times. īƒ˜Syntax of C# For Loop Looping Statements for(initialization; test-condition; iterator(increment/decrement)){ //statements to execute }
  • 51. 5/5/2021 51 1 2 3 4 5 6 7 8 9 10 Press any key to exit.. // C# code to demonstrate for loop statement using System; namespace ForLoop{ class Program { static void Main(string[] args){ for (int i = 1; i <= 10; i++){ Console.Write(" "+i); } Console.WriteLine("n Press any key to exit.."); Console.ReadKey(); }}} â€ĸ If you observe this code, â€ĸ we defined a for loop to iterate over 10 times to print the value of variable i and following are the main parts of for loop. â€ĸ Here, â€ĸ int i = 1 is the initialization part â€ĸ i <= 10 is the test-condition part â€ĸ i++ is the iterator part īƒ˜When the above code is compiled and executed, it produces the following result:
  • 52. 5/5/2021 52 For Loop without Initialization & Iterators īƒ˜Generally, the initializer, condition and iterator parameters are optional to create for loop in c# programming language. īƒ˜ Syntax of for loop without initialization and iterator īƒ˜Following is the example of creating a for loop in c# programming language without initializer and iterator. â€Ļ on the next pageâ€Ļ Looping Statements(Cont’d) initialization; for(;test-condition;){ // statements to execute iterator; }
  • 53. 5/5/2021 53 // C# code to demonstrate for loop statement without initialization and iterator using System; namespace ForLoop1{ class Program{ static void Main(string[] args){ int i=1; for (; i <= 10; ){ Console.Write(" " + i); i++; } Console.WriteLine("n Press any key to exit.."); Console.ReadKey(); }}} īƒ˜ When the above code is compiled and executed, it produces the following result: 1 2 3 4 5 6 7 8 9 10 Press any key to exit..
  • 54. 5/5/2021 54 īƒ˜C# Infinite For Loop īƒ˜In case, if the condition parameter in for loop always returns true, then the for loop will be an infinite and runs forever. īƒ˜Even if we miss the condition parameter in for loop automatically that loop will become an infinite loop. īƒ˜ Following are the different ways to make for loop as an infinite loop in c# programming language. Looping Statements(Cont’d) for (initializer; ; iterator) { // Statements to Execute } or (initializer; ; iterator) { // Statements to Execute } or for ( ; ; ){ // Statements to Execute }
  • 55. 5/5/2021 55 //Following is the example of making a for loop as an infinite in c# programming language. using System; namespace InfiniteForLoop{ class Program{ static void Main(string[] args){ for (int i = 1; i > 0; i++){ Console.Write(" " + i); i++; } Console.WriteLine("n Press any key to exit.."); Console.ReadKey(); }}}
  • 56. 5/5/2021 56 C# Nested For Loop īƒ˜In c#, we can create one for loop within another for loop based on our requirements. Looping Statements(Cont’d) //Following is the example of creating a nested for loop in c# programming language. using System; namespace NestedForLoop{ class Program{ static void Main(string[] args){ for (int i = 1; i <=3; i++){ for (int j = 1; j <=2; j++){ Console.Write(" {0} {1}, ", i, j); }} Console.WriteLine("nPress Enter Key to Exit.."); Console.ReadKey(); }}} 1 1, 1 2, 2 1, 2 2, 3 1, 3 2, Press Enter Key to Exit.. īƒ˜ When this code is compiled and executed, it produces the following result: Note: the inner for loop evaluated first. Until the test condition of inner loop becomes false execution of code stay at inner loop.
  • 57. 5/5/2021 57 2. While Loop īƒ˜In c#, While loop is used to execute a block of statements until the specified expression return as a true. īƒ˜ Generally, the for loop is useful when we are sure about how many times we need to execute the block of statements. In case, if we are unknown about the number of times to execute the block of statements, then while loop is the best solution. īƒ˜Syntax of C# While Loop: īƒ˜ if expression returns true, then the statements inside of while loop will be executed. while (expression) { // Statements to Execute } Looping Statements(Cont’d)
  • 58. 5/5/2021 58 //C# code to demonstrate while loop statement using System; namespace WhileLoop{ class Program{ static void Main(string[] args){ int i = 1; while (i<=5){ Console.Write(" " + i); i++; } Console.Write("nPress any key to exit..."); Console.ReadKey(); }}} īƒ˜ When this code is compiled and executed, it produces the following result: 1 2 3 4 5 Press any key to exit..
  • 59. 5/5/2021 59 3. Do While Loop īƒ˜In c#, Do-While loop is used to execute a block of statements until the specified expression return as a true. īƒ˜ Generally, in c# the do-while loop is same as while loop but only the difference is while loop will execute the statements only when the defined condition returns true, but do-while loop will execute the statements at least once, because first it will execute the block of statements and then it will checks the condition. īƒ˜Syntax of C# Do-While Loop: īƒ˜The body of do-while loop will be executed first, then the expression will be evaluated. if expression returns true, then again the statements inside of do-while loop will be executed. īƒ˜In case, the expression is evaluated to false, then the do-while loop stops the execution of statements and the program comes out of the loop. do{ // Statements to Execute }while (expression); Looping Statements(Cont’d)
  • 60. 5/5/2021 60 // C# code to demonstrate do-while loop statement. using System; namespace WhileLoop{ class Program{ static void Main(string[] args){ int i = 1; do{ Console.Write(" " + i); i++; }while (i<=5); Console.Write("nPress any key to exit..."); Console.ReadKey(); }}} īƒ˜ When this code is compiled and executed, it produces the following result: 1 2 3 4 5 Press any key to exit..
  • 61. 5/5/2021 61 4. Foreach Loop īƒ˜In c#, Foreach loop is used to loop through an each item in array or collection object to execute the block of statements repeatedly. īƒ˜ Generally, in c# Foreach loop will work with the collection objects such as arrays, list, etc. to execute the block of statements for each element in the array or collection. īƒ˜After completion of iterating through an each element in collection, control is transferred to the next statement following the foreach block. īƒ˜ In c#, we can use break, continue, goto and return statements within foreach loop to exit or continue to the next iteration of the loop based on our requirements. īƒ˜Syntax of C# Foreach Loop: Looping Statements(Cont’d) foreach (Type var_name in Collection_Object) { // Statements to Execute }
  • 62. 5/5/2021 62 īƒ˜ When the above code is compiled and executed, it produces the following result: //C# code to demonstrate foreach loop statement using System; namespace ForeachLoop{ class Program{ static void Main(string[] args){ string[] names = new string[4] { "Computer Science", "Accounting ", "Economics","Information Technology" }; foreach (string name in names){ Console.WriteLine(name); } Console.WriteLine("Press Enter Key to Exit.."); Console.ReadLine(); }}}
  • 63. 5/5/2021 63 īƒ˜5. 1. Break Statement īƒ˜In c#, Break statement is used to break or terminate the execution of loops (for, while, do-while, etc.) or īƒ˜ switch statement and the control is passed immediately to the next statements that follows a terminated loops or statements. īƒ˜ In c# nested loops also we can use break statement to stop or terminate the execution of inner loops based on our requirements. īƒ˜Syntax of C# Break Statement: īƒ˜In our applications, we can use break statement whenever we want to stop the execution of particular loop or statement based on our requirements. Jumping Statements(Cont’d) break;
  • 64. 5/5/2021 64 // C# code to demonstrate break statement with for loop statement using System; namespace BreakStatement{ class Program{ static void Main(string[] args){ for (int i = 1; i <= 5; i++){ if (i == 3) break; Console.Write(" " + i); } Console.WriteLine("n Press any key to exit.."); Console.ReadKey(); }}} īƒ˜ When the above code is compiled and executed, it produces the following result: 1 2 Press any key to exit..
  • 65. 5/5/2021 65 6. Continue Statement īƒ˜In c#, Continue statement is used to pass a control to the next iteration of loops such as for, while, do-while or foreach from the specified position by skipping the remaining code. īƒ˜ The main difference between break statement and continue statement is, the break statement will completely terminate the loop or statement execution but the continue statement will pass a control to the next iteration of loop. īƒ˜Syntax of C# Continue Statement: īƒ˜In our applications, we can use continue statement whenever we want to skip the execution of code from the particular position and send back the control to next iteration of loop based on our requirements. Looping Statements(Cont’d) continue;
  • 66. 5/5/2021 66 // C# code to demonstrate continue statement with for loop statement using System; namespace BreakStatement{ class Program{ static void Main(string[] args){ for (int i = 1; i <=5; i++){ if (i == 3) continue; Console.Write(" " + i); } Console.WriteLine("n Press any key to exit.."); Console.ReadKey(); }}} īƒ˜ When this code is compiled and executed, it produces the following result: 1 2 4 5 Press any key to exit..
  • 67. 5/5/2021 67 6. Goto Statement īƒ˜In c#, Goto statement is used to transfer a program control to the defined labeled statement and it is useful to get out of the loop or exit from a deeply nested loops based on our requirements. īƒ˜ Generally, in c# the defined labeled statement must always exists in the scope of goto statement and we can define multiple goto statements in our application to transfer the program control to specified labeled statement. īƒ˜Syntax of C# goto Statement: īƒ˜a goto statement by using goto keyword and with labeled_statement. Here the labeled_statement is used to transfer the program control to specified labeled_statement position. Looping Statements(Cont’d) goto labeled_statement;
  • 68. 5/5/2021 68 // C# code to demonstrate continue statement with for loop statement using System; namespace GotoStatement{ class Program{ static void Main(string[] args){ for (int i = 1; i <= 5; i++){ if (i == 3) goto m; Console.Write(" " + i); } m:Console.WriteLine("n The end"); Console.WriteLine("n Press any key to exit.."); Console.ReadKey(); }}} īƒ˜ When the above code is compiled and executed, it produces the following result: 1 2 The end Press any key to exit..
  • 69. 5/5/2021 69 6. Return Statement īƒ˜ In c#, Return statement is used to terminate the execution of method in which it appears and returns the control back to the calling method. īƒ˜Generally, in c# the return statement is useful whenever we want to get a some value from the other methods and we can omit the usage of return statement in our methods by using void as a return type. īƒ˜Syntax of C# return Statement: Looping Statements(Cont’d) return return_val;
  • 70. 5/5/2021 70 // C# code to demonstrate return statement with function or method using System; namespace ReturnStatement{ class Program{ static void Main(string[] args){ int i = 10, j = 20, result = 0; result = add(i, j); Console.WriteLine("Sum of i and J is : {0}", result); Console.WriteLine("Press Enter Key to Exit.."); Console.ReadKey(); } public static int add(int a, int b){ int x = a + b; return x; }}} īƒ˜ When the above code is compiled and executed, it produces the following result: Sum of i and J is : 30 Press Enter Key to Exit..
  • 71. 5/5/2021 71 īƒ˜A method (Function) is a group of statements that together perform a task. īƒ˜Every C# program has at least one class with a method named Main. īƒ˜Methods are generally the block of codes or statements in a program that gives the user the ability to reuse the same code which ultimately saves the excessive use of memory, acts as a time saver and more importantly, it provides a better readability of code. īƒ˜ So basically, a method is a collection of statements that perform some specific task and return the result to the caller. īƒ˜ A method can also perform some specific task without returning anything. īƒ˜To use a method, you need to: â€ĸ Define the method â€ĸ Call the method Method in C#
  • 72. 5/5/2021 72 īƒ˜Method Declaration īƒ˜Method declaration means the way to construct method including its naming. Syntax : Method (Cont’d) <access-modifier> <return-type> <method-name>([parameter-lists])
  • 73. 5/5/2021 73 īƒ˜In C# a method declaration consists of following components as follows : īƒ˜Modifier : It defines access type of the method i.e. from where it can be accessed in your application. īƒ˜ In C# there are Public, Protected, Private, static access modifiers. īƒ˜Name of the Method : It describes the name of the user defined method by which the user calls it or refer it. Eg. add() īƒ˜Return type: It defines the data type returned by the method. īƒ˜It depends upon user as it may also return void value i.e return nothing īƒ˜Body of the Method : It refers to the line of code of tasks to be performed by the method during its execution. īƒ˜ It is enclosed between braces. Method (Cont’d)
  • 74. 5/5/2021 74 īƒ˜Parameter list : Comma separated list of the input parameters are defined, preceded with their data type, within the enclosed parenthesis. īƒ˜If there are no parameters, then empty parentheses () have to use out. īƒ˜The Method Body : consists of statements of code which a user wants to perform. īƒ˜After the method has been declared, it is dependent on the user whether to define its implementation or not. īƒ˜Not writing any implementation, makes the method not to perform any task. īƒ˜ However, when the user wants to perform certain tasks using method then it must write the statements for execution in the body of the method. īƒ˜The below syntax describes the basic structure of the method body : Method (Cont’d) <return_type> <method_name>(<parameter_list>){ // Implementation of the method code goes here..... }
  • 75. 5/5/2021 75 Method Calling īƒ˜Method Invocation or Method Calling is done when the user wants to execute the method. īƒ˜ The method needs to be called for using its functionality. īƒ˜A method returns to the code that invoked it when: â€ĸ It completes all the statements in the method â€ĸ It reaches a return statement â€ĸ Throws an exception īƒ˜The next code example shows a function add that takes two integer values and returns the sum of the two integers. īƒ˜It has public access specifier, so it can be accessed from outside the class using an instance of the class. Method (Cont’d)
  • 76. 5/5/2021 76 // C# program to returns the sum of two numbers using method using System; namespace Method{ class Program { public int add(int x, int y){ int result=0; result = x + y; return result; } static void Main(string[] args){ Program n=new Program(); int a = 10, b = 20, c=0; c = n.add(a, b); Console.WriteLine("The sum of a and b is: " + c); Console.WriteLine("Press any key to exit.."); Console.ReadKey(); }}} īƒ˜ When this code is compiled and executed, it produces the following result: The sum of a and b is: 30 Press any key to exit..
  • 77. 5/5/2021 77 Advantages of using the Methods : īƒ˜ Some of the advantages of methods are listed below: īƒŧIt makes the program well structured. īƒŧMethods enhance the readability of the code. īƒŧIt provides an effective way for the user to reuse the existing code. īƒŧIt optimizes the execution time and memory space. Method (Cont’d)
  • 78. 5/5/2021 78 īƒ˜Properties are named members of classes, structures, and interfaces. īƒ˜ Member variables or methods in a class or structures are called Fields. īƒ˜Properties are an extension of fields and are accessed using the same syntax. īƒ˜They use accessors through which the values of the private fields can be read, written or manipulated. īƒ˜The accessor of a property contains the executable statements that helps in getting (reading or computing) or setting (writing) the property. īƒ˜The accessor declarations can contain a get accessor, a set accessor, or both. C# Properties
  • 79. 5/5/2021 79 using System; namespace Properties{ class Program { private string code = "N.A"; private string name = "not known"; private int age = 0; public string Code{ // Declare a Code property of type string: get{ return code; } set{ code = value; } } public string Name{ // Declare a Name property of type string: get { return name; } set{ name = value; }} // code continue on the next pageâ€Ļ
  • 80. 5/5/2021 80 public int Age{ // Declare a Age property of type int: get{ return age; } set{ age = value; }} public override string ToString() { return "Code = " + Code +", Name = " + Name + ", Age = " + Age; }} class ExampleDemo { public static void Main() { Program s = new Program(); // Create a new Student object: s.Code = "RET/858/02"; // Setting code, name and the age of the student s.Name = "Lalise"; s.Age = 20; Console.WriteLine("Student Info: {0}", s); s.Age += 1; Console.WriteLine("Student Info: {0}", s); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } }} īƒ˜ When this code is compiled and executed, it produces the following result: Student Info: Code = RET/858/02, Name = Lalise, Age = 20 Student Info: Code = RET/858/02, Name = Lalise, Age = 21 Press any key to exit...
  • 81. 5/5/2021 81 Errors īƒ˜ Programming errors are generally broken down into three types: 1. Design-time, 2. Runtime, and 3. Logic errors. 1. Design Time Errors īƒ˜ A Design-time error is also known as a syntax error. īƒ˜ These occur when the environment you're programming in doesn't understand your code. īƒ˜ These are easy to track down in C#, because you get a blue wiggly line pointing them out. īƒ˜ If you try to run the program, you'll get a dialogue box popping up telling you that there were Build errors. Exception (Error) Handling in C#
  • 82. 5/5/2021 82 2. Run Time Errors īƒ˜ Runtime errors are a lot harder to track down. As their name suggests, these errors occur when the program is running. īƒ˜ They happen when your program tries to do something it shouldn't be doing. īƒ˜ An example is trying to access a file that doesn't exist. īƒ˜ Runtime errors usually cause your program to crash. You should write code to trap runtime errors. 3. Logic Errors īƒ˜ Logic errors also occur when the program is running. īƒ˜ They happen when your code doesn't quite behave the way you thought it would. īƒ˜ A classic example is creating an infinite loop of the type "Do While x is greater than 10". If x is always going to be greater than 10, then the loop has no way to exit, and just keeps going round and round. īƒ˜ Logic errors tend not to crash your program. But they will ensure that it doesn't work properly. Exceptionâ€Ļ(Cont’d)
  • 83. 5/5/2021 83 Exceptions īƒ˜ Are events which may be considered exceptional or unusual. īƒ˜ They are conditions that are detected by an operation, that cannot be resolved within the local context of the operation and must be brought to the attention of the operation invoker. Exception Handler īƒ˜ Is a procedure or code that deals with the exceptions in your program. Raising Exceptions īƒ˜ The process of noticing exceptions, interrupting the program and calling the exception handler. Propagating the Exceptions īƒ˜ Reporting the problem to higher authority (the calling program) in your program. Handling the Exceptions īƒ˜ The process of taking appropriate corrective action. Exceptionâ€Ļ(Cont’d)
  • 84. 5/5/2021 84 Example of exceptions 1. Array out of bound 2. Divide by zero 3. Implicit type casting 4. Input/output exception 5. File not found exception Structured Exception Handling īƒ˜ C# has a built-in class that deals with errors. īƒ˜ The class is called Exception. When an exception error is found, an exception object is created. The exception object contains information relevant to the error exposed as properties of the object. īƒ˜ The object is an instance of a class that derived from a class named System.Exception. īƒ˜ The coding structure C# uses to deal with such Exceptions is called the Try â€Ļ Catch structure. Exceptionâ€Ļ(Cont’d)
  • 85. 5/5/2021 85 īƒ˜ Depends on several key words. Try: īƒ˜ Begins a section of a code in which an exception might be generated from a code error. īƒ˜ This section is called the Try Block. And it means "Try to execute this code". īƒ˜ A trapped exception is automatically routed to the Catch statement. Catch: īƒ˜ Begins an exception handler for a type of exception. īƒ˜ One or more catch code blocks follow a try block, with each catch block catching a different type of exception. Finally: īƒ˜ Contains code that runs when the try block finishes normally, or when a catch block receives control then finishes. īƒ˜ Is a block that always runs regardless of whether an exception is detected or not. ī‚§ Example: closing a database connection. Exceptionâ€Ļ(Cont’d)
  • 86. 5/5/2021 86 Implementing Exception Handling īƒ˜ Exception handlers are implemented for specific methods. īƒ˜ The following three general steps are involved in creating exception handler. īƒ˜ Wrap the code with which the handler will be associated in a Try block īƒ˜ Add one or more Catch block to handle the possible exceptions īƒ˜ Add any code that is always executed regardless of whether or not an exception is thrown to a Finally block īƒ˜ Structure Try ' normal program code goes here Catch ' catch block goes here (error handling) Finally ' finally block goes here End Try Exceptionâ€Ļ(Cont’d)
  • 87. 5/5/2021 87 // C# divide by zero exception handling program using System; namespace ExceptionHandling{ class Program { static void Main(string[] args){ try{ int x = 10, y = 0, result = 0; result = x / y; Console.WriteLine("Result = " + result); } catch{ } finally{ Console.WriteLine("End of Execution"); } Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }}} īƒ˜ When this code is compiled and executed, it produces the following result: End of Execution Press any key to exit...