KEMBAR78
1. Introduction to C# Programming Langua | PPTX
1
University of Computer Studies
University of Computer Studies
Introduction to C#
Contents
 Programming Framework
 Why use Programming Framework
 Types of Programming Framework
 Microsoft .Net Framework
 Types of Application
 Integrated Development Environment (IDE)
 Overview of C#
 Feature of C#
 Program Structure
 Declaration Space
 Namespace
 Block
 Read( ), ReadLine( ), ReadKey( )
 Syntax
2
 A framework is a set of tools in programming on which to build well-structured, reliable software and systems.
 It is ready to use collection of classes and interfaces used for developing a particular type of application.
 It can include support programs, compilers, code libraries, toolsets, and APIs to develop software and create
systems.
 Open-source frameworks are always being updated and improved.
Programming Framework
3
 It makes programming easy.
 It allows us to compile all necessary resources and codes into application.
 It support multiple languages.
 It are used to save time and money.
Why use Framework
4
 Web Frameworks
 Front-End Frameworks
 Back-End Frameworks
 Mobile App Development Frameworks
 Content Management Frameworks
 Data Science Frameworks
Type of Programming Framework
5
 The .Net framework is a software development by Microsoft.
 The .Net framework can be used to create both - Form-based and Web-based applications.
 Web services can also be developed using the .Net framework.
 The first version of the .Net framework was released in the year 2002.
 The framework also supports various programming languages such as Visual Basic and C#, etc.
Microsoft .Net Framework
6
Cont’d
7
Common Language Runtime
 The Common Language Runtime (CLR), the virtual machine
component of Microsoft .NET framework, manages the execution
of .NET programs.
Class Library
 The .NET Framework includes a set of standard class libraries.
 A class library is a collection of methods and functions that can be
used for the core purpose.
Languages
 The types of applications that can be built in the .Net framework is
classified broadly into the following categories.
 WinForms
 ASP.Net
 ADO.Net
Cont’d
8
C#
Code
C#
Compiler
F#
Code
F#
Compiler
Visual
Basic
Code
Visual Basic
Compiler
Common
Intermediate
Language (CIL)
Common
Language
Runtime (CLR)
Machine code
101000001101001
CLR
 The Common Language Runtime (CLR)'s just in time (JIT)
compilation converts Intermediate Language (MSIL) to native
code on demand at application run time.
CIL
 The Microsoft Intermediate Language (MSIL), also known as
the Common Intermediate Language (CIL) is a set of
instructions that are platform independent and are generated by
the language-specific compiler from the source code.
 Console Application
 Window Application
 Window Store Application
 Mobile Application
 Web Application
 Enterprise Application
 Games
Types of Application
9
 An IDE is a tool that helps to write program.
 Viusal Studio is an IDE provided by Micorsoft to write the code in the language such C#, F#, VisualBasic,etc.
Integrated Development Environment (IDE)
10
Cont’d
11
Cont’d
12
 C# is a simple & powerful object-oriented programming language developed by Microsoft.
 C# can be used to create various types of applications, such as web, windows, console applications or other types
of applications using Visual studio.
 C# was developed by Anders Hejlsberg and his team during the development of .NET Framework.
 The ‘#’ comes from the musical notation meaning C# is higher than C.
 The safety of Java
 The ease of Visual Basic
 The power of C++
 It uses the .NET Framework
Overview of C#
13
Cont’d
14
 C# compiler translates C# code into assembly-like language called Intermediate Language (IL).
 CLR (Common Language Runtime) is a virtual machine component of the .Net Framework that translates IL into native
machine code when run a C# program.
 CLR use a just-in-time complier (JIT compiler) to compile pieces of IL code.
 C# is case sensitive
 All statements and expressions 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.
Features of C#
15
using System;
using System.Data;
namespace <project name>
{
<modifier > class <class name>
{
static void Main()
{
[statements]
}
}
}
Program Structure
16
C# program consist of the following parts:
 Namespace declaration
 A class
 Class methods
 Class attributes
 A Main method
 Statements and Expressions
 Comments
Cont’d
17
using System;
namespace MyFirstProgram
{ class Testing
{
static void Main(string[] args)
{
/* my first program in C# */
Console.WriteLine(“Good Morning, Welcome To C# Class");
Console.ReadLine();
}
}
}
Console.Read() accepts the first character of the string and returns ASCII Code(Integer Value) of that first character.
Console.Readline() accepts the string and returns the string.
Console.ReadKey( ) obtains the next character or function key pressed by the user.
Read( ), ReadLine( ), ReadKey( )
18
 Case-sensitive
 White space means nothing
 Semicolons ( ; ) to terminate statements
 Code blocks use curly braces ( { } )
 // (for single line) or /* */ (for multi lines)
 /// (for automatic XML documentation)
Syntax
19
References
 C# 5.0 Programmer’s Reference
 www.w3schools.com
 www.tutuorialTeacher.com
 www.javapoint.com
 www.tutorialspoint.com
20
21
University of Computer Studies
University of Computer Studies
Chapter (1)
Basic Concepts
Contents
 Data Types
 Default Values
 Variable
 Naming Variable
 Variable Declaration
 Constant Variable
 Keywords
 Literals
 Escape Character
 Comments
22
Contents
 Data Type Conversion
 Implicit Conversion
 Explicit Conversion
 Scope
 Nullable Type
 Enumeration
 Array
 One-Dimensional Array
 Multi- Dimensional Array
 Jagged Array
23
Data Types
24
Cont’d
25
Reference Data Types
Value Data Types
C# Data Types
Pointer
Predefined Types User-defined Types Predefined Types User-defined Types
bool
byte
ubyte
char
short
ushort
int
uint
long
ulong
decimal
float
double
DateTime
enum
struct
Object
string
class
interfaces
delegates
Cont’d
26
Name Type Size
Boolean bool 1 bytes
Byte byte 1 bytes
Singed byte sbyte 1 bytes
Character char 2 bytes
Short integer short 2 bytes
Unsigned short integer ushort 2 bytes
Integer int 4 bytes
Unsigned integer uint 4 bytes
Long integer long 8 bytes
Unsigned long integer ulong 8 bytes
Cont’d
27
Decimal decimal 16 bytes
Single-precision floating point
number
float 4 bytes
Double-precision floating point
number
double 8 bytes
String string varies
Date and Time DateTime 8 bytes
Object object 4 bytes
Class class varies
Structure struct varies
Cont’d
28
Variable store in Memory
29
 Stack is used for static memory allocation.
 It is stored in the computer's RAM.
 Use the stack if you know exactly how much data
you need to allocate before compile time and it is not
too big.
 It is LIFO data structure.
 It is stored Directly.
 Variables can’t be resized.
 Its access fast.
Stack and Heap
30
 Heap is used for dynamic memory allocation.
 It is stored in the computer's RAM.
 Use heap if you don't know exactly how much data you
will need at runtime or if you need to allocate a lot of data.
 Chunks are allocated to store certain kinds of data objects.
 Data can be stored and removed in any order.
 It is stored indirectly.
 Variables can be resized.
 Its access is slow.
Stack and Heap
31
Value Type Reference Type
 A value type is a simple data type such as int or float that represents the data directly.
 Fixed length
 Store on the stack
 Predefined value types : Numeric types, Boolean types and Character types
 User-defined value types : struct and enumerations
 A new type : nullable type
 this type variable can hold an undefined value
 any value type variable can be defined as a nullable type
Data Types: Value Type
32
Data Types: Value Type
33
Example: int num = 100;
num
int x=10;
int y = x;
x
value copied
y
10
10
Stack
Stack
 Stores the value in heap and its reference in stack.
 String, all Arrays, Class, Object, Interface, Delegates are reference type.
 Variable length
Data Types: Reference Type(Eg-1)
34
Stack Heap
Hello, Good
Morning
0x33
0x33
Address where the
value is stored
Actual Value
string st = “Hello, Good Morning”;
st
Data Types: Reference Type(Eg-2)
35
Data Types: Reference Type
36
 User-defined type ( or complex type)
Classes, Interface, Delegates and Arrays
 Predefined ( or simple ) types
Object type and String type
Circle c = new Circle( )
Stack Heap
c
object
 When an assignment between two reference variables occurs, only the reference is copied
 The actual value remains in the same memory location (i.e. there are two references to a single value)
Data Types: Reference Type
37
Person p1 = new Person( );
p1.name = “Su Su”;
Person p2 = p1;
Stack Heap
0x332255
0x332255
p1
p2
Su Su
0x332255
Reference
copied
Default Value
38
Type Default Value
All Integer Types 0
char type ‘x000’
float type 0.0f
double type 0.0d
decimal type 0.0m
bool type false
enum type 0
All reference type null
 A variable is a name given to storage area that is used to store a value of various data types.
 It is a box in the computer’s memory holding temporary information.
 Each variable in C# have a specific type.
 A variable is either explicitly assigned a value or automatically assigned a default value.
Variable
39
 It should begin a letter (A-Z, a-z), underscore, or @ symbol.
 After that it can include letters (A-Z, a-z), numbers (0-9), or underscore.
 If the name begins with @, it must include at least one other character.
 It cannot contain special characters such as &, %, #, and $.
 It cannot be the same as C# keywords such as if, for, and public, etc.
 num1 - valid
 Num1 - valid
 student_Name - valid
 class - invalid
 student Name - invalid
 #studentName - invalid
 return - invalid
 1num - invalid
Naming Variable
40
 int num; // declare num variable with “int” data type
 int amount = 30000; // declare int type variable named “amount” with initialization
 double[] salary; // declare salary variable with double array type
 string[,] student; // declare student variable with two dimensions string array type
 const double pi = 3.14 // declare constant variable pi with double type. Its value cannot be changed later.
Variable Declaration
41
 A variable whose value will not change during the lifetime of the program.
 A constant variable must be initialized at its declaration.
 “const” keyword is used to declare constant variable.
 Constant variable is stored on stack.
 Constant is used to create a variable which value can not be changed.
 Value of constant must be computable at compile time.
Constant Variable
42
 A null value indicates that a field does not contain any data.
 A value type cannot be assigned a null value.
 For example, int i = null will give you a compile time error.
 C# introduced nullable types that allow you to assign null to value type variables.
 Nullable types can only be used with value types.
Nullable Type
43
Example
int? i = null;
double? num = null;
num = 4.5;
Keywords
44
 Keywords are words that have a predefined meaning in a programming language.
 Keywords are reserved words that developers or programmers cannot use as the name of a variable.
Value Keywords
 class , delegate , interface , object , string , void
Keywords
45
Modifier Type Keywords
Reference Type Keywords
Keywords
46
Statement Keywords
Method Parameter Keywords
 params , in, ref, out
Keywords
47
Operator Keywords
Access Keywords
 base, this
 is , new, sizeof, typeof, true, stackalloc
Namespace Keywords
 extern, namespace, and using
Literals
48
 A literal of integer type is know as the integer literal.
 It is used to write values of types int, uint, long, and ulong.
 It can be octal, decimal, binary, or hexadecimal constant.
 A prefix specifies the base.
 No prefix is required for the decimal numbers.
 A suffix can also be used with the integer literals like U or u are used for unsigned numbers while l or L are used for long
numbers.
Example
20 // int
30u // unsigned int
30l // long
0x4b // hexadecimal
Literal: Integer Literal
49
Literal: Literal Type Character
50
Character Data Type
U uint
L long
UL, LU ulong
F float
D double
M decimal
 Real literals are used to write values of types float, double, and decimal.
 one or more digits containing a decimal point (the decimal point can appear before, within, or after the digits),
 optionally preceded by a sign (+ or -),
 optionally followed by an exponent letter and exponent,
 optionally followed by kind type parameter.
Example
float ff = -12.55f;
double dd = 2.5e-5D;
decimal mm = 1234e5M;
Literal: Real Literal
51
 only two Boolean literals: true and false
Example:
bool flag = false;
Literal: Boolean Literal
52
 ‘2’ ( Single character literals )
 “2000019” ( String literals )
Example:
char grade=‘A’;
string result=“Credit”;
Literal: Single Character Literals &
String Literals
53
Escape Character
54
Escape Character Meaning
a alert
b backspace
f form feed
n new line
r carriage return
t horizontal tab
v vertical tab
’ single quote
” double quote
 backslash
0 null
Data Type and Size
55
1. Single line comments
int num = 10; // variable declaration
2. Multi-line comments
/* The following is a multi-line
Comment in C# */
Comments
56
Type of Conversion
57
Data Type Conversion
It happens when the value of one data type
is assigned to another data type.
Boxing
UnBoxing
 Compiler converts automatically
 Smaller data type to larger data type
Implicit Conversion
58
From Data Type To Data Type
byte short,int,long,float,double
short int, long, float,double
int long, float, double
long float,double
float double
class Program
{
static void Main(string[] args)
{
int a = 10;
int b = 20;
double c = a + b;
Console.WriteLine("The result is"+ c);
Console.ReadLine();
}
}
Output->The result is 30
Implicit Conversion
59
Smaller data type to larger data type
 The developer change manually.
 Larger type to smaller type.
 There are two ways to convert a value from one type to another type.
(1)Casting
Example: long salary = 300000;
int empSalary = (int)salary;
(2) Parsing
Example: double a = 30.0;
int c = Convert.ToInt32(a);
Explicit Conversion
60
Explicit Conversion
61
No Method Description
1 ToBoolean Convert a type to a Boolean value, where possible
2 ToByte Convert a type to a byte
3 ToChar Convert a type to a single Unicode character, where possible
4 ToDateTime Convert a type (integer or string type) to date-time structures
5 ToDecimal Convert a floating point or integer type to a decimal type
6 ToDouble Convert a type to a double type
7 ToInt16 Convert a type to a 16 bit integer
8 ToInt32 Convert a type to a 32 bit integer
Explicit Conversion
62
No Method Description
9 ToInt64 Convert a type to a 64 bit integer
10 ToSbyte Convert a type to a singed byte type
11 ToSingle Convert a type to a small floating point number
12 ToString Convert a type to a string
13 ToType Convert a type to a specified type
14 ToUInt16 Convert a type to an unsigned int type
15 ToUInt32 Convert a type to an unsigned long type
16 ToUInt64 Convert a type to an unsigned big integer
Example: int i = 20;
object x = i ;
Example: object x = 5;
int y = (int)x;
int z = Convert.ToInt32(x);
Boxing and Unboxing
63
Value Type to Reference Type (Boxing)
Reference Type to Value Type (Unboxing)
 A variable’s scope determines which other pieces of code can access it.
 If a variable is declared inside a method, only code within that method can access the variable.
Scope
64
Block Level Scope
 Block is a series of statements enclosed in braces.
 If a variable is declared within a block of code, the variable has block
scope, and only other code within that block can access this variable.
Block Level Scope
65
using System;
namespace VariableScope {
class Program {
static void Main(string[] args) {
for (int i = 0; i <= 3; i++) //Block Level Variable
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
Method Scope
 If a variable is declared inside a method but not within a
block, the variable is visible to any code inside the method
that follows the declaration. Example:
using System;
namespace VariableScope {
class Program
{
int Sum(int num1, int num2) //Method Level
Variable
{
int sum = num1 + num2;
return sum;
}
static void Main(string[] args) {
Program p = new Program();
Console.WriteLine(p.Sum(5,10));
Console.ReadLine();
}
}
}
Method Level Scope
66
Class Scope
 A variable with class or structure scope is available to all
code in this class or structure even if the code appears
before this variable’s declaration.
using System;
namespace VariableScope
{
class Program
{ string str = "Class Level"; // class level
variable
public void display()
{
Console.WriteLine(str);
}
static void Main(string[] args)
{
Program ps = new Program();
ps.display();
Console.ReadLine();
}
}
}
Class Level Scope
67
 An enumeration called “enum” is a discrete list of specific values called enumerators.
 To define a constant set of values.
 C# enumerations are value data type.
 Enumeration contains its own values.
 An enumerated type is declared using “enum” keyword.
 By default, the first member of an enum has the value 0 and the value of each successive enum member is increased by 1.
 By default, an enumeration’s type is int.
 Enum is more readable, more understandable, more maintainable.
Enumeration
68
Enum Variable Declaration
enum enum_name { enumeration list }
Enumeration
69
Example
Enumeration
70
enum Meal : sbyte
{
Breakfast = 1,
Lunch = Breakfast * 10,
Dinner = 30,
Supper
}
enum Days
{
Sun = 3,
Mon,
Tue,
Wed,
Thu, Fri, Sat
}
enum
Days {
Sun,
Mon,
Tue,
Web,
Thu,
Fri,
Sat
};
using System;
// define an enum
enum Weekdays
{ sunday,
monday,
tuesday,
}
class Program
{
static void Main()
{ Weekdays meetingDay = Weekdays.sunday; // assign sunday to meetingDay
Console.WriteLine(meetingDay);
Console.ReadLine();
}
}
71
Enumeration(Eg-1)
using System;
// an enum that contains shapes present in deck of card
enum Cards
{ Diamond = 1,
Spade = 2,
Club = 3,
Heart = 4,
}
class Program
{ static void Main()
{ int myCard = (int)Cards.Spade;
Console.WriteLine("Integer value of string constant is: " + myCard);
Console.ReadLine();
}
}
72
Enumeration(Eg-2)
using System;
// an enum that contains shapes present in deck of card
enum Meal :sbyte
{ Breakfast = 1,
Lunch = Breakfast * 10,
Dinner = 30,
Supper
}
class Program
{ static void Main()
{ int myCard =(int) Meal.Supper;
Console.WriteLine( myCard);
Console.ReadLine();
}
}
73
Enumeration(Eg-3)
 An array is a special data type which can store fixed number of values sequentially in the memory.
 Data type of all values in array must be the same.
 Array in C# is a reference type which is derived from System.Array class.
 Copying an array variable copies the reference only
Value Array Representation
Arrays
74
10 200 30 500 45 33 23 80
0 1 2 3 4 5 6 7
Lower bound Index Upper bound Index
Example: Array Declaration
int[] mark; // to store int value
bool[] B; // to store boolean value
double[ ] D; // to store double value
Example: Array Declaration and Initialization
One-Dimensional Array
75
int[ ] arr = new int[5] ;
(or)
int[ ] arr = {10,20,30,40,50} ;
string[] name = new string[3]{“Su Su”, “Yu Yu”, “Aung Aung”};
long[] salary = {400000L, 5000000L,200000L};
string[] color;
color = new string[3] {“White”, “Orange”, “Red”};
Example: Assigning Array
string[] color = new string[3];
color[0] = “White”;
color[1] = “Orange”;
color[2] = “Red”;
Example: Accessing Array Element
color[1]; // returns “Orange”
One-Dimensional Array
76
Example: Displaying Array Element
string[] name = new string[3]{“Su Su”, “Yu Yu”, “Aung Aung”};
for(int i=0; i< name.Length; i++)
{ Console.WriteLine(name[i]); }
(or)
foreach( string st in name)
{ Console.WriteLine(st)); }
Example: Sorting and Reversing Array Element
long[] salary = {400000, 5000000,200000};
Array.Sort(salary);
Array.Reverse(salary);
One-Dimensional Array
77
Method/ Property Name Description
GetLength (int dimension) Returns the number of elements in the specified dimension
GetLowerBound(int dimension) Returns the lowest index of the specified dimension
GetUpperBound(int dimension) Returns the highest index of the specified dimension
GetValue(int index) Returns the value at the specified index
Length Returns the total number of elements in the array
Array Properties and Methods
78
GetLength( ) and Length
79
using System;
public class Program
{ public static void Main(string[] args)
{
int[,] num = new int[3, 2] { {1,2}, {3,4},{5,6}};
int rowlength = num.GetLength(0);
Console.WriteLine("Array Row Length : " +
rowlength);
int collength = num.GetLength(1);
Console.WriteLine("Array Col Length : " +
collength);
int totallength = num.Length;
Console.WriteLine("Array Total Length : " +
totallength);
Console.ReadLine();
}
}
GetUpperBound( ) and GetLowerBound( )
80
using System;
public class Program
{ public static void Main(string[] args)
{
int [ ] myArray = new int[5] { 6 ,8 ,9 ,0 ,1};
// Get the upper and lower bounds of the array
int upperBound = myArray.GetUpperBound(0); // 4
int lowerBound = myArray.GetLowerBound(0); // 0
Console.WriteLine("Upper Bound= " +
upperBound);
Console.WriteLine("Lower Bound= " +lowerBound);
Console.ReadLine();
} }
Single-Dimensional Array
GetUpperBound( )
81
using System;
public class Program
{
public static void Main(string[] args)
{
int[,] myArray = new int[5, 10];
int upperBoundFirstDimension = myArray.GetUpperBound(0); // for row (0 to 4)
int upperBoundSecondDimension = myArray.GetUpperBound(1); // for col (0 to 9)
Console.WriteLine("Upper Bound= " + upperBoundFirstDimension);
Console.WriteLine("Lower Bound= " + upperBoundSecondDimension);
Console.ReadLine();
}
}
Multi-Dimensional Array
GetLowerBound( )
82
using System;
public class Program
{
public static void Main(string[] args)
{ int[,] myArray = new int[5, 10];
int rowLowerBound = myArray.GetLowerBound(0); // for row (0 to 4)
int colLowerBound = myArray.GetLowerBound(1); // for col (0 to 9)
Console.WriteLine("Row Lower Bound= " + rowLowerBound);
Console.WriteLine("Col Lower Bound= " + colLowerBound);
Console.ReadLine();
}
}
Multi-Dimensional Array
Multi-Dimensional Array
83
 A multi-dimensional array is a two dimensional series like rows and columns.
Example:
int[,] num = new int[ 3 , 3 ]
No of Rows No of Columns
double[,] salary;
int[,] num = new int[3,2] { { 10,11}, { 20,3}, {2, 55}}; //Static two dimensional array
int[,] point= new int[ , ] { { 10,11}, { 20,3} }; //Dynamic two dimensional array
point[1,0];
Multi-Dimensional Array
84
string[ , ] subject = {
{ “C#”, “JAVA”, “C++”},
{ “C”, “VB.NET”, “C#.NET”},
{ “XML”, “HTML”, “SQL”},
};
for (int i = 0; i < subject.GetLength(0); i++)
{
for (int j = 0; j < subject.GetLength(1); j++)
{
Console.Write(subject[i, j] + " ");
}
Console.WriteLine();
}
Jagged Array
85
 A jagged array is an array of an array.
 A jagged array is an array of arrays such that member arrays can be of different sizes.
 It stores arrays instead of any other data type value directly.
 A jagged array is initialized with two square brackets [ ][ ].
 The first bracket specifies the size of an array and the second bracket specifies the dimension of the array which is
going to store as values.
type [ ][ ] array_name = new type[size][dimension of array];
Example
int[ ][ ] A = new int[2] [ ] ; // One Dimensional array
int[][,] B = new int[2] [,]; // Two Dimensional array
Jagged Array
86
1 2 3
4 5
0
1
Example
int[ ][ ] A = new int[2][ ];
A[0] = new int[3]{1, 2, 3};
A[1] = new int[2]{4, 5 };
A
One Dimensional Array
Jagged Array
87
int[][] A= new int[3][]
{
new int[3]{15, 7, 22},
new int[2]{67, 81},
new int[4]{12,91,1,17}
};
Console.WriteLine(A[0][0]);
Console.WriteLine(A[1][1]);
Console.WriteLine(A[2][3]);
Jagged Array
88
1 2
3 4
5 6
3 4
5 6
0 0
0 0
B
1
2
0
int [ ][,] B = new int[3][,];
B[0] = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
B[1] = new int[2, 2] { { 3, 4 }, { 5, 6 } };
B[2] = new int[2, 2];
Two Dimensional Array
89
using System;
public class Program
{
public static void Main(string[] args)
{ string[][] jaggedArray = new string [2][] {
new string[] {"apple","mango"},
new string[] {"orange","banana", "guava"}
};
/* retrieve value from each array element */
for (int i = 0; i < jaggedArray.Length; i++) {
// number of row
for (int j = 0; j < jaggedArray[i].Length; j++) {
//number of col
Console.Write(jaggedArray[i][j]+" ");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
Multi-Dimensional Array
Jagged Array
Different between multi dimensional array and Jagged Array
90
91
University of Computer Studies
University of Computer Studies
Chapter 2
Operators
Contents
 What is Operator?
 Arithmetic Operators
 Comparison Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Special Operators
 Conditional Operator ( ?: )
 Null – Coalescing Operator ( ?? )
 Operator Precedence 92
Operator
 Operators are used to perform operations on variables and values.
 Operators in C# are some special symbols that perform some action on operands.
 There are two types of operators in C# : Unary operators and Binary operators.
 Unary operators act on single operand.
 Binary operators act on two operands (left-hand side and right-hand side operand of an operator). 93
sum = a + b
operators
operands
Operator
 C# includes the following categories of operators:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Equality operators
 Logical operators
 Bitwise operators
 Member access operators
 Type-cast operators
94
Arithmetic Operators
Arithmetic Operators
Table 1
95
Operator Meaning Example Result
++ Increment x++ (or) ++x x = x + 1
-- Decrement x-- (or) -- x x = x-1
+ Addition 5 + 3 8
- Subtraction 6 – 1 5
* Multiplication 4 * 3 12
/ Division 21 / 5 4.2
% Modulus 21 % 5 1
+ Unary plus + x x = +x
- Negation -x x = -x
Comparison Operators
Comparison Operators
Table 2
96
Operator Meaning Example Result
< Less than x < y true if x is less than y
<= Less than or equal to x < = y true if x is less than or equals to y
> Greater than x > y true if x is greater than y
>= Greater than or equal to x >= y true if x is greater than or equals to y
== Equals x == y true if x equals to y
!= Not Equals x != y true if x does not equal to y
Logical Operators
Logical Operators
Table 3
97
Operator Meaning Example Result
! Not (Negation) ! A true if A is false
& AND A & B true if both A and B are true
| OR A | B true if A or B ( or ) both are true
^ Xor (Exclusive Or) A ^ B true if A is true or B is true but both are
no true
&& AND A && B true if both A and B are true
|| OR A || B true if A or B ( or ) both are true
Bitwise Operators
Bitwise Operators
Table 4
98
Operator Meaning
& bitwise logical AND
| bitwise logical OR
^ bitwise logical Xor
~ one’s complement
<< shift left
>> shift right
Assignment Operators
Assignment Operators
Table 5
99
Operator Example
= a = b
+= a += b
-= a-= b
*= a*= b
/= a/=b
%= a%=b
<<= a<<= 3
>>= a>>= 3
&= a &=b
| = a |= b
^= a ^=b
Logical Operators
Special Operators
Table 6
100
Operator Meaning
is relational operator
as Relational operator
typeof type operator
sizeof size operator
new object creator
. (dot) member access operator
checked overflow checking
unchecked Prevention of overflow checking
Conditional Operator ( ?: )
 a decision-making operator “ ?: ”
 Also called conditional operator or ternary operator
 short form of the if else conditions
Syntax:
Example:
int x = 20, y = 10;
string result = ( x > y )? “x is greater than y” : “x is less than y” ;
101
(condition)? statement 1 : statement 2
102
University of Computer Studies
University of Computer Studies
Chapter(3)
Program Control Statements
Contents
103
 Decision Statements
 if statement
 if…..else statement
 if….else if…..else statement
 nested if statement
 switch statement
 Ternary operator ( ?: )
 Looping Statements
 for
 foreach
 while
 do….while
 Jump Statements
 break
 continue
 goto
 return
Decision Statements
104
to determine one or more conditions evaluated
by the program at run-time
a statement or statements to be executed if the
condition is determined to be true
other statements to be executed if the condition
is determined to be false
if Statement
 if the condition becomes true, then the block of statements enclosed within curly braces will get executed
Syntax
Example
Console.WriteLine("Enter your mark");
int mark = int.Parse(Console.ReadLine());
if (mark >= 50)
{ Console.WriteLine("Pass"); }
105
if(condition)
{
// code for execution
}
if…..else Statement
 if the condition becomes true, then the block of statements enclosed within curly braces will get executed
 otherwise, the block of code associated with the else will get executed
Syntax
106
if(condition)
{
// if condition is true
}
else
{
// if the condition becomes false
}
if…..else Statement
Example
Console.WriteLine("Enter your mark");
int mark = int.Parse(Console.ReadLine());
if (mark >= 50)
{ Console.WriteLine("Pass "); }
else
{ Console.WriteLine("Fail"); }
107
if…..else if…..else Statement
 Execute a single block based on one condition from multiple conditional statements
 The conditions are checked one by one in the if statements from the top and will execute that block whose condition is
evaluated to true
Syntax
108
if(first-condition)
{
// when first condition becomes true
}
else if(second-condition)
{
// when second condition becomes true
}
else if(third-condition)
{
// when third condition becomes true
}
else
{ // when all the conditions are false }
if…..else if…..else Statement
Example
Console.WriteLine("Enter your mark");
int mark = int.Parse(Console.ReadLine());
if (mark >= 50 && mark<65)
Console.WriteLine("Pass");
else if (mark >= 65 && mark < 80)
Console.WriteLine("Pass with Credit");
else if (mark >= 80 && mark<=100)
Console.WriteLine("Pass with Distinction");
else if(mark<50 && mark>=0)
Console.WriteLine("Fail");
else
Console.WriteLine("Invalid Mark");
109
Nested if Statement
 if statement will be nested or inside another if or else statement.
 multiple conditions have to be evaluated as true only then the nested block associated with multiple "if
conditions" will be executed.
Syntax
110
if (first-condition)
{
// when first condition becomes true
if (second-condition)
{
if second condition becomes true, code to be executed
}
}
switch Statement
 It acts as an alternative to the "if-else-if" statement
 Each value is called a case.
 The value of the expression is compared with the
values of each case.
 If there is a match, the associated block of code is
executed.
 The switch expression is evaluated once.
 Each case is exited by a break statement that helps the
program flow move out of the switch case blocks.
 A switch statement can have an optional default case,
which must appear at the end of the switch.
111
This keyword specifies some code to run if there is no case
match.
The switch expression is of integer type such as int, char,
byte, or short, or of an enumeration type, or of string type.
Duplicate case values are not allowed
The data type of the variable in the switch and value of a
case must be of the same type
The value of a case must be a constant or a literal.
Variables are not allowed
switch Statement
Syntax
112
switch(expression)
{
case value1: statement1; break;
case value2: statement2; break;
case value3: statement3; break;
.
.
.
default: statmentDefault; break;
}
switch Statement
Example
Console.WriteLine("Enter your grade");
char grade = char.Parse(Console.ReadLine());
switch (grade)
{
case 'A': Console.WriteLine("Excellent"); Console.ReadLine(); break;
case 'B':
case 'C': Console.WriteLine("Well Done"); Console.ReadLine(); break;
case 'D': Console.WriteLine("Pass"); Console.ReadLine(); break;
case 'F': Console.WriteLine("Fail"); Console.ReadLine(); break;
default: Console.WriteLine("Invalid Grade"); Console.ReadLine(); break;
} 113
Ternary operator ( ?: )
 a decision-making operator ?:
 Also called conditional operator or ternary operator
 short form of the if else conditions
Syntax
Example
string result = ( mark >= 50 )? “Pass” : “Fail”;
Console.WriteLine( result);
114
(condition)? statement1 : statement2
Looping Statements
115
to execute a statement or a group of statements
multiple times
for Loop
 For loop is used when we clearly know the number of iteration required by the loop
 to define the exact number of iterations to be performed
 contains initialization and iteration expressions along with the Boolean expression to provide a condition for the loop
Syntax
116
for ( initialization; condition; increment/decrement )
{
//code block for execution
}
for Loop
Example
for( int i=1 , j=10 ; i<=10 && j>=1; i++ , j-- )
{
int sum = i + j;
Console.WriteLine(sum);
Console.ReadLine();
}
117
foreach Loop
 It is used when a program needs to iterate through the contents of a list.
 It can be used for collections like array lists or arrays.
 It is read-only, hence it doesn’t allow you to modify the iteration variable during execution.
Syntax
118
foreach( variable in data collection)
{
statements
}
foreach Loop
Example
string[] student = { "Su Su", "Yu Yu", "Aung Aung" };
foreach (string st in student)
{
Console.WriteLine(st);
Console.ReadLine();
}
119
while Loop
Syntax
120
The while loop loops through a block of code as long as
a specified condition is True
while ( condition)
{
statement
}
while Loop
Example
Console.WriteLine("Enter number");
int num = int.Parse(Console.ReadLine());
while (num >= 0)
{
Console.WriteLine("Number = " + num);
Console.WriteLine("Enter number");
num = int.Parse(Console.ReadLine());
}
121
do while Loop
Syntax
122
 It works similar to a while loop.
 The Boolean expression is evaluated at the end of the loop instead
of the beginning.
do
{
statement
}while ( condition);
do while Loop
Example
Console.WriteLine("Enter number");
int num = int.Parse(Console.ReadLine());
do
{
Console.WriteLine("Number = " + num);
Console.WriteLine("Enter number");
num = int.Parse(Console.ReadLine());
} while (num >= 0);
123
Jump Statements
124
 used to transfer control from one point to another
point in the program due to some specified code
while executing the program
1. break
2. continue
3. goto
4. return
5. throw
five keywords in the Jump Statements:
break Statement
Syntax
break;
125
 used to break loop or switch statement
 immediately stops the innermost loop containing the statement
and passes control to the end of the loop
break Statement
Example
126
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{ if (i == 4)
{ break; }
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
continue Statement
Syntax
continue;
127
 It used to skip over the execution part of the loop on a
certain condition.
 After that, it transfers the control to the beginning of the
loop.
 It skips its following statements and continues with the next
iteration of the loop.
continue Statement
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
if (i == 4)
{
continue;
}
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
128
goto Statement
Syntax
goto label;
129
 known jump statement
 used to transfer control to the labeled statement in the program
 unconditionally jumps to the specified label
 used to transfer control from deeply nested loop or switch case
label
goto Statement
Example
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Enter even number");
int num = int.Parse(Console.ReadLine());
if (num % 2 != 0)
{ goto output; }
Console.WriteLine("Even Number = " + num);
}
output: Console.WriteLine("Input is Odd number");
130
“odd” number
inputs ,so go to
label statement
“even” number
inputs ,so work
“Even Number=”
return Statement
Example
public static int Sum( )
{
int result = 20 + 30;
return result;
}
131
 It is useful to terminate the execution of the method in which it appears
 It returns the control back to the calling method
 Methods return only one value
 If the type of method is void, then the return statement can be excluded
Thank You
132

1. Introduction to C# Programming Langua

  • 1.
    1 University of ComputerStudies University of Computer Studies Introduction to C#
  • 2.
    Contents  Programming Framework Why use Programming Framework  Types of Programming Framework  Microsoft .Net Framework  Types of Application  Integrated Development Environment (IDE)  Overview of C#  Feature of C#  Program Structure  Declaration Space  Namespace  Block  Read( ), ReadLine( ), ReadKey( )  Syntax 2
  • 3.
     A frameworkis a set of tools in programming on which to build well-structured, reliable software and systems.  It is ready to use collection of classes and interfaces used for developing a particular type of application.  It can include support programs, compilers, code libraries, toolsets, and APIs to develop software and create systems.  Open-source frameworks are always being updated and improved. Programming Framework 3
  • 4.
     It makesprogramming easy.  It allows us to compile all necessary resources and codes into application.  It support multiple languages.  It are used to save time and money. Why use Framework 4
  • 5.
     Web Frameworks Front-End Frameworks  Back-End Frameworks  Mobile App Development Frameworks  Content Management Frameworks  Data Science Frameworks Type of Programming Framework 5
  • 6.
     The .Netframework is a software development by Microsoft.  The .Net framework can be used to create both - Form-based and Web-based applications.  Web services can also be developed using the .Net framework.  The first version of the .Net framework was released in the year 2002.  The framework also supports various programming languages such as Visual Basic and C#, etc. Microsoft .Net Framework 6
  • 7.
    Cont’d 7 Common Language Runtime The Common Language Runtime (CLR), the virtual machine component of Microsoft .NET framework, manages the execution of .NET programs. Class Library  The .NET Framework includes a set of standard class libraries.  A class library is a collection of methods and functions that can be used for the core purpose. Languages  The types of applications that can be built in the .Net framework is classified broadly into the following categories.  WinForms  ASP.Net  ADO.Net
  • 8.
    Cont’d 8 C# Code C# Compiler F# Code F# Compiler Visual Basic Code Visual Basic Compiler Common Intermediate Language (CIL) Common Language Runtime(CLR) Machine code 101000001101001 CLR  The Common Language Runtime (CLR)'s just in time (JIT) compilation converts Intermediate Language (MSIL) to native code on demand at application run time. CIL  The Microsoft Intermediate Language (MSIL), also known as the Common Intermediate Language (CIL) is a set of instructions that are platform independent and are generated by the language-specific compiler from the source code.
  • 9.
     Console Application Window Application  Window Store Application  Mobile Application  Web Application  Enterprise Application  Games Types of Application 9
  • 10.
     An IDEis a tool that helps to write program.  Viusal Studio is an IDE provided by Micorsoft to write the code in the language such C#, F#, VisualBasic,etc. Integrated Development Environment (IDE) 10
  • 11.
  • 12.
  • 13.
     C# isa simple & powerful object-oriented programming language developed by Microsoft.  C# can be used to create various types of applications, such as web, windows, console applications or other types of applications using Visual studio.  C# was developed by Anders Hejlsberg and his team during the development of .NET Framework.  The ‘#’ comes from the musical notation meaning C# is higher than C.  The safety of Java  The ease of Visual Basic  The power of C++  It uses the .NET Framework Overview of C# 13
  • 14.
    Cont’d 14  C# compilertranslates C# code into assembly-like language called Intermediate Language (IL).  CLR (Common Language Runtime) is a virtual machine component of the .Net Framework that translates IL into native machine code when run a C# program.  CLR use a just-in-time complier (JIT compiler) to compile pieces of IL code.
  • 15.
     C# iscase sensitive  All statements and expressions 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. Features of C# 15
  • 16.
    using System; using System.Data; namespace<project name> { <modifier > class <class name> { static void Main() { [statements] } } } Program Structure 16
  • 17.
    C# program consistof the following parts:  Namespace declaration  A class  Class methods  Class attributes  A Main method  Statements and Expressions  Comments Cont’d 17 using System; namespace MyFirstProgram { class Testing { static void Main(string[] args) { /* my first program in C# */ Console.WriteLine(“Good Morning, Welcome To C# Class"); Console.ReadLine(); } } }
  • 18.
    Console.Read() accepts thefirst character of the string and returns ASCII Code(Integer Value) of that first character. Console.Readline() accepts the string and returns the string. Console.ReadKey( ) obtains the next character or function key pressed by the user. Read( ), ReadLine( ), ReadKey( ) 18
  • 19.
     Case-sensitive  Whitespace means nothing  Semicolons ( ; ) to terminate statements  Code blocks use curly braces ( { } )  // (for single line) or /* */ (for multi lines)  /// (for automatic XML documentation) Syntax 19
  • 20.
    References  C# 5.0Programmer’s Reference  www.w3schools.com  www.tutuorialTeacher.com  www.javapoint.com  www.tutorialspoint.com 20
  • 21.
    21 University of ComputerStudies University of Computer Studies Chapter (1) Basic Concepts
  • 22.
    Contents  Data Types Default Values  Variable  Naming Variable  Variable Declaration  Constant Variable  Keywords  Literals  Escape Character  Comments 22
  • 23.
    Contents  Data TypeConversion  Implicit Conversion  Explicit Conversion  Scope  Nullable Type  Enumeration  Array  One-Dimensional Array  Multi- Dimensional Array  Jagged Array 23
  • 24.
  • 25.
    Cont’d 25 Reference Data Types ValueData Types C# Data Types Pointer Predefined Types User-defined Types Predefined Types User-defined Types bool byte ubyte char short ushort int uint long ulong decimal float double DateTime enum struct Object string class interfaces delegates
  • 26.
    Cont’d 26 Name Type Size Booleanbool 1 bytes Byte byte 1 bytes Singed byte sbyte 1 bytes Character char 2 bytes Short integer short 2 bytes Unsigned short integer ushort 2 bytes Integer int 4 bytes Unsigned integer uint 4 bytes Long integer long 8 bytes Unsigned long integer ulong 8 bytes
  • 27.
    Cont’d 27 Decimal decimal 16bytes Single-precision floating point number float 4 bytes Double-precision floating point number double 8 bytes String string varies Date and Time DateTime 8 bytes Object object 4 bytes Class class varies Structure struct varies
  • 28.
  • 29.
  • 30.
     Stack isused for static memory allocation.  It is stored in the computer's RAM.  Use the stack if you know exactly how much data you need to allocate before compile time and it is not too big.  It is LIFO data structure.  It is stored Directly.  Variables can’t be resized.  Its access fast. Stack and Heap 30  Heap is used for dynamic memory allocation.  It is stored in the computer's RAM.  Use heap if you don't know exactly how much data you will need at runtime or if you need to allocate a lot of data.  Chunks are allocated to store certain kinds of data objects.  Data can be stored and removed in any order.  It is stored indirectly.  Variables can be resized.  Its access is slow.
  • 31.
    Stack and Heap 31 ValueType Reference Type
  • 32.
     A valuetype is a simple data type such as int or float that represents the data directly.  Fixed length  Store on the stack  Predefined value types : Numeric types, Boolean types and Character types  User-defined value types : struct and enumerations  A new type : nullable type  this type variable can hold an undefined value  any value type variable can be defined as a nullable type Data Types: Value Type 32
  • 33.
    Data Types: ValueType 33 Example: int num = 100; num int x=10; int y = x; x value copied y 10 10 Stack Stack
  • 34.
     Stores thevalue in heap and its reference in stack.  String, all Arrays, Class, Object, Interface, Delegates are reference type.  Variable length Data Types: Reference Type(Eg-1) 34 Stack Heap Hello, Good Morning 0x33 0x33 Address where the value is stored Actual Value string st = “Hello, Good Morning”; st
  • 35.
    Data Types: ReferenceType(Eg-2) 35
  • 36.
    Data Types: ReferenceType 36  User-defined type ( or complex type) Classes, Interface, Delegates and Arrays  Predefined ( or simple ) types Object type and String type Circle c = new Circle( ) Stack Heap c object
  • 37.
     When anassignment between two reference variables occurs, only the reference is copied  The actual value remains in the same memory location (i.e. there are two references to a single value) Data Types: Reference Type 37 Person p1 = new Person( ); p1.name = “Su Su”; Person p2 = p1; Stack Heap 0x332255 0x332255 p1 p2 Su Su 0x332255 Reference copied
  • 38.
    Default Value 38 Type DefaultValue All Integer Types 0 char type ‘x000’ float type 0.0f double type 0.0d decimal type 0.0m bool type false enum type 0 All reference type null
  • 39.
     A variableis a name given to storage area that is used to store a value of various data types.  It is a box in the computer’s memory holding temporary information.  Each variable in C# have a specific type.  A variable is either explicitly assigned a value or automatically assigned a default value. Variable 39
  • 40.
     It shouldbegin a letter (A-Z, a-z), underscore, or @ symbol.  After that it can include letters (A-Z, a-z), numbers (0-9), or underscore.  If the name begins with @, it must include at least one other character.  It cannot contain special characters such as &, %, #, and $.  It cannot be the same as C# keywords such as if, for, and public, etc.  num1 - valid  Num1 - valid  student_Name - valid  class - invalid  student Name - invalid  #studentName - invalid  return - invalid  1num - invalid Naming Variable 40
  • 41.
     int num;// declare num variable with “int” data type  int amount = 30000; // declare int type variable named “amount” with initialization  double[] salary; // declare salary variable with double array type  string[,] student; // declare student variable with two dimensions string array type  const double pi = 3.14 // declare constant variable pi with double type. Its value cannot be changed later. Variable Declaration 41
  • 42.
     A variablewhose value will not change during the lifetime of the program.  A constant variable must be initialized at its declaration.  “const” keyword is used to declare constant variable.  Constant variable is stored on stack.  Constant is used to create a variable which value can not be changed.  Value of constant must be computable at compile time. Constant Variable 42
  • 43.
     A nullvalue indicates that a field does not contain any data.  A value type cannot be assigned a null value.  For example, int i = null will give you a compile time error.  C# introduced nullable types that allow you to assign null to value type variables.  Nullable types can only be used with value types. Nullable Type 43 Example int? i = null; double? num = null; num = 4.5;
  • 44.
    Keywords 44  Keywords arewords that have a predefined meaning in a programming language.  Keywords are reserved words that developers or programmers cannot use as the name of a variable. Value Keywords
  • 45.
     class ,delegate , interface , object , string , void Keywords 45 Modifier Type Keywords Reference Type Keywords
  • 46.
    Keywords 46 Statement Keywords Method ParameterKeywords  params , in, ref, out
  • 47.
    Keywords 47 Operator Keywords Access Keywords base, this  is , new, sizeof, typeof, true, stackalloc Namespace Keywords  extern, namespace, and using
  • 48.
  • 49.
     A literalof integer type is know as the integer literal.  It is used to write values of types int, uint, long, and ulong.  It can be octal, decimal, binary, or hexadecimal constant.  A prefix specifies the base.  No prefix is required for the decimal numbers.  A suffix can also be used with the integer literals like U or u are used for unsigned numbers while l or L are used for long numbers. Example 20 // int 30u // unsigned int 30l // long 0x4b // hexadecimal Literal: Integer Literal 49
  • 50.
    Literal: Literal TypeCharacter 50 Character Data Type U uint L long UL, LU ulong F float D double M decimal
  • 51.
     Real literalsare used to write values of types float, double, and decimal.  one or more digits containing a decimal point (the decimal point can appear before, within, or after the digits),  optionally preceded by a sign (+ or -),  optionally followed by an exponent letter and exponent,  optionally followed by kind type parameter. Example float ff = -12.55f; double dd = 2.5e-5D; decimal mm = 1234e5M; Literal: Real Literal 51
  • 52.
     only twoBoolean literals: true and false Example: bool flag = false; Literal: Boolean Literal 52
  • 53.
     ‘2’ (Single character literals )  “2000019” ( String literals ) Example: char grade=‘A’; string result=“Credit”; Literal: Single Character Literals & String Literals 53
  • 54.
    Escape Character 54 Escape CharacterMeaning a alert b backspace f form feed n new line r carriage return t horizontal tab v vertical tab ’ single quote ” double quote backslash 0 null
  • 55.
  • 56.
    1. Single linecomments int num = 10; // variable declaration 2. Multi-line comments /* The following is a multi-line Comment in C# */ Comments 56
  • 57.
    Type of Conversion 57 DataType Conversion It happens when the value of one data type is assigned to another data type. Boxing UnBoxing
  • 58.
     Compiler convertsautomatically  Smaller data type to larger data type Implicit Conversion 58 From Data Type To Data Type byte short,int,long,float,double short int, long, float,double int long, float, double long float,double float double
  • 59.
    class Program { static voidMain(string[] args) { int a = 10; int b = 20; double c = a + b; Console.WriteLine("The result is"+ c); Console.ReadLine(); } } Output->The result is 30 Implicit Conversion 59 Smaller data type to larger data type
  • 60.
     The developerchange manually.  Larger type to smaller type.  There are two ways to convert a value from one type to another type. (1)Casting Example: long salary = 300000; int empSalary = (int)salary; (2) Parsing Example: double a = 30.0; int c = Convert.ToInt32(a); Explicit Conversion 60
  • 61.
    Explicit Conversion 61 No MethodDescription 1 ToBoolean Convert a type to a Boolean value, where possible 2 ToByte Convert a type to a byte 3 ToChar Convert a type to a single Unicode character, where possible 4 ToDateTime Convert a type (integer or string type) to date-time structures 5 ToDecimal Convert a floating point or integer type to a decimal type 6 ToDouble Convert a type to a double type 7 ToInt16 Convert a type to a 16 bit integer 8 ToInt32 Convert a type to a 32 bit integer
  • 62.
    Explicit Conversion 62 No MethodDescription 9 ToInt64 Convert a type to a 64 bit integer 10 ToSbyte Convert a type to a singed byte type 11 ToSingle Convert a type to a small floating point number 12 ToString Convert a type to a string 13 ToType Convert a type to a specified type 14 ToUInt16 Convert a type to an unsigned int type 15 ToUInt32 Convert a type to an unsigned long type 16 ToUInt64 Convert a type to an unsigned big integer
  • 63.
    Example: int i= 20; object x = i ; Example: object x = 5; int y = (int)x; int z = Convert.ToInt32(x); Boxing and Unboxing 63 Value Type to Reference Type (Boxing) Reference Type to Value Type (Unboxing)
  • 64.
     A variable’sscope determines which other pieces of code can access it.  If a variable is declared inside a method, only code within that method can access the variable. Scope 64 Block Level Scope  Block is a series of statements enclosed in braces.  If a variable is declared within a block of code, the variable has block scope, and only other code within that block can access this variable.
  • 65.
    Block Level Scope 65 usingSystem; namespace VariableScope { class Program { static void Main(string[] args) { for (int i = 0; i <= 3; i++) //Block Level Variable { Console.WriteLine(i); } Console.ReadLine(); } } }
  • 66.
    Method Scope  Ifa variable is declared inside a method but not within a block, the variable is visible to any code inside the method that follows the declaration. Example: using System; namespace VariableScope { class Program { int Sum(int num1, int num2) //Method Level Variable { int sum = num1 + num2; return sum; } static void Main(string[] args) { Program p = new Program(); Console.WriteLine(p.Sum(5,10)); Console.ReadLine(); } } } Method Level Scope 66
  • 67.
    Class Scope  Avariable with class or structure scope is available to all code in this class or structure even if the code appears before this variable’s declaration. using System; namespace VariableScope { class Program { string str = "Class Level"; // class level variable public void display() { Console.WriteLine(str); } static void Main(string[] args) { Program ps = new Program(); ps.display(); Console.ReadLine(); } } } Class Level Scope 67
  • 68.
     An enumerationcalled “enum” is a discrete list of specific values called enumerators.  To define a constant set of values.  C# enumerations are value data type.  Enumeration contains its own values.  An enumerated type is declared using “enum” keyword.  By default, the first member of an enum has the value 0 and the value of each successive enum member is increased by 1.  By default, an enumeration’s type is int.  Enum is more readable, more understandable, more maintainable. Enumeration 68
  • 69.
    Enum Variable Declaration enumenum_name { enumeration list } Enumeration 69
  • 70.
    Example Enumeration 70 enum Meal :sbyte { Breakfast = 1, Lunch = Breakfast * 10, Dinner = 30, Supper } enum Days { Sun = 3, Mon, Tue, Wed, Thu, Fri, Sat } enum Days { Sun, Mon, Tue, Web, Thu, Fri, Sat };
  • 71.
    using System; // definean enum enum Weekdays { sunday, monday, tuesday, } class Program { static void Main() { Weekdays meetingDay = Weekdays.sunday; // assign sunday to meetingDay Console.WriteLine(meetingDay); Console.ReadLine(); } } 71 Enumeration(Eg-1)
  • 72.
    using System; // anenum that contains shapes present in deck of card enum Cards { Diamond = 1, Spade = 2, Club = 3, Heart = 4, } class Program { static void Main() { int myCard = (int)Cards.Spade; Console.WriteLine("Integer value of string constant is: " + myCard); Console.ReadLine(); } } 72 Enumeration(Eg-2)
  • 73.
    using System; // anenum that contains shapes present in deck of card enum Meal :sbyte { Breakfast = 1, Lunch = Breakfast * 10, Dinner = 30, Supper } class Program { static void Main() { int myCard =(int) Meal.Supper; Console.WriteLine( myCard); Console.ReadLine(); } } 73 Enumeration(Eg-3)
  • 74.
     An arrayis a special data type which can store fixed number of values sequentially in the memory.  Data type of all values in array must be the same.  Array in C# is a reference type which is derived from System.Array class.  Copying an array variable copies the reference only Value Array Representation Arrays 74 10 200 30 500 45 33 23 80 0 1 2 3 4 5 6 7 Lower bound Index Upper bound Index
  • 75.
    Example: Array Declaration int[]mark; // to store int value bool[] B; // to store boolean value double[ ] D; // to store double value Example: Array Declaration and Initialization One-Dimensional Array 75 int[ ] arr = new int[5] ; (or) int[ ] arr = {10,20,30,40,50} ;
  • 76.
    string[] name =new string[3]{“Su Su”, “Yu Yu”, “Aung Aung”}; long[] salary = {400000L, 5000000L,200000L}; string[] color; color = new string[3] {“White”, “Orange”, “Red”}; Example: Assigning Array string[] color = new string[3]; color[0] = “White”; color[1] = “Orange”; color[2] = “Red”; Example: Accessing Array Element color[1]; // returns “Orange” One-Dimensional Array 76
  • 77.
    Example: Displaying ArrayElement string[] name = new string[3]{“Su Su”, “Yu Yu”, “Aung Aung”}; for(int i=0; i< name.Length; i++) { Console.WriteLine(name[i]); } (or) foreach( string st in name) { Console.WriteLine(st)); } Example: Sorting and Reversing Array Element long[] salary = {400000, 5000000,200000}; Array.Sort(salary); Array.Reverse(salary); One-Dimensional Array 77
  • 78.
    Method/ Property NameDescription GetLength (int dimension) Returns the number of elements in the specified dimension GetLowerBound(int dimension) Returns the lowest index of the specified dimension GetUpperBound(int dimension) Returns the highest index of the specified dimension GetValue(int index) Returns the value at the specified index Length Returns the total number of elements in the array Array Properties and Methods 78
  • 79.
    GetLength( ) andLength 79 using System; public class Program { public static void Main(string[] args) { int[,] num = new int[3, 2] { {1,2}, {3,4},{5,6}}; int rowlength = num.GetLength(0); Console.WriteLine("Array Row Length : " + rowlength); int collength = num.GetLength(1); Console.WriteLine("Array Col Length : " + collength); int totallength = num.Length; Console.WriteLine("Array Total Length : " + totallength); Console.ReadLine(); } }
  • 80.
    GetUpperBound( ) andGetLowerBound( ) 80 using System; public class Program { public static void Main(string[] args) { int [ ] myArray = new int[5] { 6 ,8 ,9 ,0 ,1}; // Get the upper and lower bounds of the array int upperBound = myArray.GetUpperBound(0); // 4 int lowerBound = myArray.GetLowerBound(0); // 0 Console.WriteLine("Upper Bound= " + upperBound); Console.WriteLine("Lower Bound= " +lowerBound); Console.ReadLine(); } } Single-Dimensional Array
  • 81.
    GetUpperBound( ) 81 using System; publicclass Program { public static void Main(string[] args) { int[,] myArray = new int[5, 10]; int upperBoundFirstDimension = myArray.GetUpperBound(0); // for row (0 to 4) int upperBoundSecondDimension = myArray.GetUpperBound(1); // for col (0 to 9) Console.WriteLine("Upper Bound= " + upperBoundFirstDimension); Console.WriteLine("Lower Bound= " + upperBoundSecondDimension); Console.ReadLine(); } } Multi-Dimensional Array
  • 82.
    GetLowerBound( ) 82 using System; publicclass Program { public static void Main(string[] args) { int[,] myArray = new int[5, 10]; int rowLowerBound = myArray.GetLowerBound(0); // for row (0 to 4) int colLowerBound = myArray.GetLowerBound(1); // for col (0 to 9) Console.WriteLine("Row Lower Bound= " + rowLowerBound); Console.WriteLine("Col Lower Bound= " + colLowerBound); Console.ReadLine(); } } Multi-Dimensional Array
  • 83.
    Multi-Dimensional Array 83  Amulti-dimensional array is a two dimensional series like rows and columns. Example: int[,] num = new int[ 3 , 3 ] No of Rows No of Columns double[,] salary; int[,] num = new int[3,2] { { 10,11}, { 20,3}, {2, 55}}; //Static two dimensional array int[,] point= new int[ , ] { { 10,11}, { 20,3} }; //Dynamic two dimensional array point[1,0];
  • 84.
    Multi-Dimensional Array 84 string[ ,] subject = { { “C#”, “JAVA”, “C++”}, { “C”, “VB.NET”, “C#.NET”}, { “XML”, “HTML”, “SQL”}, }; for (int i = 0; i < subject.GetLength(0); i++) { for (int j = 0; j < subject.GetLength(1); j++) { Console.Write(subject[i, j] + " "); } Console.WriteLine(); }
  • 85.
    Jagged Array 85  Ajagged array is an array of an array.  A jagged array is an array of arrays such that member arrays can be of different sizes.  It stores arrays instead of any other data type value directly.  A jagged array is initialized with two square brackets [ ][ ].  The first bracket specifies the size of an array and the second bracket specifies the dimension of the array which is going to store as values. type [ ][ ] array_name = new type[size][dimension of array]; Example int[ ][ ] A = new int[2] [ ] ; // One Dimensional array int[][,] B = new int[2] [,]; // Two Dimensional array
  • 86.
    Jagged Array 86 1 23 4 5 0 1 Example int[ ][ ] A = new int[2][ ]; A[0] = new int[3]{1, 2, 3}; A[1] = new int[2]{4, 5 }; A One Dimensional Array
  • 87.
    Jagged Array 87 int[][] A=new int[3][] { new int[3]{15, 7, 22}, new int[2]{67, 81}, new int[4]{12,91,1,17} }; Console.WriteLine(A[0][0]); Console.WriteLine(A[1][1]); Console.WriteLine(A[2][3]);
  • 88.
    Jagged Array 88 1 2 34 5 6 3 4 5 6 0 0 0 0 B 1 2 0 int [ ][,] B = new int[3][,]; B[0] = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } }; B[1] = new int[2, 2] { { 3, 4 }, { 5, 6 } }; B[2] = new int[2, 2]; Two Dimensional Array
  • 89.
    89 using System; public classProgram { public static void Main(string[] args) { string[][] jaggedArray = new string [2][] { new string[] {"apple","mango"}, new string[] {"orange","banana", "guava"} }; /* retrieve value from each array element */ for (int i = 0; i < jaggedArray.Length; i++) { // number of row for (int j = 0; j < jaggedArray[i].Length; j++) { //number of col Console.Write(jaggedArray[i][j]+" "); } Console.WriteLine(); } Console.ReadLine(); } } Multi-Dimensional Array Jagged Array
  • 90.
    Different between multidimensional array and Jagged Array 90
  • 91.
    91 University of ComputerStudies University of Computer Studies Chapter 2 Operators
  • 92.
    Contents  What isOperator?  Arithmetic Operators  Comparison Operators  Logical Operators  Bitwise Operators  Assignment Operators  Special Operators  Conditional Operator ( ?: )  Null – Coalescing Operator ( ?? )  Operator Precedence 92
  • 93.
    Operator  Operators areused to perform operations on variables and values.  Operators in C# are some special symbols that perform some action on operands.  There are two types of operators in C# : Unary operators and Binary operators.  Unary operators act on single operand.  Binary operators act on two operands (left-hand side and right-hand side operand of an operator). 93 sum = a + b operators operands
  • 94.
    Operator  C# includesthe following categories of operators:  Arithmetic operators  Assignment operators  Comparison operators  Equality operators  Logical operators  Bitwise operators  Member access operators  Type-cast operators 94
  • 95.
    Arithmetic Operators Arithmetic Operators Table1 95 Operator Meaning Example Result ++ Increment x++ (or) ++x x = x + 1 -- Decrement x-- (or) -- x x = x-1 + Addition 5 + 3 8 - Subtraction 6 – 1 5 * Multiplication 4 * 3 12 / Division 21 / 5 4.2 % Modulus 21 % 5 1 + Unary plus + x x = +x - Negation -x x = -x
  • 96.
    Comparison Operators Comparison Operators Table2 96 Operator Meaning Example Result < Less than x < y true if x is less than y <= Less than or equal to x < = y true if x is less than or equals to y > Greater than x > y true if x is greater than y >= Greater than or equal to x >= y true if x is greater than or equals to y == Equals x == y true if x equals to y != Not Equals x != y true if x does not equal to y
  • 97.
    Logical Operators Logical Operators Table3 97 Operator Meaning Example Result ! Not (Negation) ! A true if A is false & AND A & B true if both A and B are true | OR A | B true if A or B ( or ) both are true ^ Xor (Exclusive Or) A ^ B true if A is true or B is true but both are no true && AND A && B true if both A and B are true || OR A || B true if A or B ( or ) both are true
  • 98.
    Bitwise Operators Bitwise Operators Table4 98 Operator Meaning & bitwise logical AND | bitwise logical OR ^ bitwise logical Xor ~ one’s complement << shift left >> shift right
  • 99.
    Assignment Operators Assignment Operators Table5 99 Operator Example = a = b += a += b -= a-= b *= a*= b /= a/=b %= a%=b <<= a<<= 3 >>= a>>= 3 &= a &=b | = a |= b ^= a ^=b
  • 100.
    Logical Operators Special Operators Table6 100 Operator Meaning is relational operator as Relational operator typeof type operator sizeof size operator new object creator . (dot) member access operator checked overflow checking unchecked Prevention of overflow checking
  • 101.
    Conditional Operator (?: )  a decision-making operator “ ?: ”  Also called conditional operator or ternary operator  short form of the if else conditions Syntax: Example: int x = 20, y = 10; string result = ( x > y )? “x is greater than y” : “x is less than y” ; 101 (condition)? statement 1 : statement 2
  • 102.
    102 University of ComputerStudies University of Computer Studies Chapter(3) Program Control Statements
  • 103.
    Contents 103  Decision Statements if statement  if…..else statement  if….else if…..else statement  nested if statement  switch statement  Ternary operator ( ?: )  Looping Statements  for  foreach  while  do….while  Jump Statements  break  continue  goto  return
  • 104.
    Decision Statements 104 to determineone or more conditions evaluated by the program at run-time a statement or statements to be executed if the condition is determined to be true other statements to be executed if the condition is determined to be false
  • 105.
    if Statement  ifthe condition becomes true, then the block of statements enclosed within curly braces will get executed Syntax Example Console.WriteLine("Enter your mark"); int mark = int.Parse(Console.ReadLine()); if (mark >= 50) { Console.WriteLine("Pass"); } 105 if(condition) { // code for execution }
  • 106.
    if…..else Statement  ifthe condition becomes true, then the block of statements enclosed within curly braces will get executed  otherwise, the block of code associated with the else will get executed Syntax 106 if(condition) { // if condition is true } else { // if the condition becomes false }
  • 107.
    if…..else Statement Example Console.WriteLine("Enter yourmark"); int mark = int.Parse(Console.ReadLine()); if (mark >= 50) { Console.WriteLine("Pass "); } else { Console.WriteLine("Fail"); } 107
  • 108.
    if…..else if…..else Statement Execute a single block based on one condition from multiple conditional statements  The conditions are checked one by one in the if statements from the top and will execute that block whose condition is evaluated to true Syntax 108 if(first-condition) { // when first condition becomes true } else if(second-condition) { // when second condition becomes true } else if(third-condition) { // when third condition becomes true } else { // when all the conditions are false }
  • 109.
    if…..else if…..else Statement Example Console.WriteLine("Enteryour mark"); int mark = int.Parse(Console.ReadLine()); if (mark >= 50 && mark<65) Console.WriteLine("Pass"); else if (mark >= 65 && mark < 80) Console.WriteLine("Pass with Credit"); else if (mark >= 80 && mark<=100) Console.WriteLine("Pass with Distinction"); else if(mark<50 && mark>=0) Console.WriteLine("Fail"); else Console.WriteLine("Invalid Mark"); 109
  • 110.
    Nested if Statement if statement will be nested or inside another if or else statement.  multiple conditions have to be evaluated as true only then the nested block associated with multiple "if conditions" will be executed. Syntax 110 if (first-condition) { // when first condition becomes true if (second-condition) { if second condition becomes true, code to be executed } }
  • 111.
    switch Statement  Itacts as an alternative to the "if-else-if" statement  Each value is called a case.  The value of the expression is compared with the values of each case.  If there is a match, the associated block of code is executed.  The switch expression is evaluated once.  Each case is exited by a break statement that helps the program flow move out of the switch case blocks.  A switch statement can have an optional default case, which must appear at the end of the switch. 111 This keyword specifies some code to run if there is no case match. The switch expression is of integer type such as int, char, byte, or short, or of an enumeration type, or of string type. Duplicate case values are not allowed The data type of the variable in the switch and value of a case must be of the same type The value of a case must be a constant or a literal. Variables are not allowed
  • 112.
    switch Statement Syntax 112 switch(expression) { case value1:statement1; break; case value2: statement2; break; case value3: statement3; break; . . . default: statmentDefault; break; }
  • 113.
    switch Statement Example Console.WriteLine("Enter yourgrade"); char grade = char.Parse(Console.ReadLine()); switch (grade) { case 'A': Console.WriteLine("Excellent"); Console.ReadLine(); break; case 'B': case 'C': Console.WriteLine("Well Done"); Console.ReadLine(); break; case 'D': Console.WriteLine("Pass"); Console.ReadLine(); break; case 'F': Console.WriteLine("Fail"); Console.ReadLine(); break; default: Console.WriteLine("Invalid Grade"); Console.ReadLine(); break; } 113
  • 114.
    Ternary operator (?: )  a decision-making operator ?:  Also called conditional operator or ternary operator  short form of the if else conditions Syntax Example string result = ( mark >= 50 )? “Pass” : “Fail”; Console.WriteLine( result); 114 (condition)? statement1 : statement2
  • 115.
    Looping Statements 115 to executea statement or a group of statements multiple times
  • 116.
    for Loop  Forloop is used when we clearly know the number of iteration required by the loop  to define the exact number of iterations to be performed  contains initialization and iteration expressions along with the Boolean expression to provide a condition for the loop Syntax 116 for ( initialization; condition; increment/decrement ) { //code block for execution }
  • 117.
    for Loop Example for( inti=1 , j=10 ; i<=10 && j>=1; i++ , j-- ) { int sum = i + j; Console.WriteLine(sum); Console.ReadLine(); } 117
  • 118.
    foreach Loop  Itis used when a program needs to iterate through the contents of a list.  It can be used for collections like array lists or arrays.  It is read-only, hence it doesn’t allow you to modify the iteration variable during execution. Syntax 118 foreach( variable in data collection) { statements }
  • 119.
    foreach Loop Example string[] student= { "Su Su", "Yu Yu", "Aung Aung" }; foreach (string st in student) { Console.WriteLine(st); Console.ReadLine(); } 119
  • 120.
    while Loop Syntax 120 The whileloop loops through a block of code as long as a specified condition is True while ( condition) { statement }
  • 121.
    while Loop Example Console.WriteLine("Enter number"); intnum = int.Parse(Console.ReadLine()); while (num >= 0) { Console.WriteLine("Number = " + num); Console.WriteLine("Enter number"); num = int.Parse(Console.ReadLine()); } 121
  • 122.
    do while Loop Syntax 122 It works similar to a while loop.  The Boolean expression is evaluated at the end of the loop instead of the beginning. do { statement }while ( condition);
  • 123.
    do while Loop Example Console.WriteLine("Enternumber"); int num = int.Parse(Console.ReadLine()); do { Console.WriteLine("Number = " + num); Console.WriteLine("Enter number"); num = int.Parse(Console.ReadLine()); } while (num >= 0); 123
  • 124.
    Jump Statements 124  usedto transfer control from one point to another point in the program due to some specified code while executing the program 1. break 2. continue 3. goto 4. return 5. throw five keywords in the Jump Statements:
  • 125.
    break Statement Syntax break; 125  usedto break loop or switch statement  immediately stops the innermost loop containing the statement and passes control to the end of the loop
  • 126.
    break Statement Example 126 using System; namespaceMyApplication { class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) { if (i == 4) { break; } Console.WriteLine(i); } Console.ReadLine(); } } }
  • 127.
    continue Statement Syntax continue; 127  Itused to skip over the execution part of the loop on a certain condition.  After that, it transfers the control to the beginning of the loop.  It skips its following statements and continues with the next iteration of the loop.
  • 128.
    continue Statement using System; namespaceMyApplication { class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) { if (i == 4) { continue; } Console.WriteLine(i); } Console.ReadLine(); } } } 128
  • 129.
    goto Statement Syntax goto label; 129 known jump statement  used to transfer control to the labeled statement in the program  unconditionally jumps to the specified label  used to transfer control from deeply nested loop or switch case label
  • 130.
    goto Statement Example for (inti = 1; i <= 5; i++) { Console.WriteLine("Enter even number"); int num = int.Parse(Console.ReadLine()); if (num % 2 != 0) { goto output; } Console.WriteLine("Even Number = " + num); } output: Console.WriteLine("Input is Odd number"); 130 “odd” number inputs ,so go to label statement “even” number inputs ,so work “Even Number=”
  • 131.
    return Statement Example public staticint Sum( ) { int result = 20 + 30; return result; } 131  It is useful to terminate the execution of the method in which it appears  It returns the control back to the calling method  Methods return only one value  If the type of method is void, then the return statement can be excluded
  • 132.