0% found this document useful (0 votes)
22 views64 pages

Unit 1 - DOT - NET - CORE

Uploaded by

thirosul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views64 pages

Unit 1 - DOT - NET - CORE

Uploaded by

thirosul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Unit 1

Introduction to C#

➢ Introduction to .Net Framework –


The .NET is a software framework which is designed and developed by Microsoft. The first version
of the .Net framework was 1.0 which came in the year 2002. It is used to develop window-based applications,
Web-based applications, console based application and Web services. There is a variety of programming
languages available on the .Net platform such as VB.Net and C# and more. The .Net is platform where multiple
technologies can work together. It is used to build applications for Windows, phone, web, etc.

Fig - .Net Framework

➢ Component of .Net Framework –


There are main four components of .net framework as bellow:-
1) Common Language Runtime (CLR)
2) Framework Class Library (FCL)
3) Common Language Specification (CLS)
4) Common Type System (CTS)

Prof. Honrao Bhagyashri Prakash [ 1 ]


1) Common Language Runtime (CLR) -
Common Language Runtime is an execution engine of .Net framework. It is heart of .Net
framework and it is interface between application and operating system. CLR is system that manages the
loading and execution of our program. When we compile c# program, the output of compiler is not executable
code, instead it is a file that contain special type of pseudo code instruction called Microsoft Intermediate

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

Prof. Honrao Bhagyashri Prakash [ 2 ]


2) Framework Class Library (FCL) –
The .Net framework has provided large class library for developing windows, web and
console application in .net. The FCL is a collection of large amount of classes and data types. This is also called
as Base Class Library and it is common for all types of applications. It is just like the header files in C/C++ and
packages in the java. It is common for all types of applications in .Net, i.e. the way you access the Library Classes
and Methods in VB.NET will be the same in C#, and it is common for all other languages in .Net. In short,
developers just need to import the Base Class Library in their language code and use its predefined methods and
properties to implement common and complex functions like reading and writing to file, graphic rendering,
database interaction, and XML document manipulation. Classes have organized in a logical hierarchy called
„namespace‟. “Namespace is a way to group a collection classes and interface together”. This class library is
common to all languages in .NET.
E.g.: System is highest level namespace also called root namespace. All framework classes are inherited from
root class called Object. This object class defined in system namespace.
E.g. of namespace is
System.Web System.Text System.Collection.

3) Common Language Specification (CLS) -


An important goal of .Net framework is to support multiple languages, but all language is not
created equals. So it is important to agree upon a common subset, that all language will support. CLS defines a
set of rules for all compilers that plan to generate managed code for .Net application. CLS defines a set of rules

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.

4) Common Type System (CTS) -


The .NET Framework supports many programming languages such as C#, VB.NET, J#, F#, etc.
Every programming language has its own data type. One programming language data type cannot be
understood by other programming languages. But, there can be situations where we need to communicate
between two different programming languages. CTS describe set of data types that can be used in different .Net
languages in common. Common Type System (CTS) describes the data types that can be used by managed
code. For example, we need to write code in the VB.NET language and that code may be called from C#

Prof. Honrao Bhagyashri Prakash [ 3 ]


language. In order to ensure smooth communication between these languages, the most important thing is that
they should have a Common Type System (CTS) which ensures that data types defined in two different
languages get compiled to a common data type.
CLR in .NET Framework will execute all programming language’s data types. This is possible
because CLR has its own data types which are common to all programming languages. At the time of
compilation, all language-specific data types are converted into CLR’s data type. This data type system of CLR
is common to all .NET Supported Programming languages and this is known as the Common Type System
(CTS) in .NET Framework.
Eg. When we declare an int type data type in C# and VB.Net then they are converted to int32. In other words,
now both will have a common data type that provides flexible communication between these two languages.

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 !

Prof. Honrao Bhagyashri Prakash [ 4 ]


➢ Compilation of the program –

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.

Prof. Honrao Bhagyashri Prakash [ 5 ]


➢ Introduction to Variable -
A variable is a name of memory location. It is used to store data. Its value can be changed
and it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
A variable is a data name that may be used to store a data value. Variables are terms or entities that
can be changed during program execution.
A variable name can be chosen by the programmer in a meaningful way. Normally,
variables are the locations in the computer’s memory to store data.

Declaration (Creating) of Variable –


Every variable in the program must be declared at the top of the program before variable can use in the
program. To declare variable use following
Syntax –
data_type variable_name;
Where,
a) Data_type – it can be any primary data type that is int, float etc.
b) Variable_name – it is any combination of characters as variable name.

Example –
int a;
char c;
User can also declare variable more than one at a time.

Example –
int a,b,c;
char str,ch;

Rules to declare variable –

Following are some rules to declare variables –

1) Every variable name should start with alphabet or underscore ( _ )

2) No space allowed in the variable name.

3) No special symbols are allowed in variable name except underscore.

4) Keywords are not used as variable name.

Prof. Honrao Bhagyashri Prakash [ 6 ]


5) Variables are case sensitive means upper case and lower case consider different.

6) Characters limit is 255.

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

Prof. Honrao Bhagyashri Prakash [ 7 ]


➢ Introduction to Data Types –
A data type specifies the type of data, that a variable can store value. Data types are
used to define a variable before to use in a program.
It is important to use the correct data type for the corresponding variable; to avoid
errors, to save time and memory, but it will also make your code more maintainable and readable.
The most common data types are:

Data Type Size Description

Stores whole numbers from -2,147,483,648 to


int 4 bytes
2,147,483,647
Stores whole numbers from - 223,372,036,854,775,808
long 8 bytes
to 9,223,372,036,854,775,807
Stores fractional numbers. Sufficient for storing 6 to 7
float 4 bytes
decimal digits
Stores fractional numbers. Sufficient for storing 15
Double 8 bytes
decimal digits
bool 1 bit Stores true or false values
Stores a single character/letter, surrounded by single
char 2 bytes
quotes
Stores a sequence of characters, surrounded by double
string 2 bytes per character
quotes

➢ 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.

Prof. Honrao Bhagyashri Prakash [ 8 ]


1) Integer Types

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);
}
}
}

➢ Characters data type


The char data type is used to store a single character. The character must be surrounded
by single quotes, like 'A' or 'c':
Example -
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
char myGrade = 'B';
Console.WriteLine(myGrade);
}
}
}

Prof. Honrao Bhagyashri Prakash [ 10 ]


➢ Strings data type
The string data type is used to store a sequence of characters (text). String values must
be surrounded by double quotes:
Example -
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string greeting = "Hello World";
Console.WriteLine(greeting);
}
}
}

➢ Value Type & Reference Type:-

CTS define types into 2 categories:-

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”.

The following example makes this clear:-


using System;
namespace ConsoleApplication8
{
class Program
{
static void Main(String[] args)
Prof. Honrao Bhagyashri Prakash [ 11 ]
{
/*Line 1*/ int num1, num2;
/* Line 2*/ num1 = 5;
/* Line 3*/ num2 = num1;
/* Line 4*/ Console.WriteLine("Num1 is {0}. Num2 is {1}", num1, num2);
/* Line 5*/ num2 = 3;
/* Line 6*/ Console.WriteLine("Num1 is {0}. Num2 is {1}", num1, num2);
/* Line 7*/ Console.Read();
}
}
}

Output:-
Num1 is 5. Num2 is 5
Num1 is 5. Num2 is 3

After Line 1 After Line 2 After Line 3 After Line 5


Stack Stack Stack Stack

num2 num2 num2 num2


0 0 5 3
num1 num1 num1 num1
0 5 5 5

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.

Reference types defined in CTS are:-

Object, String, Classes, Interfaces, Array, and Delegates.


Example:-

int weight = 70; weight 70


Prof. Honrao Bhagyashri Prakash [ 12 ]
String title = “.NET”; title .NET

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:-

Parameter Value Type Reference Type


Variable holds Actual Value Memory Location
Default Value 0 Null
Allocated On Stack, Member Heap
Null ability Always has value May be null
Assignment Copying Actual Data Copying reference.

➢ 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.

There are total 78 keywords in C# as follows:

abstract char do fixed int null public short try

as checked double float interface object readonly static typeof


base
class else for internal operator ref string unit
bool
const enum foreach is out return struct ulong

break continue event goto look override sbyte switch unchecked

byte decimal explicit if long params sealed this unsafe

case default false implicit namespace private sizeof throw ushort

catch delegate finally in new protected stackalloc true using


using
virtual void volatile while
static

Keywords in C# is mainly divided into 10 categories as follows:

1) Value Type Keywords: There are 15 keywords in value types which are used to define various
data types.

Prof. Honrao Bhagyashri Prakash [ 14 ]


bool byte char decimal
double enum float int
long sbyte short struct
unit ulong ushort

// C# Program to illustrate the

// value type keywords

using System;

class GFG

static public void Main (String [] args)

byte a = 47;

Console.WriteLine("The value of a is: "+a);

bool b = true;

Console.WriteLine("The value of b is: "+b);

Console.Read();
}

Output:

The value of a is: 47

The value of b is: True

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
{

// using public modifier


// keyword
public int n1;

// Main Method
static void Main(string[] args) {

Mod obj1 = new Mod();

// access to public members


obj1.n1 = 77;

Console.WriteLine("Value of n1: {0}", obj1.n1);


Console.Read();
}

}
Output:

Value of n1: 77

4) Statements Keywords: There are total 18 keywords which are used in program instructions.

if else switch do for


foreach in while break continue
goto return throw try catch
finally checked unchecked

Prof. Honrao Bhagyashri Prakash [ 16 ]


// C# program to illustrate the statement keywords

using System;
class demoContinue
{
public static void Main()
{

// using for as statement keyword


// GeeksforGeeks is printed only 2 times
// because of continue statement
for(int i = 1; i < 3; i++)
{

// here if and continue are keywords


if(i == 2)
continue;
Console.WriteLine("GeeksforGeeks");
Console.Read();
}
}
}

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.

➢ Boxing and Unboxing


Boxing and unboxing are important concepts in C#. The C# Type System contains three data
types: Value Types (int, char, etc), Reference Types (object) and Pointer Types. Basically, Boxing
converts a Value Type variable into a Reference Type variable, and Unboxing achieves the vice-
versa.

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 :

int num = 23; // 23 will assigned to num

Object Obj = num; // Boxing

Example 2 :

Prof. Honrao Bhagyashri Prakash [ 18 ]


// C# implementation to demonstrate the Boxing
using System;
class GFG
{
// Main Method
static public void Main(String[] args)
{
// assigned int value 2020 to num
int num = 2020;
// boxing
object obj = num;

// value of num to be change


num = 100;

Console.WriteLine("Value - type value of num is : "+ num);


Console.WriteLine("Object - type value of obj is : "+obj);
Console.Read();
}
}
Output:

Value - type value of num is : 100

Object - type value of obj is : 2020

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

Prof. Honrao Bhagyashri Prakash [ 19 ]


Example 2:
// C# implementation to demonstrate the Unboxing
using System;
class GFG {
// Main Method
static public void Main()
{
// assigned int value
// 23 to num
int num = 23;

// 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: -

Operator Meaning Description

+ Addition It returns addition of two operands/variables (e.g. c=a+b)

Subtract second operand from first operand and return


- Subtraction
difference. (e.g. c=a-b)

* Multiplication It returns multiplication of two operands (e.g c=a*b)

/ Division It divide number by enumerator and return quotient (e.g c=a/b)

Divide number by enumerator and return reminder after


% Modulation
integer division. (e.g. c=a%b)

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
{

static void Main(string[] args)


{
int result;
int x = 10, y = 5;
result = (x + y);
Console.WriteLine("Addition Operator: " + result);
Prof. Honrao Bhagyashri Prakash [ 21 ]
result = (x - y);
Console.WriteLine("Subtraction Operator: " + result);
result = (x * y);
Console.WriteLine("Multiplication Operator: " + result);
result = (x / y);
Console.WriteLine("Division Operator: " + result);
result = (x % y);
Console.WriteLine("Modulo Operator: " + result);
Console.Read();

}
}
}
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.

Operator Meaning Description

< 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)

== Equal to It return true if both operands are equal (e.g 10=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.

Operator Meaning Description

The result of compound expression is true when all expressions


&& Logical AND
are true.

The result of compound expression is true if one of the


|| Logical OR
expressions is true.

The result of compound statement is true of operator is false.


! Logical NOT
Means convert false result into true and true result into false.

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

NOT Operator: False

4) Assignment Operator.-
Assignment operators are used to assign value to left side variable. There are following
types of assignment operators: -

Operator Meaning Description

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)

f) Left Shift Operator ( << ) –


Left shift operator shifts all bits towards left by certain number of specified bits.
Example-
C=212
212 = 1 1 0 1 0 1 0 0 (In binary)
212<<1 it means left shift by 1
O/P - = 1 0 1 0 1 0 0 0 (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…

Prof. Honrao Bhagyashri Prakash [ 31 ]


2) if else statement –
In if statement given condition is true then the statement block is executed otherwise it
does not execute, so if else statement is used.
If else statement is a two way branching statement, it consists of two blocks of statements.
In if else statement condition is true then first statement block is execute, if condition is false then second
block is execute.
Syntax –
if(condition)
{
//statements;
}
else
{
//statements;
}
Flowchart –

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…

4) switch case statement –


If programmer has to choose one block of statement among many alternative, nested if else
can be used, but this make programming login complex. This type of problem can be handled in C
language programming using switch statement.
Switch statements are used when there is a situation to choose single particular statement
among much statement. It is also called as decision making statement.
Syntax –
switch(expression)
{
case constant1:
statement;
break;
case constant2:
statement;
break;
.
default:
statement;
}

Prof. Honrao Bhagyashri Prakash [ 35 ]


In switch statement value of expression is matched against one of the constant then
statement belonging to that case is executed and statement is break. When no match found then
default case is executed.
Yes
Expression Statement
Flowchart -
No

Cas Yes Statement


e1

No

Cas Yes Statement


e1

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

B) Looping / Iterative Statements –


Looping statement is also called as iterative statement. In iterative statement, a sequence of
statements or instructions that is continually repeated until a certain condition is reached.
A loop statement allows us to execute a statement or group of statements multiple times.
C# programming language provide the following types of loops that is –
1) while loop
2) do while loop
3) for loop

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

Prof. Honrao Bhagyashri Prakash [ 37 ]


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;
while (a <= 5)
{
Console.WriteLine(a);
a++;
}
Console.Read();
}
}
}
Output –
1
2
3
4
5

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.

Example: - a++, a--, etc.

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.

Prof. Honrao Bhagyashri Prakash [ 40 ]


Flowchart: -

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

Sr. No while loop do while loop


Condition is checked first then Statement(s) is executed at least once,
1
statement(s) is executed. thereafter condition is checked.
It might occur statement(s) is executed
2 At least once the statement(s) is executed.
zero times, If condition is false.
No semicolon at the end of while. Semicolon at the end of while.
3
while(condition) while(condition);
If there is a single statement, brackets are
4 Brackets are always required.
not required.
Variable in condition is initialized before Variable may be initialized before or within
5
the execution of loop. the loop.
6 while loop is entry controlled loop. do - while loop is exit controlled loop.
Syntax:
Syntax:
do
while(condition)
{
7 {
statement(s);
statement(s);
}
}
while(condition);

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

➢ Type casting or type conversion or casting of data types: -


Casting of data type means to convert variable from one data type to another data type.
There are two types of type casting that are: -
1) Implicit conversion
2) Explicit conversion

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
{

static void Main(string[] args)


{
short a = 10;
int b;
b = a;
Console.Write("Vaue is :" + b);
Console.Read();
}
}
}
Output—
Value is=10 Prof. Honrao Bhagyashri Prakash [ 48 ]
2) Explicit Conversion: -
Explicit conversion is also called as type casting. The explicit conversion performed by
the programmer by posing the data type of the expression of specific type is knows as explicit
conversion. In explicit conversion, the conversion make forcefully. It requires a type casting
operator.
Syntax: -
(datatype)expression

Example: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{

static void Main(string[] args)


{
double myDouble = 9.78;
int myInt = (int)myDouble; // Manual casting: double to int
Console.WriteLine(myDouble);
Console.WriteLine(myInt);
Console.Read();
}
}
}
Output—
9.78
9

➢ Complex data types –


A complex data type is a transformation data type that represents multiple data values in a
single column position. The data values are called elements.
The following are the complex data types –
1) Enums
2) Arrays
3) Tuples
Prof. Honrao Bhagyashri Prakash [ 49 ]
1) Enums –
Enum in C# is also known as enumeration. It is used to store a set of named constants
such as season, days, month, size etc. The enum constants are also known as enumerators. Enum
in C# can be declared within or outside class and structs.
Enum constants has default values which starts from 0 and incremented to one by one. But we can
change the default value.
Note –
• enum has fixed set of constants
• enum improves type safety
• enum can be traversed
Syntax –
enum Enum_variable
{
string_1...;
string_2...;
.
.
}
Example 1–
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sample
{
public class EnumExample
{
public enum Season { Winter, Spring=10, Summer, Fall }
public static void Main(string [] args)
{
int x = (int)Season.Winter;
int y = (int)Season.Spring;
Console.WriteLine("WINTER = {0}", x);
Console.WriteLine("SPRING = {0}", y);
Console.ReadLine();
Prof. Honrao Bhagyashri Prakash [ 50 ]
}
}
}
Output –
WINTER = 0
SPRING = 10

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

Prof. Honrao Bhagyashri Prakash [ 51 ]


2) Arrays –

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].

➢ Accessing individual array element: -

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};

The value is assign to variable with its index number.


age[0]=10;
age[1]=20;
age[2]=30;
age[3]=40;
age[4]=45;
age[5]=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

➢ To manipulate array elements using loop: -


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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

Prof. Honrao Bhagyashri Prakash [ 55 ]


a) Single Dimensional Array –
In C# programming language, single dimensional arrays are used to store list of values of
same data type. In this type, data is stored in linear form. Single dimensional array is also called as
one-dimensional arrays or linear arrays or simply 1-D 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]);

The output will display 75 value from above values.

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:

data_type[][] name_of_array = new data_type[rows][]

Example:

int[][] jagged_arr = new int[4][]


Prof. Honrao Bhagyashri Prakash [ 59 ]
In the above example, a single-dimensional array is declared that has 4 elements(rows),
each of which is a 1-D array of integers.

Initialization –

Example :

arr[0] = new int[4] { 11, 21, 56, 78 };

arr[1] = new int[6] { 42, 61, 37, 41, 59, 63 };

Here, size of elements in jagged array is optional. So, you can write above code as given
below:

arr[0] = new int[] { 11, 21, 56, 78 };

arr[1] = new int[] { 42, 61, 37, 41, 59, 63 };

Program for Jagged Array in C#-

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:

1) Using Constructor of Tuple Class


2) Using Create Method

1) Using Constructor of Tuple Class:-


You can create a tuple by using the constructor which is provided by Tuple<T>
class. Where you can store elements starting from one to eight with their type. But you are
not allowed to store elements greater than eight in a tuple. If you try to do so then the
compiler will throw an error.

Prof. Honrao Bhagyashri Prakash [ 61 ]


Syntax:
// Constructor for single elements
Tuple <T1>(T1)

// Constructor for two elements


Tuple <T1, T2>(T1, T2)
.
.
.
// Constructor for eight elements
Tuple <T1, T2, T3, T4, T5, T6, T7, TRest>(T1, T2, T3, T4, T5, T6, T7, TRest)

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");

// Tuple with three elements


Tuple<string, string, int>My_Tuple2 = new Tuple<string, string,
int>("Romil", "Python", 29);

// Tuple with eight elements


Tuple<int, int, int, int, int, int, int, Tuple<int>>My_Tuple3 = new Tuple<int,
int, int, int, int, int, int, Tuple<int>>(1,2,3,4,5,6,7, new Tuple<int>(8));

Console.Read();
}
}
}

2) Using Create Method:-


When we use the tuple constructor to create a tuple we need to provide the type of each
element stored in the tuple which makes your code cumbersome. So, Bhagyashri
Prof. Honrao C# provides Prakash
another [ 62 ]
class that is Tuple class which contains the static methods for creating tuple object without
providing the type of each element.

Syntax:

// Method for 1-tuple


Create(T1)

// Method for 2-tuple


Create(T1, T2)
.
.
.
// Method for 8-tuple
Create(T1, T2, T3, T4, T5, T6, T7, T8)

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

// Using Create Method


var My_Tuple1 = Tuple.Create("GeeksforGeeks");

// 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 ]
}

Prof. Honrao Bhagyashri Prakash [ 64 ]

You might also like