Unit 1 - DOT - NET - CORE
Unit 1 - DOT - NET - CORE
Introduction to C#
language (MSIL). The function of CLR is to convert managed code (MSIL) into machine native code
(executable code) and then execute the program. It means .Net application is compiled into byte code format
known as MSIL. During execution the CLR (JIT) compiler (Just-In-Time compiler) converts byte code into
processor native code and executes the application. CLR are also provides the following services / function:-
1) Memory management or garbage collection.
2) Loading and Execution of Program.
3) Convert intermediate language code to machine native code.
4) Exception Handling.
5) Class Loader.
6) Interoperability of other language.
7) Security.
❖ Component of CLR –
There are following component of CLR –
1) Class Loader
2) Type Definition
3) COM marshaling
4) Debug manager
5) Exception manager
6) Code Manager
7) Security Engine
8) Thread Support
9) Garbage Collector
10) IL to Native Convertor (JIT)
11) BCL Support
that enables interoperability on the .Net platform Common Language Specification (CLS) is a set of basic
language features that .Net Languages needed to develop Applications and Services , which are compatible with
the .Net Framework. It supports reusability; therefore improve the efficiency of development process. CLS is
subset of CTS.
C# Basics
➢ C# Language –
C# (Pronounced as “C Sharp‟) is a computer Programming Language developed by Microsoft
Corporation, USA. C# is fully object oriented language and it is first Component-Oriented language. It is a
simple, modern, and efficient and type safe language derived from the popular C & C++ language. Although it
belongs to the modern language suitable for developing web based, windows & console application.
Simple Program in C#-
using System;
namespace HelloWorld
{
class Program
{
static void Main(String[] args)
{
Console.WriteLine("Hello World !");
Console.Read();
}
}
}
Output:-
Hello World !
1) The .Net framework has one or more language compliers, such as Visual Basic, C#, Visual C++,
JScript, or one of many third-party compilers such as an Eiffel, Perl, or COBOL compiler.
2) Source code (C# or VB.Net) is compiled into Microsoft Intermediate Language (MSIL) codewith
the help of language specific compiler.
E.g.:- CSC compiler for C# and VBC compiler for VB.Net.
3) "Microsoft Intermediate Language" (MSIL) code is also known as "Intermediate Language"(IL)
Code or "Common Intermediate Language" (CIL) Code.
4) C# compiler translates source code into MSIL/IL/CIL code.
5) MSIL code is stored in file called Assembly. This assembly is created after the successful
compilation of application.
6) Since MSIL code cannot be executed directly, because it's not in a machine-executable format,the
CLR compiles the MSIL using the Just-In-Time (JIT) compiler (or JIT compiler) into native CPU
instructions. The JIT compiling occurs only as methods in the program are called. The compiled
executable code is cached on the machine and is recompiled only if there's some change to the source
code.
7) This native executable code is then processed by machines processor.
Example –
int a;
char c;
User can also declare variable more than one at a time.
Example –
int a,b,c;
char str,ch;
Initializing variable –
In C# programming language variable can be initialized in the declaration statement. Variable initialization
means assigning a value to the variable. The variable should be declared in the program before initialize the value to
variable.
In C# program the variable initialize with the help of assignment operator “ = “.
Syntax –
data_type variable_name = value;
OR
variable_name = value;
Example –
int num;
num=10;
OR
int num=12;
Program-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sample
{
class Program
{
static void Main(string[] args)
{
int num;
Console.Write("Enter Number=");
num = Convert.ToInt32(Console.ReadLine());
Console.Write("Value is :" + num);
Console.ReadLine();
}
}
}
Output -
Enter Number=10
Value is : 10
➢ Numbers -
Number types are divided into two groups:
1) Integer types stores whole numbers, positive or negative (such as 123 or -456),
without decimals. Valid types are int and long. Which type you should use, depends on the
numeric value.
2) Floating point types represents numbers with a fractional part, containing one or more
decimals. Valid types are float and double.
a) Int -
The int data type can store whole numbers from -2147483648 to 2147483647. The int data
type is the preferred data type when we create variables with a numeric value.
Example -
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int myNum = 010101;
Console.WriteLine(myNum);
}
}
}
b) Long
The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the value. Note
that you should end the value with an "L":
Example -
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
long myNum = 15000000000L;
Console.WriteLine(myNum);
}
}
}
Prof. Honrao Bhagyashri Prakash [ 9 ]
2) Floating Point Types
You should use a floating point type whenever you need a number with a decimal,
such as 9.99 or 3.14515.
The float and double data types can store fractional numbers. Note that you should end
the value with an "F" for floats and "D" for doubles:
Example -
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
float myNum = 5.75F;
Console.WriteLine(myNum);
}
}
}
1. Value Type:-
2. Reference Type:
1. Value Type:-
Value Type directly contains actual data on stack. They cannot contain null value.
For example, when we declare an int (integer) variable & assign a value to it, the
variable directly contains that value. And when we assign a value type variable to another, both
variables have make different copies. In other word if we change either of them, the other does not
change. These kinds of data types are called “Value Types”.
Output:-
Num1 is 5. Num2 is 5
Num1 is 5. Num2 is 3
Here, num1 & num2 each contains a copy of its own value.
struct, enums are also value types.
2. Reference Type:-
For reference types, the variable stores a reference to the data rather than the actual data.
The reference is stored on stack, while the actual object is created on managed heap. Reference
type can be null.
When Reference type is assigned to another reference type, one the reference is copied &
not the value. The actual value remains in the same memory location. This means that there are
two references to a single value.
Program:-
using System;
namespace ConsoleApplication8
{
class abc
{
public int value = 0;
}
class Test
{
public static void Main(String[] Args)
{
int val1 = 0;
int val2 = val1;
val2 = 123;
abc x = new abc();
abc x1 = x;
x1.value = 123;
Console.WriteLine("Value : {0} {1}", val1, val2);
Console.WriteLine("Refs : {0} {1}", x.value, x1.value);
Console.Read();
}
}
}
Output:-
Value : 0 123
Refs : 123 123
Prof. Honrao Bhagyashri Prakash [ 13 ]
➢ Difference between value type & reference type:-
➢ Keywords-
Keywords or Reserved words are the words in a language that are used for some internal
process or represent some predefined actions. These words are therefore not allowed to use as
variable names or objects. Doing this will result in a compile-time error.
1) Value Type Keywords: There are 15 keywords in value types which are used to define various
data types.
using System;
class GFG
byte a = 47;
bool b = true;
Console.Read();
}
Output:
2) Reference Type Keywords: There are 6 keywords in reference types which are used to store
references of the data or objects. The keywords in this category are: class, delegate, interface,
object, string, void.
3) Modifiers Keywords: There are 17 keywords in modifiers which are used to modify the
declarations of type member.
public private internal protected abstract
const event extern new override
partial readonly sealed static unsafe
virtual volatile
Prof. Honrao Bhagyashri Prakash [ 15 ]
// C# Program to illustrate the
// modifiers keywords
using System;
class Geeks
{
class Mod
{
// Main Method
static void Main(string[] args) {
}
Output:
Value of n1: 77
4) Statements Keywords: There are total 18 keywords which are used in program instructions.
using System;
class demoContinue
{
public static void Main()
{
Output:
GeeksforGeeks
5) Method Parameters Keywords: There are total 4 keywords which are used to change the
behavior of the parameters that passed to a method. The keyword includes in this category
are: params, in, ref, out.
6) Namespace Keywords: There are total 3 keywords in this category which are used
in namespaces. The keywords are: namespace, using, extern.
7) Operator Keywords: There are total 8 keywords which are used for different purposes like
creating objects, getting a size of object etc. The keywords are: as, is, new, sizeof, typeof, true,
false, stackalloc.
Prof. Honrao Bhagyashri Prakash [ 17 ]
8) Conversion Keywords: There are 3 keywords which are used in type conversions. The
keywords are: explicit, implicit, operator.
9) Access Keywords: There are 2 keywords which are used in accessing and referencing the class
or instance of the class. The keywords are base, this.
10) Literal Keywords: There are 2 keywords which are used as literal or constant. The keywords
are null, default.
Important Points:
• Keywords are not used as an identifier or name of a class, variable, etc.
• If you want to use a keyword as an identifier then you must use @ as a prefix. For
example, @abstract is valid identifier but not abstract because it is a keyword.
a) Boxing –
• The process of converting a Value Type variable (char, int etc.) to a Reference Type variable
(object) is called Boxing.
• Boxing is an implicit conversion process in which object type (super type) is used.
• Value Type variables are always stored in Stack memory, while Reference Type variables are
stored in Heap memory.
Example 1 :
Example 2 :
b) UnBoxing –
• The process of converting a Reference Type variable into a Value Type variable is known as
Unboxing.
• It is an explicit conversion process.
Example 1 :
int num = 23; // value type is int and assigned value 23
Object Obj = num; // Boxing
int i = (int)Obj; // Unboxing
// boxing
object obj = num;
// unboxing
int i = (int)obj;
// Display result
Console.WriteLine("Value of ob object is : " + obj);
Console.WriteLine("Value of i is : " + i);
Console.Read();
}
}
Output:
Value of ob object is : 23
Value of i is : 23
➢ Operators –
An operator is a special symbol that represents an operation. C support a rich set of built-
in operators. Operators are used in program to manipulate data and variables.
There are following types of operators –
1) Arithmetic Operator.
2) Relational Operator / Comparison Operator
3) Logical Operator.
4) Assignment Operator.
Prof. Honrao Bhagyashri Prakash [ 20 ]
5) Conditional Operator.
6) Bitwise Operator
1) Arithmetic Operator-
Arithmetic operator requires two operands to perform operation. The result of these
operands could be either positive or negative. Arithmetic operators are also called as binary operators.
There are following arithmetic operators and their meaning: -
Example –
Write a program to demonstrate the arithmetic operator.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
}
}
}
Output –
Addition Operator: 15
Subtraction Operator: 5
Multiplication Operator: 50
Division Operator: 2
Modulo Operator: 0
2) Relational Operator-
Relational operators are used to change flow of program. These operators are used
in conditional statements, loops. The result of these operators is either true or false, which can also
consider as 1 or 0 respectively.
< Less than It returns true if 1st operand is less than 2nd operand. (e.g. 4<10)
> Greater than It returns true of 1st operand is greater than 2nd operand (e.g. 4>10)
Less than or It returns true if 1st operand is less than or equal to 2nd operand.
<=
equal to (e.g. 4<=10)
Greater than It returns true of 1st operand is greater than or equal to 2nd operand
>=
or equal to (e.g. 4>=10)
!= Not equal to It return true if 1st operand is not equal to 2nd operands.(e.g 8!=10)
Prof. Honrao Bhagyashri Prakash [ 22 ]
Example –
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
bool result;
int x = 5, y = 10;
result = (x == y);
Console.WriteLine("Equal to Operator: " + result);
result = (x > y);
Console.WriteLine("Greater than Operator: " + result);
result = (x < y);
Console.WriteLine("Less than Operator: " + result);
result = (x >= y);
Console.WriteLine("Greater than or Equal to: " + result);
result = (x <= y);
Console.WriteLine("Lesser than or Equal to: " + result);
result = (x != y);
Console.WriteLine("Not Equal to Operator: " + result);
Console.Read();
}
}
}
Output –
Equal to Operator: False
Greater than Operator: False
Less than Operator: True
Greater than or Equal to: False
Lesser than or Equal to: True
Prof. Honrao Bhagyashri Prakash [ 23 ]
Not Equal to Operator: True
3) Logical Operator.-
Logical operators are used to combine two or more conditional expression in single line.
These operators always operate on true or false values and result is also true or false.
The following table shows the logical operators.
Example –
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
bool a = true, b = false, result;
result = a && b;
Console.WriteLine("AND Operator: " + result);
result = a || b;
Console.WriteLine("OR Operator: " + result);
result = !a;
Console.WriteLine("NOT Operator: " + result);
Console.Read();
}
}
} Prof. Honrao Bhagyashri Prakash [ 24 ]
Output-
AND Operator: False
OR Operator: True
4) Assignment Operator.-
Assignment operators are used to assign value to left side variable. There are following
types of assignment operators: -
It is used to assign value from right side variable to left side variable. (e.
= Assignment
g c=a+b)
Addition and It adds the right variable to the left side variable and assigns the result to
+=
Assignment the left side variable. (e. g c+=a is equal to c=c+a)
Subtraction and It subtracts the right variable from the left side variable and assigns the
-=
Assignment result to the left side variable. (e. g c- =a is equal to c=c-a)
Multiply and It multiplies the right operand with left operand and assigns the result to
*=
Assignment the left operand. (e. g c*=a is equal to c=c*a)
Divide and It divides the left operand with the right operand and assign the result to
/=
Assignment the left operand. (e. g c/=a is equal to c=c/a)
Modulus and It takes modules using two operands and assigns the result to the left
%=
Assignment operand. (e. g c%=a is equal to c=c%a)
Example –
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
Prof. Honrao Bhagyashri Prakash [ 25 ]
class Program
{
static void Main(string[] args)
{
int x = 15;
x += 10;
Console.WriteLine("Add Assignment Operator: " + x);
x = 20;
x -= 5;
Console.WriteLine("Subtract Assignment Operator: " + x);
x = 15;
x *= 5;
Console.WriteLine("Multiply Assignment Operator: " + x);
x = 25;
x /= 5;
Console.WriteLine("Division Assignment Operator: " + x);
x = 25;
x %= 5;
Console.WriteLine("Modulo Assignment Operator: " + x);
Console.Read();
}
}
}
Output-
Add Assignment Operator: 25
Subtract Assignment Operator: 15
Multiply Assignment Operator: 75
Division Assignment Operator: 5
Modulo Assignment Operator: 0
5) Conditional Operator-
Conditional operator in C language is a powerful operator which can be used to implement
if - else type of logic. Conditional operator is also called as ternary operator. It use ?: as a conditional
operator.
Syntax: -
Prof. Honrao Bhagyashri Prakash [ 26 ]
Condition?expression1:expression2
The conditional operator work like if-else statement. If condition is true the expression1 is
execute otherwise expression2 is execute.
Example: -
Write a program to implement the conditional operator.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int x = 5, y = 10, result;
result = x > y ? x : y;
Console.WriteLine("Result: " + result);
result = x < y ? x : y;
Console.WriteLine("Result: " + result);
Console.Read();
}
}
}
Output –
Result: 10
Result: 5
6) Bitwise Operator-
Bitwise operators are used for manipulation of data at bit level. These operators are used
for testing the bites or shifting them right or left. Bitwise operators are not applied to float or double data
type, it operates on only integer and character data type.
a) Bitwise AND (&) –
The output of bitwise AND is 1 of the corresponding bits of two operands is 1. If either bit of an
operand is 0, the result of corresponding bit is 0.
Prof. Honrao Bhagyashri Prakash [ 27 ]
Example –
A=12, b=25
Binary value of 12 and 25 is –
12 = 0 0 0 0 1 1 0 0 (In binary)
25 = 0 0 0 1 1 0 0 1 (In binary)
12 & 25 = 0 0 0 0 1 0 0 0
b) Bitwise OR ( | ) –
The output of bitwise OR is 1, if at least one corresponding bit of two operands is 1.
Example –
A=12, b=25
Binary value of 12 and 25 is –
12 = 0 0 0 0 1 1 0 0 (In binary)
25 = 0 0 0 1 1 0 0 1 (In binary)
12 | 25 = 0 0 0 1 1 1 0 1
(In decimal (29))
c) Bitwise XOR( ^ ) –
The result of bitwise XOR operator is 1, if the corresponding bits of two operand are apposite that
is 1 ^ 0 = 1
Example –
A=12, b=25
Binary value of 12 and 25 is –
12 = 0 0 0 0 1 1 0 0 (In binary)
25 = 0 0 0 1 1 0 0 1 (In binary)
12 ^ 25 = 0 0 0 1 0 1 0 1
(In decimal)(21))
d) Bitwise Complement (~) –
Bitwise complement operator is unary operator, it works only one operand. It changes 1 to 0 and 0
to 1.
Example -
a=35
35 = 0 0 1 0 0 0 1 1 (In binary)
c=~a = 1 1 0 1 1 1 0 0
(In decimal) (220))
Prof. Honrao Bhagyashri Prakash [ 28 ]
e) Right Shift Operator( >> ) –
Right Shift operator shifts all bits towards right by certain number of specified bits.
Example –
C=212
212 = 1 1 0 1 0 1 0 0 (In binary)
212>>2 It means right shift by 2
O/P - = 0 0 1 1 0 1 0 1(In binary)
Program -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int x = 5, y = 10, result;
result = x & y;
Console.WriteLine("Bitwise AND: " + result);
result = x | y;
Console.WriteLine("Bitwise OR: " + result);
result = x ^ y;
Console.WriteLine("Bitwise XOR: " + result);
result = ~x;
Prof. Honrao Bhagyashri Prakash [ 29 ]
Console.WriteLine("Bitwise Complement: " + result);
result = x << 2;
Console.WriteLine("Bitwise Left Shift: " + result);
result = x >> 2;
Console.WriteLine("Bitwise Right Shift: " + result);
Console.Read();
}
}
}
Output –
Bitwise AND: 0
Bitwise OR: 15
Bitwise XOR: 15
Bitwise Complement: -6
Bitwise Left Shift: 20
Bitwise Right Shift: 1
C# statements
A) Conditional Statements: -
Conditional statements are used to change the flow of program. Normally these statements
are used to make decision. So it is also called as decision making or selective statement. C# language
provide following statements: -
1) if statement
2) if else statement
3) if else if statement
4) switch statement
1) if statement –
If statement is used to check statements conditionally, in this statement you can check
single condition. The keyword id is follows by an expression enclosed in round bracket.
Syntax –
if(condition)
{
//statements;
}
Prof. Honrao Bhagyashri Prakash [ 30 ]
In if statement the condition is true then statements are executed enclosed within if
statement, if condition is false the statement following if are skipped and execute next statement.
Flowchart –
if it false
Condition
if it true
Statement 1
Statement 2
Example -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int x,re;
Console.Write("Enter Number=");
x = Convert.ToInt32(Console.ReadLine());
if (x % 2 == 0)
{
Console.Write(x+" is Even Number...");
}
Console.Read();
}
}
}
Output –
Enter number: 10
10 is Even Number…
if it false
Condition
if it true Statement 1
Statement 2
Statement 1
Statement 2
Example –
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
Prof. Honrao Bhagyashri Prakash [ 32 ]
{
int x,re;
Console.Write("Enter Number=");
x = Convert.ToInt32(Console.ReadLine());
if (x % 2 == 0)
{
Console.Write(x+" is Even Number...");
}
else
{
Console.Write(x+" is Odd Number...");
}
Console.Read();
}
}
}
Output –
Enter number: 11
11 is Odd Number…
3) if else if statement –
if else if statement is used when more than one condition is to be checked. In this case
expressions are evaluated from top to down. Conditions are checked in each if and else if part.
If the condition is true, the statements inside that block are executed and other statement
blocks are skipped. If first condition is false then focus go to next else if condition. If all if
conditions are false then else block are executed.
Syntax –
if(condition 1)
{
//statements;
}
else if(condition 2)
{
//statements;
}
..
..
else
Prof. Honrao Bhagyashri Prakash [ 33 ]
{
//statements;
}
Flowchart -
if it false
Condition 1
if it false
Condition 2
if it true
Statement if it false
if it true Condition n
Statement
if it true
Statement
Statement
Example –
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int x1,x2,x3;
Console.Write("Enter First Number=");
x1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Second Number=");
x2 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Third Number=");
x3 = Convert.ToInt32(Console.ReadLine());
if (x1>x2&&x1>x3)
{
Console.Write(x1+" is greater Number...");
}
else if (x2 > x1 && x2 > x3)
{ Prof. Honrao Bhagyashri Prakash [ 34 ]
Console.Write(x2 + " is greater Number...");
}
else
{
Console.Write(x3 + " is greater Number...");
}
Console.Read();
}
}
}
Output -
Enter First Number: 20
Enter Second Number: 25
Enter Third Number: 15
25 is greater Number…
No
No
Default
Example –
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int number = 30;
switch (number)
{
case 10: Console.WriteLine("case 10");
break;
case 20: Console.WriteLine("case 20");
break;
case 30: Console.WriteLine("case 30");
break;
default: Console.WriteLine("None matches");
break;
}
Console.Read();
}
Prof. Honrao Bhagyashri Prakash [ 36 ]
}
}
Output –
case 30
1) while loop –
The while loop is called as simple looping structure, a while loop in programming
repeatedly executes a target statement as long as a given condition is true. The while loop is an
entry controlled
loop statement.
Syntax –
while(condition)
{
statement;
}
The while loop execute the statements until it is true, if this condition is false then control
is transferred out of loop.
The body of the loop may have one or more statements.
Flowchart –
Is false
Conditi
on
Is true
Statement
2) do while loop –
While loop and do while loop are similar, but in while loop condition is check first and
then execute statements and in do while loop the statements is execute first and then condition check. In
do while loop the condition is check at the bottom of the loop. The do while loop is an exit controlled
loop statement
Syntax –
do
{
Statements;
}
while(condition);
Prof. Honrao Bhagyashri Prakash [ 38 ]
In do statement, the program evaluates the body of the loop first and condition is evaluated
at the end of the loop. If the condition is true the program continues to evaluate the body of loop once
again, this process is continues as long as condition is true, when condition become false the loop will be
terminated.
Flowchart –
Code
Is true
Conditi
on
Is false
Example –
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int a = 1;
do
{
Console.WriteLine(a);
a++;
}
while (a <= 5);
Console.Read();
}
}
}
Output –
Prof. Honrao Bhagyashri Prakash [ 39 ]
1
2
3
4
5
3) for loop: -
for loop is another entry control loop provide a more brief loop control structure. A for
loop is repetition control structure that allows you to efficiently write a loop that needs to execute
a specific number of times.
Syntax: -
for(initialization;condition;increment/decrement)
{
// statements;
}
Here,
a) initialization: -
We can initialize the variable value, such as i=1 or c=0.
b) Condition: -
The value of the control variable is tested using condition. The condition is true the
body of loop is executed otherwise loop terminates.
c) Increment / decrement: -
It allows you to update any loop control variable.
In for loop first we initialize the variable as 1 or 0 or other integer value then we
can check the condition. If condition is true then execute the loop body and then flow of
control jump back to increment / decrement statement in loop. This process continues till the
value of control become fail.
Initialize
Condition False
True
Statement
Increment / Decrement
Example: -
Write a program to print 1 to 5 numbers using for loop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int a;
for (a = 1; a <= 5; a++)
{
Console.WriteLine(a);
}
Console.Read();
} } }
Output: -
1
2
3
4
5
Prof. Honrao Bhagyashri Prakash [ 41 ]
➢ Difference between while loop and do while loop
C) Jumping Statements –
C# language provides following unconditional control statements that are: -
1) break
2) continue
3) goto
4) return
5) throw
1) break: -
The break statement is used to come out of the loop instantly. Whenever compiler finds a
break statement inside a loop, the control directly comes out of loop and passed to the statement
following the loop.
Prof. Honrao Bhagyashri Prakash [ 42 ]
Syntax: -
break;
Example: -
Write a program to print 1 to 5 numbers using break statement.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int num;
num = 1;
while(num<= 10)
{
Console.WriteLine(num);
if(num == 5)
{
break;
}
num++;
}
Console.Read();
}
}
}
Output: -
1
2
3
Prof. Honrao Bhagyashri Prakash [ 43 ]
4
5
2) continue: -
The continue statement is used to force the next iteration of loop to take place, skipping
any code in between. Continue statement is opposite of the break statement. As the name
suggest they continue statement forces the loop to continue or execute the next iteration.
Syntax: -
continue;
Example: -
Write a program to print 1 to 10 numbers using continue statement.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int num;
for(num=1;num<=10;num++)
{
Console.WriteLine(num);
if(num == 5)
{
continue;
}
}
Console.Read();
}
}
}
Output—
1
2
3
Prof. Honrao Bhagyashri Prakash [ 44 ]
4
5
6
7
8
9
10
3) goto statement: -
A goto statement in c programming provides an unconditional jump from the
‘goto’ to a labeled statement in the same function.
The goto statement allows us to transfer control of the program to the specified
label.
Syntax: -
goto label;
.
.
label:statement;
Flowchart: -
label 1 Statement 1
goto
label 2 Statement 2 lable
3
label 3 Statement 3
Example: -
Write a C program to print sum of first 5 numbers using goto statement.
using System;
using System.Collections.Generic;
using System.Linq;
Prof. Honrao Bhagyashri Prakash [ 45 ]
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int num = 20;
switch (num)
{
case 5:
Console.WriteLine("case 5");
break;
case 10:
Console.WriteLine("case 10");
break;
case 20:
Console.WriteLine("case 20");
goto case 5;
default:
Console.WriteLine("No match found");
break;
}
Console.Read();
}
}
}
Output—
case 20
case 5
4) return –
This statement terminates the execution of the method and returns the control to the
calling method. It returns an optional value. If the type of method is void, then the return
statement can be excluded.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program Prof. Honrao Bhagyashri Prakash [ 46 ]
{
static int Addition(int a)
{
int add = a + a;
return add;
}
static void Main(string[] args)
{
int num = 2;
int re = Addition(num);
Console.WriteLine("The addition is " + re);
Console.Read();
}
}
}
Output –
The addition is 4
5) throw –
This is used to create an object of any valid exception class with the help
of new keyword manually. The valid exception must be derived from the Exception class .
Example -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static string sub = null;
static void displaysubject(string sub1)
{
if (sub1 == null)
throw new NullReferenceException("Exception Message");
}
static void Main(string[] args)
{
try
{
displaysubject(sub);
}
catch (Exception exp)
{ Prof. Honrao Bhagyashri Prakash [ 47 ]
Console.WriteLine(exp.Message);
}
Console.Read();
}
}
}
Output –
Exception Message
1) Implicit Conversion: -
“Implicit conversion means conversion of data types without losing its original meaning.”
Implicit conversion happens automatically when a value is copied to its compatible data type.
Example: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
Example: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
Example 2 –
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sample
{
public class EnumExample
{
enum Level
{
Low,
Medium,
High
}
public static void Main(string []args)
{
Level myVar = Level.Medium;
Console.WriteLine(myVar);
Console.ReadLine();
}
}
}
Output-
Medium
In C# programming language one of the frequently arising problems is to handle similar types
of data.
Example : -
If user wants to store marks of 100 students, this can be done by creating 100 variables
individually but this process is lengthy and impracticable. These type problems can be handled in
C# programming by using array.
➢ Definition of Array: -
“An array is affixed size sequenced collection of elements of the same data type.”
OR
“Array is a fixed size to collect same type of value.”
OR
“Array is collection of similar data elements represented by single name is known as
array.”
➢ Declaration of array: -
Array is a kind of data structure that can store a fixed-size sequential collection of
elements of the same type. It is simply a grouping of same type data. An array is used to store a
collection of data, but it often more useful to think of an array as a collection of variables of same
type.
Every element has common name known as array name. In C# language array can be
declare with the help of data type, array name.
Syntax: -
data_type [ ] array_name;
Where,
a) data_type: - It can be any primary or secondary data type.
b) array_name: - It is name of array as variable.
Example 1: -
int [ ] a;
➢ Initialization of Array: -
Prof. Honrao
Like other variables an array variable can also be initialized Bhagyashri
in following ways: -Prakash [ 52 ]
Syntax 1: -
data_type [ ] array_name={element1,element2,……….elementn};
Example 1: -
int [ ] age={8,19,17,25,30};
An array can referred each value separately by its index number. “The array index
always start with 0 (zero) and end with size-1 and array position starts from 1 (one).
Example: -
int [ ] age={10,20,30,40,45,70};
So the first element of array can be referred as age[0], second is age[1], and n element can
be referred as age[n-1].
Array variables value is stored by its index number, so when we access it then use index
number with variable.
Example: -
int [ ]age={10,20,30,40,45,70};
Example: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; Prof. Honrao Bhagyashri Prakash [ 53 ]
namespace Sample
{
public class EnumExample
{
public static void Main(string []args)
{
int[] num = { 10, 20, 30 };
Console.WriteLine("First Value is :"+num[0]);
Console.WriteLine("Second Value is :" + num[1]);
Console.WriteLine("Third Value is :" + num[2]);
Console.ReadLine();
}
}
}
Output: -
First Value is : 10
Second Value is: 20
Third Value is : 30
namespace Sample
{
public class EnumExample
{
public static void Main(string []args)
{
int[] num=new int[10];
int i;
Prof. Honrao Bhagyashri Prakash [ 54 ]
Console.WriteLine("Enter 5 array elements =");
for (i = 0; i <5; i++)
{
num[i]=Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Elements are=");
for (i = 0; i < 5; i++)
{
Console.WriteLine(num[i]);
}
Console.ReadLine();
}
}
}
Output: -
Enter 5 array elements=
10
12
14
16
20
Elements are=
10
12
14
16
20
C# Array Types-
a) Single Dimensional Array
b) Multidimensional Array
c) Jagged Array
Declaration: -
Syntax: -
data_type [ ] array_name;
Example: -
int [ ]n;
Initialization: -
Following syntax for declaring and initializing a single dimensional arrays with size and
initial
value.
Syntax: -
data_type [ ]array_name = {value1,value2,……..,valuen};
Example: -
int [ ]marks={80,70,75,45,60,65};
Accessing: -
To access the elements of single dimensional array we use array name followed by index
number of element. Here the index value must be enclosed in square braces.
Syntax: -
array_name[index_value];
Example 1: -
Console.WriteLine(marks[2]);
Example 2: -
using System;
using System.Collections.Generic;
Prof. Honrao Bhagyashri Prakash [ 56 ]
using System.Linq;
using System.Text;
namespace Sample
{
public class EnumExample
{
public static void Main(string []args)
{
int[] num=new int[10];
int i,sum1;
sum1 = 0;
Console.WriteLine("Enter 5 array elements =");
for (i = 0; i <5; i++)
{
num[i]=Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Elements are=");
for (i = 0; i < 5; i++)
{
sum1 = sum1 + num[i];
Console.WriteLine(num[i]);
}
Console.Write("Sum of 5 array elements is=" + sum1);
Console.ReadLine();
}
}
}
Output: -
Enter 5 array elements=
1
2
3
4
5
Elements are =
Prof. Honrao Bhagyashri Prakash [ 57 ]
1
2
3
4
5
Sum of 5 array elements is = 15
b) Multidimensional Array –
An array of array is called as multidimensional array. In other words, an array created
with more than one dimension (size) is called as multidimensional array. The multidimensional
array is also known as rectangular arrays in C#.
Array having more than one subscript variable is called as multidimensional array. It
is also called as matrix. To create multidimensional array, we need to use comma inside the square
brackets.
Syntax –
datatype[,] arrayname = new datatype [3,3];//declaration of 2D array
datatype [,,]arrayname = new datatype [3,3,3];//declaration of 3D array
Example 1 –
int[,] arr = new int[3,3];//declaration of 2D array
int[,,] arr = new int[3,3,3];//declaration of 3D array
Example 1 –
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sample
{
public class EnumExample
{
public static void Main(string []args)
{
int[,] arr=new int[3,3];//declaration of 2D array
arr[0,1]=10;//initialization
arr[1,2]=20;
Prof. Honrao Bhagyashri Prakash [ 58 ]
arr[2,0]=30;
//traversal
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
Console.Write(arr[i,j]+" ");
}
Console.WriteLine();//new line at each row
}
Console.ReadLine();
}
}
}
Output –
0 10 0
0 0 20
30 0 0
c) Jagged Array –
Jagged array is a array of arrays such that member arrays can be of different
sizes. In other words, the length of each array index can differ. The elements of Jagged Array
are reference types and initialized to null by default. Jagged Array can also be mixed with
multidimensional arrays. Here, the number of rows will be fixed at the declaration time, but you
can vary the number of columns.
Declaration –
In Jagged arrays, user has to provide the number of rows only. If the user is also
going to provide the number of columns, then this array will be no more Jagged Array.
Syntax:
Example:
Initialization –
Example :
Here, size of elements in jagged array is optional. So, you can write above code as given
below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sample
{
public class EnumExample
{
public static void Main(string []args)
{
int[][] arr = new int[2][];// Declare the array
arr[0] = new int[] { 11, 21, 56, 78 };// Initialize the array
arr[1] = new int[] { 42, 61, 37, 41, 59, 63 };
// Traverse array elements
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < arr[i].Length; j++)
{
System.Console.Write(arr[i][j] + " ");
}
System.Console.WriteLine();
Prof. Honrao Bhagyashri Prakash [ 60 ]
}
Console.ReadLine();
}
}
}
Output –
11 21 56 78
42 61 37 41 59 63
3) Tuples –
A tuple is a data structure that contains a sequence of elements of different data
types. Tuples in C# are used to return multiple data values.
Features of Tuples:
• It allows us to represent multiple data into a single data set.
• It allows us to create, manipulate, and access data set.
• It returns multiple values from a method without using out parameter.
• It can also store duplicate elements.
• It allows us to pass multiple values to a method with the help of single parameters.
The most common data structures like Array, List, etc. are only of a specific type and
can store infinite elements. But Tuples are able to store a limited number of elements i.e 8 and
can be of any type.
In C#, there are mainly 2 ways to create the tuple which are as follows:
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Tuple<string>My_Tuple1 = new Tuple<string>("GeeksforGeeks");
Console.Read();
}
}
}
Syntax:
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// Creating 1-tuple
// Creating 4-tuple
// Using Create Method
var My_Tuple2 = Tuple.Create(12, 30, 40, 50);
// Creating 8-tuple
// Using Create Method
var My_Tuple3 = Tuple.Create(13, "Geeks", 67,
89.90, 'g', 39939, "geek", 10);
Console.Read();
}
}
Prof. Honrao Bhagyashri Prakash [ 63 ]
}