Uploaded by Nivedita Sharma

C# Unit I Notes

advertisement
Unit – I
.NET framework
The .NET framework is a collection of all the tools and utilities required to execute the .NET
managed applications on a particular platform. The MS.NET framework includes the standard
compilers (C#, VB.NET, J#, C++.NET, Jscript.NET), various utilities like runtime environment
(CLR), garbage collector, security manager, thread manager, assembly loader, just in time
compilers, and the standard framework or base class libraries. The .NET Framework is an
environment for building, deploying, and running Web Services, Enterprise applications, and
other mid and small size applications.
The .NET Framework, which consists of the Common Language Runtime (CLR) and the .NET
Framework class library. The CLR provides a standard foundation for building applications,
while the .NET Framework class library offers a large set of standard classes and other types that
can be used by any .NET Framework application written in any language.
Visual Studio, an integrated development environment (IDE) for creating Windows applications.
While this tool can be used to build software that runs directly on Windows, its main focus is
helping developers create .NET Framework applications. Visual Studio supports several
programming languages for creating these applications, including C#, Visual Basic (VB), and
C++.
Main Components of .NET Framework
Common Language Runtime (CLR)
The most important part of the .NET Framework is the .Net Common Language Runtime (CLR)
also called .Net Runtime in short. The .NET Framework provides a runtime environment called
the Common Language Runtime or CLR (similar to the Java Virtual Machine or JVM in Java),
which handles the execution of code and provides useful services for the implementation of the
program. It is a framework
layer that resides above the Operating System and handles/manages the execution of the .NET
applications.
Our .Net programs don’t directly communicate with the Operating System but through CLR.
CLR takes care of code management at program execution and provides various beneficial
services such as:
a) Memory management
b) Thread management
c) Security management
d) Code verification
e) Compilation and other system services
MSIL (Microsoft Intermediate Language) Code
When we compile our .Net Program using any .Net compliant language like (C#, VB.NET,
C++.NET) it does not get converted into the executable binary code but to an intermediate code,
called MSIL or IL in short, understandable by CLR. MSIL is an OS and H/w independent code.
When the program needs to be executed, this MSIL or intermediate code is converted to binary
executable code, called native code. The presence of IL makes it possible the Cross Language
Relationship as all the .Net compliant languages produce the similar standard IL code.
Just In Time Compilers (JITers)
When our IL compiled code needs to be executed, CLR invokes JIT compilers which compile
the IL code to native executable code (.exe or .dll) for the specific machine and OS. JITers in
many ways are different from traditional compilers as they, as their name suggests, compile the
IL to native code only when desired e.g., when a function is called, IL of function’s body is
converted to native code; just in time of need.
Framework Class Library (FCL)
.NET Framework provides huge set of Framework (or Base) Class Library (FCL) for common,
usual tasks. FCL contains thousands of classes to provide the access to Windows API and
common functions like String Manipulation, Common Data Structures, IO, Streams, Threads,
Security, Network Programming, Windows Programming, Web Programming, Data Access, etc.
It is simply the largest standard library ever shipped with any development environment or
programming language. The best part of this library is they follow extremely efficient OO design
(design patterns) making their access and use very simple and predictable. You can use the
classes in FCL in your program just as you use any other class and can even apply inheritance
and polymorphism on these. The .NET Framework class library is made up of namespaces,
which are contained within assemblies. Namespaces are used to create logical groups of related
classes and interfaces that can be used by any language that targets the .NET Framework. An
assembly contains all the information about the implementation of classes, structures, and
interfaces. It is a single deployable unit that stores all the information about itself. This
information is known as metadata and includes name and version number of the assembly,
security information, dependency information, and a list of the files that constitute the assembly.
Common Language Specification (CLS)
Microsoft has released a small set of specification that each language should meet to qualify as a
.NET Compliant Language. As IL is a very rich language, it is not necessary for a language to
implement all the IL functionality, rather it meets the small subset of it, CLS, to qualify as a
.NET compliant language, which is the reason why so many languages (procedural and OO) are
now running under .Net umbrella. CLS basically addresses to language design issues and lays
certain standards like there should be no global function declaration, no pointers, no multiple
inheritance and things like that. The important point to note here is that if you keep your code
within CLS boundary, your code is guaranteed to be usable in any other .Net language.
Common Type System (CTS)
.NET also defines a Common Type System (CTS). Like CLS, CTS is also a set of standards.
CTS define the basic data types that IL understands. Each .NET compliant language should map
its data types to these standard data types. This makes it possible for the 2 languages to
communicate with each other by passing/receiving parameters to/from each other. For example,
CTS defines a type Int32, an integral data type of 32 bits (4 bytes) which is mapped by C#
through int and VB.Net through its Integer data type.
Microsoft .NET Assemblies
A .NET assembly is the main building block of the .NET Framework. It is a small unit of code
that contains a logical compiled code in the Common Language infrastructure (CLI), which is
used for deployment, security and versioning. It defines in two parts (process) DLL and library
(exe) assemblies. When the .NET program is compiled, it generates a metadata with Microsoft
Intermediate Language, which is stored in a file called Assembly.
Garbage Collector (GC)
When a dot net application runs, lots of objects are created. At a given point in time, it is possible
that some of those objects are not used by the application. Garbage Collector in .NET
Framework is nothing but a Small Routine or you can say it’s a Background Process Thread that
runs periodically and try to identify what objects are not being used currently by the application
and de-allocates the memory of those objects.
So, Garbage Collector is nothing but, it is a feature provided by CLR which helps us to clean or
destroy unused managed objects. Cleaning or destroying those unused managed objects basically
reclaim the memory.
Note: The Garbage Collector will destroy only the unused managed objects. It does not clean
unmanaged objects.
Programming Platform of .NET Framework
The .NET Framework is a software development platform that was introduced by Microsoft in
the late 1990 under the NGWS. On 13 February 2002, Microsoft launched the first version of the
.NET Framework, referred to as the .NET Framework 1.0.
It is a virtual machine that provide a common platform to run an application that was built using
the different language such as C#, VB.NET, C++, etc. It is also used to create a form based,
console-based, mobile and web-based application or services that are available in Microsoft
environment. Furthermore, the .NET framework is a pure object oriented, that similar to the Java
language. But it is not a platform independent as the Java. So, its application runs only to the
windows platform. The main objective of this framework is to develop an application that can
run on the windows platform.
.Net Framework Architecture
The two major components of the .NET Framework are the Common Language Runtime and the
.NET Framework Class Library.
1. CLR: The Common Language Runtime (CLR) is the execution engine that handles
running applications. It provides services like thread management, garbage collection, type
safety, exception handling, and more.
2. BCL: The Base Class Library provides a set of APIs and types for common functionality. It
provides types for strings, dates, numbers, etc. The Class Library includes APIs for reading
and writing files, connecting to databases, drawing, and more.
The .NET applications are written in C#, F#, or VB programming languages. The Source Code is
compiled into an intermediate language code called IL or MSIL or CIL (Common Intermediate
Language). And the Compiled code is stored in assemblies with .DLL or .EXE file extension.
When an application runs, the CLR takes the Assembly (IL Code or MSIL Code, or CIL) and
uses the Just-in-Time compiler (JIT) to convert the MSIL or IL code into machine code that
can execute on the specific architecture of the computer it is running on.
Introduction to C#
C# is pronounced "C-Sharp". C# is a simple & powerful object-oriented programming
language developed by Microsoft that runs on the .NET Framework.
C# can be used to create various types of applications, such as web, windows, console
applications, or other types of applications using Visual studio. C# has roots from the C
family, and the language is close to other popular languages like C++ and Java.
Anders Hejlsberg is known as the founder of C# language. The first version was released in
year 2002. The latest version, C# 11, was released in November 2022.
C# is used for:








Mobile applications
Desktop applications
Web applications
Web services
Web sites
Games
VR
Database applications
C# Features
C# is object oriented programming language. It provides a lot of features that are given below.
1. Simple
2. Modern programming language
3. Object oriented
4. Type safe
5. Interoperability
6. Scalable and Updateable
7. Component oriented
8. Structured programming language
9. Rich Library
10. Fast speed
1) Simple
C# is a simple language in the sense that it provides structured approach (to break the problem
into parts), rich set of library functions, data types etc.
2) Modern Programming Language
C# programming is based upon the current trend and it is very powerful and simple for building
scalable, interoperable and robust applications.
3) Object Oriented
C# is object oriented programming language. OOPs makes development and maintenance easier
where as in Procedure-oriented programming language it is not easy to manage if code grows as
project size grow.
4) Type Safe
C# type safe code can only access the memory location that it has permission to execute.
Therefore it improves a security of the program.
5) Interoperability
Interoperability process enables the C# programs to do almost anything that a native C++
application can do.
6) Scalable and Updateable
C# is automatic scalable and updateable programming language. For updating our application we
delete the old files and update them with new ones.
7) Component Oriented
C# is component oriented programming language. It is the predominant software development
methodology used to develop more robust and highly scalable applications.
8) Structured Programming Language
C# is a structured programming language in the sense that we can break the program into parts
using functions. So, it is easy to understand and modify.
9) Rich Library
C# provides a lot of inbuilt functions that makes the development fast.
10) Fast Speed
The compilation and execution time of C# language is fast.
First C# Program
Here, you will learn to create a simple console application in C# and understand the basic
building blocks of a console application.
C# can be used in a window-based, web-based, or console application. To start with, we will
create a console application to work with C#.
Open Visual Studio (2017 or later) installed on your local machine. Click on File -> New
Project... from the top menu, as shown below.
Create a New Project in Visual Studio 2019
From the New Project popup, shown below, select Visual C# in the left side panel and select
the Console App in the right-side panel.
Select Visual C# Console App Template
In the name section, give any appropriate project name, a location where you want to create
all the project files, and the name of the project solution.
Click OK to create the console project. Program.cs will be created as default a C# file in
Visual Studio where you can write your C# code in Program class, as shown below. (The .cs
is a file extension for C# file.)
C# Console Program
Every console application starts from the Main() method of the Program class. The following
example displays "Hello World!!" on the console.
Example: C# Console Application
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string message = "Hello World!!";
Console.WriteLine(message);
}
}
}
The following image illustrates the important parts of the above example.
C# Code Structure
Let's understand the above C# structure.
1. Every .NET application takes the reference of the necessary .NET framework namespaces
that it is planning to use with the using keyword, e.g., using System.Text.
2. Declare the namespace for the current class using the namespace keyword, e.g., namespace
MyApplication
3. We then declared a class using the class keyword: class Program
4. The Main() is a method of Program class is the entry point of the console application.
5. string is a data type.
6. A message is a variable that holds the value of a specified data type.
7. “Hello World!!” is the value of the message variable.
8. The Console.WriteLine() is a static method, which is used to display a text on the console.
Note: Every line or statement in C# must end with a semicolon (;).
Output:
Hello World!!
Integrated Development Environment (IDE) for C#
Visual Studio is the Integrated Development Environment in which developers work when
creating programs in one of many languages, including C#, for the .NET Framework . It is used
to create console and graphical user interface (GUI) applications along with Windows Forms or
WPF (Windows Presentation Foundation) applications, web applications, and web services in
both native code together with managed code for all platforms supported by Microsoft Windows,
Windows Mobile, Windows CE, .NET Framework, .NET Compact Framework and Microsoft
Silverlight.
It offers a set of tools that help you to write and modify the code for your programs, and also
detect and correct errors in your programs. Visual Studio supports various programming
languages by means of language services, which allow the code editor and debugger to support
nearly any programming language, provided a language-specific service exists. Like any other
IDE, it includes a code editor that supports syntax highlighting and code completion using
IntelliSense for not only variables, functions and methods but also language constructs like loops
and queries.
Microsoft Visual Studio is a powerful IDE that ensures quality code throughout the entire
application lifecycle, from design to deployment. Some windows are used for writing code, some
for designing interfaces, and others for getting a general overview of files or classes in your
application. Microsoft Visual Studio includes a host of visual designers to aid in the development
of various types of applications. These tools include such as Windows Forms Designer, WPF
(Windows Presentation Foundation) Designer, Web development, Class designer, Data designer
and Mapping designer.
Microsoft provides the following development tools for C# programming −



Visual Studio 2010 (VS)
Visual C# 2010 Express (VCE)
Visual Web Developer
The last two are freely available from Microsoft official website. Using these tools, you can
write all kinds of C# programs from simple command-line applications to more complex
applications. You can also write C# source code files using a basic text editor, like Notepad, and
compile the code into assemblies using the command-line compiler, which is again a part of the
.NET Framework.
Visual C# Express and Visual Web Developer Express edition are trimmed down versions of
Visual Studio and has the same appearance. They retain most features of Visual Studio. In this
tutorial, we have used Visual C# 2010 Express.
Visual Development and Event Driven Programming
Forms and controls are the basic elements in the user interface of any .windows application. In
Visual Development, these elements are called objects because they are manipulated like objects.
Objects have properties and methods, and they read to external events, as does any physical
object. Most control properties are set when the object is created (placed on the Form), but you
can change a property later by assigning a new value to it. You can change a property at
design time (through the Properties window) or-at runtime (through your code).
Event-driven programming is a programming paradigm in which the flow of program execution
is determined by events - for example a user action such as a mouse click, key press, or a
message from the operating system or another program. An event-driven application is designed
to detect events as they occur, and then deal with them using an appropriate event-handling
procedure. The idea is an extension of interrupt-driven programming of the kind found in early
command-line environments such as DOS, and in embedded systems.
Event-driven programs can be written in any programming language, although some
languages(C# for example) are specifically designed to facilitate event-driven programming, and
provide an integrated development environment (IDE) that partially automates the production of
code, and provides a comprehensive selection of built-in objects and controls, each of which can
respond to a range of events. Virtually all object-oriented and visual languages support eventdriven programming. Visual Basic, Visual C++, Visual C# and Java are examples of such
languages.
A visual programming IDE such as C#.Net provides much of the code for detecting events
automatically when a new application is created. The programmer can therefore concentrate on
issues such as interface design, which involves adding controls such as command buttons, text
boxes, and labels to standard forms (a form represents an application's workspace or window).
Once the user interface is substantially complete, the programmer can add event-handling code
to each control as required.
Many visual programming environments will even provide code templates for event-handlers, so
the programmer only needs to provide the code that defines the action the program should take
when the event occurs. Each event-handler is usually bound to a specific object or control on a
form. Any additional subroutines, methods, or function procedures required are usually placed in
a separate code module, and can be called from other parts of the program as and when needed.
if you want to write blocks of code that execute in response to a certain event, like when a user
clicks a button in your application? This is called event-driven programming.
Appropriately handling events is essential when developing desktop, mobile, and web
applications. Event-driven programming allows you to write code that responds to specific
events that are raised in your application. Such events could be triggered by the application itself
or by the user, such as when the user clicks a button or presses a key.
Events in C#
Events in C# are a mechanism that classes use to send notifications or messages to other classes.
They are a specialized delegate type that we use to notify other classes when something they
listen to happens. Events are a vital part of many applications, and a perfect way to decouple and
create flexible and extendable applications.
Some of the properties of events are given as follows:
1. Events have publishers and subscribers. The publishers determine when an event is raised
while the subscribers determine the actions that are performed in response to the event.
2. If there are no subscribers for an event, then event is never raised. However, for an event
there can be many subscribers.
3. If an event has many subscribers, when the event is raised the event handlers are invoked
synchronously.
4. User actions such as menu selections, button clicks etc. are signaled by using events.
5. The events are based on the EventHandler delegate and the EventArgs base class.
Event Syntax
The events are declared using the keyword event. The syntax for this is given as followed:
event delegate_nameevent_name;
In the above syntax, the keyword event is followed by the delegate name and then the event
name.
A program that demonstrates events is given as follows:
Source Code: Program to implement Events in C#
using System;
namespace Example {
public delegate string demoDelegate(string str1, string str2);
class MyEvents {
event demoDelegatemyEvent;
public MyEvents() {
this.myEvent += new demoDelegate(this.Display);
}
public string Display(string studentname, string subject) {
return "Student: " + studentname + "\nSubject: " +subject;
}
static void Main(string[] args) {
MyEvents e = new MyEvents();
string res = e.myEvent("Jack", "Science");
Console.WriteLine("RESULT...\n"+res);
}
}
}
The output of the above program is as follows:
RESULT...
Student: Jack
Subject: Science
C# Data Types
A data type specifies the type of data that a variable can store such as integer, floating, character
etc.
C# is a strongly-typed language. It means we must declare the type of a variable that
indicates the kind of values it is going to store, such as integer, float, decimal, text, etc.
There are 3 types of data types in C# language.
Types
Data Types
Value Data Type
short, int, char, float, double etc
Reference Data Type
String, Class, Object and Interface
Pointer Data Type
Pointers
Value Data Type
The value data types are integer-based and floating-point based. C# language supports both
signed and unsigned literals.
There are 2 types of value data type in C# language.
1) Predefined Data Types - such as Integer, Boolean, Float, etc.
2) User defined Data Types - such as Structure, Enumerations, etc.
The memory size of data types may change according to 32 or 64 bit operating system.
Let's see the value data types. It size is given according to 32 bit OS.
Data Types
Memory Size
Range
Char
1 byte
-128 to 127
signed char
1 byte
-128 to 127
unsigned char
1 byte
0 to 127
Short
2 byte
-32,768 to 32,767
signed short
2 byte
-32,768 to 32,767
unsigned short
2 byte
0 to 65,535
Int
4 byte
-2,147,483,648 to -2,147,483,647
signed int
4 byte
-2,147,483,648 to -2,147,483,647
unsigned int
4 byte
0 to 4,294,967,295
Long
8 byte
?9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
signed long
8 byte
?9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
unsigned long
8 byte
0 - 18,446,744,073,709,551,615
Float
4 byte
1.5 * 10-45 - 3.4 * 1038, 7-digit precision
Double
8 byte
5.0 * 10-324 - 1.7 * 10308, 15-digit precision
decimal
16 byte
at least -7.9 * 10?28 - 7.9 * 1028, with at least 28-digit precision
Reference Data Types: The Reference Data Types will contain a memory address of
variable value because the reference types won’t store the variable value directly in
memory. The built-in reference types are string, object.
There are 2 types of reference data type in C# language.
1) Predefined Types - such as Objects, String.
2) User defined Types - such as Classes, Interface.
1. Predefined Types
String : It represents a sequence of Unicode characters and its type name is System.String.
So, string and String are equivalent.
Example :
string s1 = "hello"; // creating through string keyword
String s2 = "welcome"; // creating through String class
Object : In C#, all types, predefined and user-defined, reference types and value types,
inherit directly or indirectly from Object. So basically it is the base class for all the data
types in C#. Before assigning values, it needs type conversion. When a variable of a value
type is converted to object, it’s called boxing. When a variable of type object is converted
to a value type, it’s calle
d unboxing. Its type name is System.Object.
Example :
// C# program to demonstrate the Reference data types
Using System;
namespace ValueTypeTest {
class Test{
// Main Function
Static void Main()
{
// declaring string
string a = "Nutan";
//append in a
a+=" College ";
a = a+" Bhopal ";
Console.WriteLine(a);
// declare object obj
object obj;
obj = 20;
Console.WriteLine(obj);
// to show type of object using GetType()
Console.WriteLine(obj.GetType());
}
}
}
Output :
Nutan College Bhopal
System.Int32
Pointer Data Type : The Pointer Data Types will contain a memory address of the variable
value.
To get the pointer details we have a two symbols ampersand (&) and asterisk (*).
ampersand (&): It is Known as Address Operator. It is used to determine the address of a
variable.
asterisk (*): It also known as Indirection Operator. It is used to access the value of an address.
Syntax :
type* identifier;
Example :
int* p1, p; // Valid syntax
int *p1, *p; // Invalid
Declaring a pointer
The pointer in C# language can be declared using * (asterisk symbol).
int * a; //pointer to int
char * c; //pointer to char
Type conversion
Type conversion is converting one type of data to another type. It is also known as Type Casting.
In C#, type casting has two forms −

Implicit type conversion − These conversions are performed by C# in a type-safe manner.
For example, are conversions from smaller to larger integral types and conversions from
derived classes to base classes.

Explicit type conversion − These conversions are done explicitly by users using the predefined functions. Explicit conversions require a cast operator.
The following example shows an explicit type conversion −
Using System;
namespace TypeConversionApplication
{
class Explicit Conversion{
static void Main(string[] args)
{
double d =5673.74;
int i;
// cast double to int.
i=(int)d;
Console.WriteLine(i);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
5673
C# Type Conversion Methods
C# provides the following built-in type conversion methods −
Sr.No.
1
Methods & Description
ToBoolean
Converts a type to a Boolean value, where possible.
2
ToByte
Converts a type to a byte.
3
ToChar
Converts a type to a single Unicode character, where possible.
4
ToDateTime
Converts a type (integer or string type) to date-time structures.
5
ToDecimal
Converts a floating point or integer type to a decimal type.
6
ToDouble
Converts a type to a double type.
7
ToInt16
Converts a type to a 16-bit integer.
8
ToInt32
Converts a type to a 32-bit integer.
9
ToInt64
Converts a type to a 64-bit integer.
10
ToSbyte
Converts a type to a signed byte type.
11
ToSingle
Converts a type to a small floating pointnumber.
12
ToString
Converts a type to a string.
13
ToType
Converts a type to a specified type.
14
ToUInt16
Converts a type to an unsigned int type.
15
ToUInt32
Converts a type to an unsigned long type.
16
ToUInt64
Converts a type to an unsigned big integer.
The following example converts various value types to string type −
using System;
Namespace TypeConversionApplication{
class StringConversion{
Static void Main(string[] args){
int i=75;
float f =53.005f;
double d =2345.7652;
bool b =true;
Console.WriteLine(i.ToString());
Console.WriteLine(f.ToString());
Console.WriteLine(d.ToString());
Console.WriteLine(b.ToString());
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
75
53.005
2345.7652
True
C# 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.
The basic variable type available in C# can be categorized as:
Variable Type
Example
Decimal types
Decimal
Boolean types
True or false value, as assigned
Integral types
int, char, byte, short, long
Floating point types
float and double
Nullable types
Nullable data types
type variable_list;
The example of declaring variable is given below:
int i, j;
double d;
float f;
char ch;
Here, i, j, d, f, ch are variables and int, double, float, char are data types.
We can also provide values while declaring the variables as given below:
int i=2,j=4; //declaring 2 variable of integer type
float f=40.2;
char ch='B';
Rules for defining variables




A variable can have alphabets, digits and underscore.
A variable name can start with alphabet and underscore only. It can't start with digit.
No white space is allowed within variable name.
A variable name must not be any reserved word or keyword e.g. char, float etc.
Valid variable names:
int x;
int _x;
int k20;
Invalid variable names:
int 4;
int x y;
int double;
Initializing Variables
Variables are initialized (assigned a value) with an equal sign followed by a constant expression.
The general form of initialization is −
variable_name = value;
Variables can be initialized in their declaration. The initializer consists of an equal sign followed
by a constant expression as −
<data_type><variable_name> = value;
Some examples are −
int d =3, f =5; /* initializing d and f. */
byte z =22;
/* initializes z. */
double pi =3.14159;
/* declares an approximation of pi. */
char x ='x';
/* the variable x has the value 'x'. */
It is a good programming practice to initialize variables properly, otherwise sometimes program
may produce unexpected result.
The following example uses various types of variables −
using System;
Namespace VariableDefinition{
class Program{
static void Main(string[]args){
short a;
intb ;
double c;
/* actual initialization */
a =10;
b =20;
c = a + b;
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
a = 10, b = 20, c = 30
Accepting Values from User
The Console class in the System namespace provides a function ReadLine() for accepting input
from the user and store it into a variable.
For example,
int num;
num =Convert.ToInt32(Console.ReadLine());
The function Convert.ToInt32() converts the data entered by the user to int data type,
because Console.ReadLine() accepts the data in string format.
Lvalue and Rvalue Expressions in C#
There are two kinds of expressions in C# −
1. lvalue − An expression that is anlvalue may appear as either the left-hand or right-hand side of
an assignment.
2. rvalue − An expression that is anrvalue may appear on the right- but not left-hand side of an
assignment.
Variables are lvalues and hence they may appear on the left-hand side of an assignment. Numeric
literals are rvalues and hence they may not be assigned and can not appear on the left-hand side.
Following is a valid C# statement −
int g = 20;
Constants
If you don't want others (or yourself) to overwrite existing values, you can add
the const keyword in front of the variable type.
This will declare the variable as "constant", which means unchangeable and read-only:
Example
const int myNum=15;
myNum=20; // error
The const keyword is useful when you want a variable to always store the same value, so that
others (or yourself) won't mess up your code. An example that is often referred to as a constant,
is PI (3.14159...).
Note: You cannot declare a constant variable without assigning the value. If you do, an error will
occur: A const field requires a value to be provided.
C# operators
An operator is simply a symbol that is used to perform operations. There can be many types of
operations like arithmetic, logical, bitwise etc.
Operators are used to In C#, perform operations on variables and values.
Operators can also categorized based upon Number of Operands :



Unary Operator: Operator that takes one operand to perform the operation.
Binary Operator: Operator that takes two operands to perform the operation.
Ternary Operator: Operator that takes three operands to perform the operation.
In the example below, we use the +operator to add together two values:
Example
int x =100+50;
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations:
Operator
Name
Description
Example
+
Addition
Adds together two values
x+y
-
Subtraction
Subtracts one value from another
x–y
*
Multiplication
Multiplies two values
x*y
/
Division
Divides one value by another
x/y
%
Modulus
Returns the division remainder
x%y
++
Increment
Increases the value of a variable by 1
x++
--
Decrement
Decreases the value of a variable by 1
x--
C# Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the value 10 to a variable
called x:
Example
int x =10;
The addition assignment operator (+=) adds a value to a variable:
Example
int x =10;
x +=5;
A list of all assignment operators:
Operator
Example
Same As
=
x=5
x=5
+=
x += 3
x=x+3
-=
x -= 3
x=x–3
*=
x *= 3
x=x*3
/=
x /= 3
x=x/3
%=
x %= 3
x=x%3
&=
x &= 3
x=x&3
|=
x |= 3
x=x|3
^=
x ^= 3
x=x^3
Example:
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 10;
x += 5;
Console.WriteLine(x);
}
}
}
C# Comparison Operators
Comparison operators are used to compare two values:
Operator
Name
Example
==
Equal to
x == y
!=
Not equal
x != y
>
Greater than
x>y
<
Less than
x<y
>=
Greater than or equal to x >= y
<=
Less than or equal to
x <= y
C# Logical Operators
Logical operators are used to determine the logic between variables or values:
Operator
Name
Description
&&
Logical and Returns true if both statements are true
x < 5 && x< 10
||
Logical or
x < 5 || x < 4
!
Logical not Reverse the result, returns false if the result is
true
Returns true if one of the statements is true
Example
using System;
namespace MyApplication
{
Example
!(x < 5 && x < 10)
class Program
{
static void Main(string[] args)
{
int x = 5;
Console.WriteLine(x > 3 && x < 10);
// returns True
}
}
}
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
Console.WriteLine(!(x > 3 && x < 10));
// returns False
}
}
}
Bitwise Operators
In C#, there are 6 bitwise operators which work at bit level or used to perform bit by bit
operations. Following are the bitwise operators:




& (bitwise AND) Takes two numbers as operands and does AND on every bit of two
numbers. The result of AND is 1 only if both bits are 1.
| (bitwise OR) Takes two numbers as operands and does OR on every bit of two numbers.
The result of OR is 1 any of the two bits is 1.
^ (bitwise XOR) Takes two numbers as operands and does XOR on every bit of two
numbers. The result of XOR is 1 if the two bits are different.
<< (left shift) Takes two numbers, left shifts the bits of the first operand, the second
operand decides the number of places to shift.

>> (right shift) Takes two numbers, right shifts the bits of the first operand, the second
operand decides the number of places to shift.
Example:
// C# program to demonstrate the working of Bitwise Operators
Using System;
Namespace Bitwise {
Class Test{
// Main Function
static void Main(string[] args)
{
int x = 5, y = 10, result;
// Bitwise AND Operator
result = x & y;
Console.WriteLine("Bitwise AND: "+ result);
// Bitwise OR Operator
result = x | y;
Console.WriteLine("Bitwise OR: "+ result);
// Bitwise XOR Operator
result = x ^ y;
Console.WriteLine("Bitwise XOR: "+ result);
// Bitwise AND Operator
result = ~x;
Console.WriteLine("Bitwise Complement: "+ result);
// Bitwise LEFT SHIFT Operator
result = x << 2;
Console.WriteLine("Bitwise Left Shift: "+ result);
// Bitwise RIGHT SHIFT Operator
result = x >> 2;
Console.WriteLine("Bitwise Right Shift: "+ result);
}
}
}
Output:
Bitwise AND: 0
Bitwise OR: 15
Bitwise XOR: 15
Bitwise Complement: -6
Bitwise Left Shift: 20
Bitwise Right Shift: 1
Conditional Operator
It is ternary operator which is a shorthand version of if-else statement. It has three operands
and hence the name ternary. It will return one of two values depending on the value of a
Boolean expression.
Syntax:
condition ?first_expression : second_expression;
Explanation:
condition: It must be evaluated to true or false.
If the condition is true, first_expression is evaluated and becomes the result.
If the condition is false, second_expression is evaluated and becomes the result.
Example:
// C# program to demonstrate the working of Conditional Operator
using System;
namespace Conditional
{
class Test{
// Main Function
static void Main(string[] args)
{
int x = 5, y = 10, result;
// To find which value is greater using Conditional Operator
result = x >y ? x : y;
// To display the result
Console.WriteLine("Result: "+ result);
}
}
}
Output :
Result: 10
Result: 5
Decision Making Statements
A programming language uses decision making statements to control the flow of execution of
program based on certain conditions. Decision making statements contain conditions that are
evaluated by the program. If the condition is true, then a set of statements are executed and if the
condition is false then another set of statements is executed.
There are many decision making statements in C# such as:
• if statement
• if else statement
• if else if statement
• nested if statement
• switch statement
if Statement
The if statement checks the given condition. If the condition evaluates to be true then the
block of code/statements will execute otherwise not.
Syntax:
if(condition)
{
//code to be executed
}
Note: If the curly brackets { } are not used with if statements than the statement just next to
it is only considered associated with the if statement.
Example:
// C# program to illustrate if statement
using System;
public class Test
{
public static void Main(string[] args)
{
int age = 19;
if (age>=18)
{
Console.WriteLine("Eligible for Voting");
}
}
}
Output:
Eligible for Voting
if-else statement
The "if statement" will ensure the given condition and if the condition becomes true, then the
block of statements enclosed within curly braces will get executed; otherwise, the block of code
associated with the else will get executed.
Syntax:
if(condition)
{
// if condition is true
}
else
{
// if the condition becomes false
}
Example:
using System;
namespace Demo {
public class Example {
public static void Main(string[] args) {
int a = 10;
int b=15;
if (a>b)
Console.WriteLine("a is big number");
else
Console.WriteLine("b is big number");
}
}
}
Output
B is big number
If else if ladder statement
The if-else-if ladder statement executes one condition from multiple statements. The
execution starts from top and checked for each if condition. The statement of if block will be
executed which evaluates to be true. If none of the if condition evaluates to be true then the
last else block is evaluated.
Syntax:
if(condition1)
{
// code to be executed if condition1 is true
}
else if(condition2)
{
// code to be executed if condition2 is true
}
else if(condition3)
{
// code to be executed if condition3 is true
}
...
else
{
// code to be executed if all the conditions are false
}
Example
// C# program to illustrate if else if ladder
using System;
class Greatest
{
public static void Main(String[] args)
{
int a = 20;
int b=12;
int c=15;
if (a>b&&a>c)
Console.WriteLine("a is greatest");
else if (b>a&&b>c)
Console.WriteLine("b is greatest");
else
Console.WriteLine("c is greatest");
}
}
Output:
a is greatest
Nested If Statement
if statement inside an if statement is known as nested if. if statement in this case is the target
of another if or else statement. When more than one condition needs to be true and one of the
condition is the sub-condition of parent condition, nested if can be used.
Syntax:
if (condition1)
{
// code to be executed
// if condition2 is true
if (condition2)
{
// code to be executed
// if condition2 is true
}
}
Exampleusing System;
namespace Test
{
class Program
{
static void Main(string[] args)
{
int x = 5, y = 20;
if (x > y)
{
if (x >= 10)
{
Console.WriteLine("x value greater than or equal to 10");
}
else
{
Console.WriteLine("x value less than 10");
}
}
else
{
if (y <= 20)
{
Console.WriteLine("y value less than or equal to 20");
}
else
{
Console.WriteLine("y value greater than 20");
}
}
Console.ReadLine();
}
}
}
Output:
y value less than or equal to 20
Switch Statement
Switch statement is an alternative to long if-else-if ladders. The expression is checked for
different cases and the one match is executed. break statement is used to move out of the
switch. If the break is not used, the control will flow to all cases below it until break is found
or switch comes to an end. There is default case (optional) at the end of switch, if none of the
case matches then default case is executed.
Syntax:
switch (expression)
{
case value1: // statement sequence
break;
case value2: // statement sequence
break;
.
.
.
case valueN: // statement sequence
break;
default: // default statement sequence
}
Example
using System;
public class Test
{
public static void Main(String[] args)
{
int number = 3;
switch(number)
{
case 1: Console.WriteLine("Monday");
break;
case 2: Console.WriteLine("Tuesday");
break;
case 3: Console.WriteLine("Wednesday");
break;
case 4: Console.WriteLine("Thursday");
break;
case 5: Console.WriteLine("Friday");
break;
case 6: Console.WriteLine("Saturday");
break;
case 7: Console.WriteLine("Sunday");
break;
default: Console.WriteLine("Invalid Choice");
break;
}
}
}
Output:
Wednesday
Loops Statements
Loops are also called repeating statements or iterative statements. There may be a situation,
when you need to execute a block of code several numbers of times. Loops are used to execute
one or more statements multiple times until a specified condition is fulfilled. When the condition
becomes false the execution of the loops terminates. So, in simple words, we can say that Loop is
nothing but repeating some tasks for some amount of time until the condition is true.
Loops play an important role in programming.
Types of Loops in C#
Iteration statements create loops in the program. It repeats the same code several times until a
specified condition is satisfied. Iteration statements execute the same set of instructions until a
termination condition is met. There are four types of looping statements in C#. They are as
follows:
1. while loop
2. do while loop
3. for loop
4. foreach Loop
Loops are mainly divided into two categories:
1. Entry Controlled Loops: The loops in which the condition to be tested is present at
beginning of the loop body are known as Entry Controlled Loops. Examples of Entry
Controlled Loops are while loop and for loop.
2. Exit Controlled Loops: The loops in which the testing condition is present at the end of the
loop body are termed Exit Controlled Loops. An example of Exit Controlled Loop is the dowhile loop. In Exit Controlled Loops, the loop body will be evaluated at least one time as the
testing condition is present at the end of the loop body.
while loop
The test condition is given in the beginning of the loop and all statements are executed till the
given boolean condition satisfies when the condition becomes false, the control will be out
from the while loop.
Syntax:
while (boolean condition)
{
loop statements...
}
Example
class Example {
static void Main(string[] args) {
int i = 1;
Console.WriteLine("First 10 Natural Numbers are: ");
while (i <= 10)
{
Console.WriteLine( i );
i++;
}
}
}
Output
First 10 Natural Numbers are:
1
2
3
4
5
6
7
8
9
10
do-while loop
The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.
Syntax
do
{
// code block to be executed
}
while (condition);
The example below uses a do/while loop. The loop will always be executed at least once, even if
the condition is false, because the code block is executed before the condition is tested:
class Example
{
static void Main(string[] args) {
int i = 1;
Console.WriteLine("First 10 Natural Numbers are: ");
do
{
Console.WriteLine( i );
i++;
} while (i <= 10);
}
}
The output of the above program is as follows:
First 10 Natural Numbers are:
1
2
3
4
5
6
7
8
9
10
for loop
The for loop executes one or more statements multiple times as long as the loop condition is
satisfied. If the loop condition is true, the body of the for loop is executed. Otherwise, the control
flow jumps to the next statement after the for loop.
The syntax of the for loop is given below:
for ( initialization, condition, increment /decrement)
{
// These statements will be executed if the condition evaluates to true
}
Example
class Example {
static void Main(string[] args) {
Console.WriteLine("First 10 Natural Numbers are: ");
for (int i = 1; i <= 10; i++)
Console.WriteLine(i);
}
}
}
The output of the above program is as follows:
First 10 Natural Numbers are:
1
2
3
4
5
6
7
8
9
10
foreach loop in C#
C# provides an easy to use and more readable alternative to for loop, the foreach loop when
working with arrays and collections to iterate through the items of arrays/collections. The
foreach loop iterates through each item, hence called foreach loop. A program that demonstrates
the foreach loop is given as follows:
foreach (type variableName in collection)
{
// code block to be executed
}
Example
using System;
namespace LoopDemo
{
class Example {
static void Main(string[] args) {
Console.WriteLine("First 10 Natural Numbers are: ");
int[] naturalNos = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
foreach (int i in naturalNos)
{
Console.WriteLine(i);
}
}
}
}
The output of the above program is as follows:
First 10 Natural Numbers are:
1
2
3
4
5
6
7
8
9
10
Object and Class
Since C# is an object-oriented language, program is designed using objects and classes in C#.
C# Object
In C#, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.
In other words, object is an entity that has state and behavior. Here, state means data and
behavior means functionality.
Object is a runtime entity, it is created at runtime.
Object is an instance of a class. All the members of the class can be accessed through object.
Let's see an example to create object using new keyword.
Student s1 = new Student();
//creating an object of Student
In this example, Student is the type and s1 is the reference variable that refers to the instance of
Student class. The new keyword allocates memory at runtime.
Class
In C#, class is a group of similar objects. It is a template from which objects are created. It can
have fields, methods, constructors etc.
Let's see an example of C# class that has two fields only.
public class Student
{
int roll;
//field or data member
String name;
//field or data member
}
Object and Class Example
Let's see an example of class that has two fields: id and name. It creates instance of the class,
initializes the object and prints the object value.
using System;
public class Student
{
int roll;
//data member (also instance variable)
String name;
//data member(also instance variable)
public static void Main(string[] args)
{
Student s1 = new Student();
s1.id = 2112345;
s1.name = "Ram";
Console.WriteLine(s1.id);
Console.WriteLine(s1.name);
}
}
Output:
2112345
Ram
//creating an object of Student
Method in C#
A method is a group of statements that together perform a task. Every C# program has at least
one class with a method named Main. A method is a block of code which only runs when it is
called.
You can pass data, known as parameters, into a method. Methods are also known as functions.
Defining Methods in C#
When you define a method, you basically declare the elements of its structure. The syntax for
defining a method in C# is as follows −
<Access Specifier> <Return Type> <Method Name>(Parameter List) {
Method Body
}
Following are the various elements of a method −
Access Specifier − It defines access type of the method i.e. from where it can be accessed in
your application.
In C#, there are three types of access modifiers:
 Public: All methods have access to the code.
 Private: Only the current method has access to the code.
 Protected: It is only available within the same class or a subclass of that class.
Return type − A method may return a value. The return type is the data type of the value the
method returns. If the method is not returning any values, then the return type is void.
Method name − Method name is a unique identifier and it is case sensitive. It cannot be same
as any other identifier declared in the class.
Parameter list − Comma separated list of the input parameters are defined, preceded with
their data type, within the enclosed parenthesis. If there are no parameters, then empty
parentheses () have to use out.
Method body − It refers to the line of code of tasks to be performed by the method during its
execution. It is enclosed between braces.
Example
Following code snippet shows a function FindMax that takes two integer values and returns the
larger of the two. It has public access specifier, so it can be accessed from outside the class using
an instance of the class.
class NumberManipulator
{
public int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
...
}
Calling Methods in C#
You can call a method using the name of the method. The following example illustrates this −
class NumberManipulator {
public int FindMax(int num1, int num2) {
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
static void Main(string[] args)
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
NumberManipulator n = new NumberManipulator();
//calling the FindMax method
ret = n.FindMax(a, b);
Console.WriteLine("Max value is : {0}", ret );
Console.ReadLine();
}
}
When the above code is compiled and executed, it produces the following result −
Max value is : 200
Example 2:
using System;
namespace Method {
class Program {
// method declaration
public void display() {
Console.WriteLine("Hello World");
}
static void Main(string[] args) {
// create class object
Program p1 = new Program();
//call method
p1.display();
Console.ReadLine();
}
}
}
Output
Hello World
In the above example, we have created a method named display(). We have created an object p1
of the Program class. Notice the line,
p1.display();
Here, we are using the object to call the display() method.
Example 3:
using System;
namespace Method
{
class Program
{
// method declaration
static int addNumbers() {
int sum = 5 + 14;
return sum;
}
static void Main(string[] args)
{
// call method
int sum = addNumbers();
Console.WriteLine(sum);
Console.ReadLine();
}
}
}
Output
19
In the above example, we have a method named addNumbers() with the int return type.
int sum = addNumbers();
Here, we are storing the returned value from the addNumbers() to sum. We have used int data
type to store the value because the method returns an int value.
Note: As the method is static we do not create a class object before calling the method. The
static method belongs to the class rather than the object of a class.
Example 4:
using System;
namespace Method {
class Program {
int addNumber (int a, int b) {
int sum = a + b;
return sum;
}
static void Main(string[] args) {
// create class object
Program p1 = new Program();
//call method
int sum = p1.addNumber(100,100);
Console.WriteLine("Sum: " + sum);
Console.ReadLine();
}
}
}
Output
Sum: 200
C# Arrays
Like other programming languages, array in C# is a group of similar types of elements that have
contiguous memory location. In C#, array is an object of base type System.Array. In C#, array
index starts from 0. We can store only fixed set of elements in C# array.
Advantages of C# Array





Code Optimization (less code)
Random Access
Easy to traverse data
Easy to manipulate data
Easy to sort data etc.
Disadvantages of C# Array


Fixed size
Store Heterogeneous Data
Types of Array
There are 3 types of arrays in C# programming:
1. Single Dimensional Array
2. Multidimensional Array
3. Jagged Array
C# Single Dimensional Array
To create single dimensional array, you need to use square brackets [] after the type.
int[] arr = new int[5];
//creating array
You cannot place square brackets after the identifier.
int arr[] = new int[5];
//compile time error
Let's see a simple example of C# array, where we are going to declare, initialize and traverse
array.
Example
using System;
public class ArrayExample
{
public static void Main(string[] args)
{
int[] arr = new int[5];
//creating array
arr[0] = 10;
//initializing array
arr[1] = 15;
arr[2] = 20;
arr[3] = 25;
arr[4] = 30;
//traversing array
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
}
}
Output:
10
15
20
25
30
C# Array Example: Declaration and Initialization at same time
There are 3 ways to initialize array at the time of declaration.
int[] arr = new int[5]{ 10, 20, 30, 40, 50 };
We can omit the size of array.
int [] arr = new int[]{ 10, 20, 30, 40, 50 };
We can omit the new operator also.
int[] arr = { 10, 20, 30, 40, 50 };
Let's see the example of array where we are declaring and initializing array at the same time.
using System;
public class ArrayExample
{
public static void Main(string[] args)
{
int[] arr = { 10, 20, 30, 40, 50 };//Declaration and Initialization of array
//traversing array
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
}
}
Output:
10
20
30
40
50
C# Array Example: Traversal using foreach loop
We can also traverse the array elements using foreach loop. It returns array element one by one.
using System;
public class ArrayExample
{
public static void Main(string[] args)
{
int[] arr = { 10, 20, 30, 40, 50 };//creating and initializing array
//traversing array
foreach (int i in arr)
{
Console.WriteLine(i);
}
}
}
Output:
10
20
30
40
50
Accessing Array Elements
Array elements can be accessed using an index. An index is a number associated with each
array element, starting with index 0 and ending with array size - 1.
The following examples add/update and retrieve array elements using indexes.
int[] evenNums = new int[5];
evenNums[0] = 2;
evenNums[1] = 4;
Console.WriteLine(evenNums[0]); //prints 2
Console.WriteLine(evenNums[1]); //prints 4
Example
using System;
namespace array_example1
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[10];
for (int x = 0; x < 10; x++)
{
Console.WriteLine("Enter array element : {0}", x + 1);
arr[x] = Int32.Parse(Console.ReadLine());
}
foreach (int i in arr)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
Note: If you do not initialize an array at the time of declaration, the array members are
automatically initialized to the default initial value for the array type. Also, if you declare the
array as a field of a type, it will be set to the default value null when you instantiate the type.
Something about foreach
In a for loop, you should know the number of element of the array. If you don't, the C#
language allows you to let the compiler use its internal mechanism to get this count and use it
to know where to stop counting. To assist you with this, C# provides the foreach operator.

foreach loop is used on enumerator type only.

foreach is read-only loop.

Multidimensional arrays (rectangular arrays)
Arrays can have more than one dimension; these arrays-of-arrays are called multidimensional
arrays. They are very similar to standard arrays with the exception that they have multiple sets of
square brackets after the array identifier.
The most common kind of multidimensional array is the two-dimensional array. A two
dimensional array can be thought of as a grid of rows and columns.
Declaring multidimensional array
string[,] names = new string[4, 4];
int[,] numbers = new int[3, 4];
Multidimensional array initialization
int[,] numbers = new int[3, 2] {{1,2}, {3,4}, {5,6}};
string[,] names = new string[2, 2] {{"Ana", "Anita"}, {"Bob", "Barbie"}};
You can omit the size of the array, like this:
int[,] numbers = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
string[,] names = new string[,] {{"Ana", "Anita"}, {"Bob", "Barbie"}};
You can also omit the new operator if you initialize array like this:
int[,] numbers = {{1,2}, {3,4}, {5,6}};
string[,] names = {{"Ana", "Anita"}, {"Bob", "Barbie"}};
Practical demonstration of multidimensional array
Example:
using System;
public class MultiArrayExample
{
public static void Main(string[] args)
{
int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };//declaration and initialization
//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
}
}
}
Output:
123
456
789
Example 2
using System;
public class MultiArrayExample
{
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;
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
}
}
}
Output:
0 10 0
0 0 20
30 0 0
Jagged Arrays (array-of-arrays)
Jagged arrays are often called array of arrays. More specifically, a jagged array is an array of
vectors In C#, a jagged array consists of multiple arrays as its element. However, unlike
multidimensional arrays, each array inside a jagged array can be of different sizes.
Here, the number of rows will be fixed at the declaration time, but you can vary the number of
columns.
C# Jagged Array Declaration
Here's a syntax to declare a jagged array in C#.
dataType[ ][ ] nameOfArray = new dataType[rows][ ];
Let's see an example,
// declare jagged array
int[ ][ ] jaggedArray = new int[2][ ];
Here,
int - data type of the array
[][] - represents jagged array
jaggedArray - name of the jagged array
[2][] - represents the number of elements (arrays) inside the jagged array
Since we know each element of a jagged array is also an array, we can set the size of the
individual array. For example,
// set size of the first array as 3
jaggedArray[0] = new int[3];
// set size of second array as 2
jaggedArray[1] = new int[2];
Initializing Jagged Array
There are different ways to initialize a jagged array. For example,
1. Using the index number
Once we declare a jagged array, we can use the index number to initialize it. For example,
initialize the first array
jaggedArray[0][0] = 1;
jaggedArray[0][1] = 3;
jaggedArray[0][2] = 5;
// initialize the second array
jaggedArray[1][0] = 2;
jaggedArray[1][1] = 4;
Here,
index at the first square bracket represents the index of the jagged array element
index at the second square bracket represents the index of the element inside each element of the
jagged array
2. Initialize without setting size of array elements
// declaring string jagged array
int[ ][ ] jaggedArray = new int[2] [ ];
// initialize each array
jaggedArray[0] = new int[] {1, 3, 5};
jaggedArray[1] = new int[] {2, 4};
3. Initialize while declaring Jagged Array
int[ ][ ] jaggedArray = {
new int[ ] {10, 20, 30},
new int[ ] {11, 22},
new int[ ] {88, 99}
};
Accessing elements of a jagged array
We can access the elements of the jagged array using the index number. For example,
// access first element of second array
jaggedArray[1][0];
// access second element of the second array
jaggedArray[1][1];
// access second element of the first array
jaggedArray[0][1];
Example: C# Jagged Array
using System;
namespace JaggedArray {
class Program {
static void Main(string[] args) {
// create a jagged array
int[ ][ ] jaggedArray = {
new int[] {1, 3, 5},
new int[] {2, 4},
};
// print elements of jagged array
Console.WriteLine("jaggedArray[1][0]: " + jaggedArray[1][0]);
Console.WriteLine("jaggedArray[1][1]: " + jaggedArray[1][1]);
Console.WriteLine("jaggedArray[0][2]: " + jaggedArray[0][2]);
Console.ReadLine();
}
}
}
Output
jaggedArray[1][0]: 2
jaggedArray[1][1]: 4
jaggedArray[0][2]: 5
Here, inside a jagged array,
jaggedArray[1][0] - first element of the second array
jaggedArray[1][1] - second element of the second array
jaggedArray[0][2] - third element of the first arraydemonstration of jagged array
Iterating through a jagged array
In C#, we can use loops to iterate through each element of the jagged array. For example,
using System;
namespace JaggedArray {
class Program {
static void Main(string[] args) {
// declare a jagged array
int[][] jaggedArray = new int[2][];
// set size of Jagged Array Elements
jaggedArray[0] = new int[3];
jaggedArray[1] = new int[2];
// initialize the first array
jaggedArray[0][0] = 1;
jaggedArray[0][1] = 3;
jaggedArray[0][2] = 5;
// initialize the second array
jaggedArray[1][0] = 2;
jaggedArray[1][1] = 2;
// outer for loop
for (int i = 0; i < jaggedArray.Length; i++) {
Console.Write("Element "+ i +": ");
// inner for loop
for (int j = 0; j < jaggedArray[i].Length; j++) {
Console.Write(jaggedArray[i][j] + " ");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}
Output
Element 0: 1 3 5
Element 1: 2 2
In the above example, we have used a nested for loop to iterate through the jagged array. Here,
1. Outer for loop
to access the elements (arrays) of the jagged array
jaggedArray.Length - gives the size of jagged array
2. Inner for loop
to access the elements of the individual array inside the jagged array.
jaggedArray[i].Length - gives the size of elements of the ith array inside the jagged array
Example 2:
C# Jagged Array Example
Let's see a simple example of jagged array in C# which declares, initializes and traverse jagged
arrays.
public class JaggedArrayTest
{
public static void Main()
{
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();
}
}
}
Output:
11 21 56 78
42 61 37 41 59 63
Initialization of Jagged array upon Declaration
Let's see an example to initialize the jagged array while declaration.
int[][] arr = new int[3][]{
new int[] { 11, 21, 56, 78 },
new int[] { 2, 5, 6, 7, 98, 5 },
new int[] { 2, 5 }
};
Example 2
Let's see a simple example of jagged array which initializes the jagged arrays upon declaration.
public class JaggedArrayTest
{
public static void Main()
{
int[][] arr = new int[3][]{
new int[] { 11, 21, 56, 78 },
new int[] { 2, 5, 6, 7, 98, 5 },
new int[] { 2, 5 }
};
// 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();
}
}
}
Output:
11 21 56 78
2 5 6 7 98 5
25
String
In C#, a string is a series of characters that is used to represent text. It can be a character, a
word or a long passage surrounded with the double quotes ". In C#, string is an object
of System.String class that represent sequence of characters.
We can perform many operations on strings such as concatenation, comparision, getting
substring, search, trim, replacement etc. The following are string literals.
Example: String Literals
"S"
"String"
"This is a string."
string vs String
In C#, string is keyword which is an alias for System.String class. That is why string and String
are equivalent. We are free to use any naming convention.
string s1 = "hello";
//creating string using string keyword
String s2 = "welcome"; //creating string using String class
C# provides the String data type to store string literals. A variable of the string type can be
declared and assign string literal, as shown below.
public class Program
{
public static void Main()
{
string ch = "S";
string word = "String";
string text = "This is a string.";
Console.WriteLine(ch);
Console.WriteLine(word);
Console.WriteLine(text);
}
}
Output
S
String
This is a string.
Example 2:
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "hello";
char[] ch = { 'c', 's', 'h', 'a', 'r', 'p' };
string s2 = new string(ch);
Console.WriteLine(s1);
Console.WriteLine(s2);
}
}
Output:
hello
csharp
String Operations
C# string provides various methods to perform different operations on strings. We will look
into some of the commonly used string operations.
1. Get the Length of a string
To find the length of a string, we use the Length property. For example,
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
// create string
string str = "C# Programming";
Console.WriteLine("string: " + str);
// get length of str
int length = str.Length;
Console.WriteLine("Length: "+ length);
Console.ReadLine();
}
}
}
Output
string: C# Programming
Length: 14
In the above example, the Length property calculates the total number of characters in the
string and returns it.
2. Join two strings in C#
We can join two strings in C# using the Concat() method. For example,
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
// create string
string str1 = "C# ";
Console.WriteLine("string str1: " + str1);
// create string
string str2 = "Programming";
Console.WriteLine("string str2: " + str2);
// join two strings
string joinedString = string.Concat(str1, str2);
Console.WriteLine("Joined string: " + joinedString);
Console.ReadLine();
}
}
}
Output
string str1: C#
string str2: Programming
Joined string: C# Programming
In the above example, we have created two strings named str1 and str2. Notice the statement,
string joinedString = string.Concat(str1, str2);
Here, the Concat() method joins str1 and str2 and assigns it to the joinedString variable.
We can also join two strings using the + operator in C#. To learn more, visit C# string Concat.
3. C# compare two strings
In C#, we can make comparisons between two strings using the Equals() method. The Equals()
method checks if two strings are equal or not. For example,
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
// create string
string str1 = "C# Programming";
string str2 = "C# Programming";
string str3 = "Programiz";
// compare str1 and str2
Boolean result1 = str1.Equals(str2);
Console.WriteLine("string str1 and str2 are equal: " + result1);
//compare str1 and str3
Boolean result2 = str1.Equals(str3);
Console.WriteLine("string str1 and str3 are equal: " + result2);
Console.ReadLine();
}
}
}
Output
string str1 and str2 are equal: True
string str1 and str3 are equal: False
In the above example, we have created 3 strings named str1, str2, and str3. Here, we are using
the Equals() method to check if one string is equal to another.
Download