0% found this document useful (0 votes)
15 views

c#

This document provides an introduction to C# and the .NET Framework, covering fundamental concepts such as data types, control flow, and the structure of a simple C# application. It explains the role of the Common Language Runtime (CLR), Microsoft Intermediate Language (MSIL), and Just In Time (JIT) compilation in executing .NET applications. Additionally, it discusses the importance of namespaces, classes, and methods in C# programming, along with practical examples for writing and running a 'Hello World' application.

Uploaded by

sunitha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

c#

This document provides an introduction to C# and the .NET Framework, covering fundamental concepts such as data types, control flow, and the structure of a simple C# application. It explains the role of the Common Language Runtime (CLR), Microsoft Intermediate Language (MSIL), and Just In Time (JIT) compilation in executing .NET applications. Additionally, it discusses the importance of namespaces, classes, and methods in C# programming, along with practical examples for writing and running a 'Hello World' application.

Uploaded by

sunitha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

C# & ASP.

Net
Unit 1
INTRODUCTION:
The C# language
The .Net Architecture and .Net Framework
Understanding the HELLO WORLD Application Code,
Namespaces in C#
The using Keyword
The class Keyword
The Main() Method
Printing on the Console, Comments.

C# BASICS:
Data Types,
Variables & Constants,
Operators in C#,
Arithmetic Operators,
Prefix and Postfix notation,
Assignment Operators,
Relational Operators,
Other Operators,
Operators precedence,
Flow Control and Conditional Statements if-else statement,
switch statement,
Loops in C#,
for loop,
do-while loop,
Array in C#,
foreach Loop.
The C# language
 Anders Hejlsberg is known as the founder of C# language.
 C#(c-sharp) is a programming language developed by Microsoft that runs on the .NET Framework .
 It is an Object Oriented Programming language and has at its core, many similarities to Java, C++ and
VB.
 In fact, C# combines the power and efficiency of C++, the simple and clean OO design of Java and the
language simplification of Visual Basic.
 Like Java, C# also does not allow multiple inheritance or the use of pointers (in safe/managed code),
 C# provide garbage memory collection at runtime, type and memory access checking.
 However, contrary to JAVA, C# maintains the unique useful operations of C++ like operator overloading,
enumerations, pre-processor directives, pointers (in unmanaged/un-safe code), function pointers (in the form
of delegates) and promises to have template support in the next versions.
 Like VB, it also supports the concepts of properties (context sensitive fields).
 In addition to this, C# comes up with some new and exciting features such as reflections, attributes,
marshalling, remoting, threads, streams, data access with ADO.Net and more.

C# is used for:
 Mobile applications
 Desktop applications
 Web applications
 Web services
 Web sites
 Games
 VR
 Database applications
 And much, much more!

Why Use C#?


 It is one of the most popular programming language in the world
 It is easy to learn and simple to use
 It has a huge community support
 C# is an object oriented language which gives a clear structure to programs and allows code to be
reused, lowering development costs
 As C# is close to C, C++ and Java, it makes it easy for programmers to switch to C# or vice versa
The .Net Architecture and .Net Framework
In the .Net Architecture and the .Net Framework there are different important terms and concepts :

The Common Language Runtime (CLR)


The most important concept of the .Net Framework is the existence and functionality of the .Net Common
Language Runtime (CLR), also called .Net Runtime for short.
It is a framework layer that resides above the OS and handles the execution of all the .Net applications. Our
programs don't directly communicate with the OS but go through the CLR.
The Common Language Runtime is responsible for managing the execution of code written in any of the
.NET-supported languages. When an application is run, the CLR loads the required libraries and compiles
the code into machine code that can be executed by the computer’s processor. The CLR also provides a
number of services, such as automatic memory management and security, that help ensure that
applications are reliable and secure.

MSIL (Microsoft Intermediate Language) Code


When we compile our .Net Program using any .Net compliant language (such as C#, VB.Net or C++.Net)
our source code does not get converted into the executable binary code, but to an intermediate code known
as MSIL which is interpreted by the Common Language Runtime. MSIL is operating system and hardware
independent code. Upon program execution, this MSIL (intermediate code) is converted to binary executable
code (native code). Cross language relationships are possible as the MSIL code is similar for each .Net
language.
Just In Time Compilers (JITers)
When our IL compiled code needs to be executed, the CLR invokes the JIT compiler, which compile the IL
code to native executable code (.exe or .dll) that is designed for the specific machine and OS.
JITers in many ways are different from traditional compilers as they compile the IL to native code only
when desired; e.g., when a function is called, the IL of the function's body is converted to native code just in
time. So, the part of code that is not used by that particular run is never converted to native code. If some IL
code is converted to native code, then the next time it's needed, the CLR reuses the same (already compiled)
copy without re-compiling. So, if a program runs for some time (assuming that all or most of the functions
get called), then it won't have any just-in-time performance penalty.
As JITers are aware of the specific processor and OS at runtime, they can optimize the code extremely
efficiently resulting in very robust applications. Also, since a JIT compiler knows the exact current state of
executable code, they can also optimize the code by in-lining small function calls (like replacing body of
small function when its called in a loop, saving the function call time). Although Microsoft stated that C#
and .Net are not competing with languages like C++ in efficiency and speed of execution, JITers can make
your code even faster than C++ code in some cases when the program is run over an extended period of time
(like web-servers).

The Framework Class Library (FCL)


The .Net Framework provides a huge Framework (or Base) Class Library (FCL) for common, usual tasks.
FCL contains thousands of classes to provide 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 would use any other class. You can even apply
inheritance and polymorphism to these classes.

The Common Language Specification (CLS)


Earlier, we used the term '.Net Compliant Language' and stated that all the .Net compliant languages can
make use of CLR and FCL. But what makes a language a '.Net compliant' language? The answer is the
Common Language Specification (CLS).
Microsoft has released a small set of specifications 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 merely needs to meet a small subset of CLS to qualify as a .Net compliant language.
This is the reason why so many languages (procedural and OO) are now running under the .Net umbrella.
CLS basically addresses language design issues and lays down certain standards. For instance, there
shouldn't be any global function declarations, no pointers, no multiple inheritance and things like that.
The important point to note here is that if you keep your code within the CLS boundary, your code is
guaranteed to be usable in any other .Net language.

The Common Type System (CTS)


.Net also defines a Common Type System (CTS). Like CLS, CTS is also a set of standards. CTS defines 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 and 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.

Garbage Collection (GC)


CLR also contains the Garbage Collector (GC), which runs in a low-priority thread and checks for un-
referenced, dynamically allocated memory space. If it finds some data that is no longer referenced by any
variable/reference, it re-claims it and returns it to the OS. The presence of a standard Garbage Collector frees
the programmer from keeping track of dangling data. Ask any C++ programmer how big a relief it is!

The .Net Framework


The .NET Framework is a software development framework developed by Microsoft that provides a
runtime environment and a set of libraries and tools for building and running applications on Windows
operating systems. The framework includes a variety of programming languages, such as C#, F#, and
Visual Basic, and supports a range of application types, including desktop, web, mobile, and gaming
applications
The .Net Framework is the combination of layers of CLR, FCL, Data and XML Classes and our Windows,
Web applications and Web Services. A diagram of the .Net Framework is presented below for better
understanding.
Writing Your First Hello World Console Application in C#
Working Without Visual Studio.Net
using System;
namespace MyHelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
Console.WriteLine("Hello World");
}
}
}
Save this with any file name with the extension ".cs". Example: 'MyFirstApplication.cs' To compile this file,
go to command prompt and write:
csc MyFirstApplication.cs
This will compile your program and create an .exe file (MyFirstApplication.exe) in the same directory and
will report any errors that may occur.

To run your program, type:


MyFirstApplication
This will print Hello World as a result on your console screen.

With Visual Studio.Net


Start Microsoft Visual Studio.Net and select File - New - Project; this will show the open file dialog. Select
Visual C# Project from Project Type and select Console Application from Template. Write
MyHelloWorldApplication in the name text box below and click OK

Remove the documentation comments (lines starting with ///), change the name of class from Class1 to
HelloWorld and write
Console.WriteLine("Hello World"); in place of //TODO: Add code....
to make the picture look like
using System;
namespace MyHelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
Console.WriteLine("Hello World");
}
}
}
Now to compile and execute your application, select Debug - Start Without Debugging or press Ctrl+F5. This
will open a new Console Window with Hello World written in it. Once you press any key, the window will
close, terminating the program.

Understanding the Hello World Application Code:


The first line of our program (using System;) appears in virtually all the C# programs.
It gives us access to the core functionality of our computer system.

Namespaces in C#
A Namespace is simply a logical collection of related classes in C#.
We bundle our related classes (like those related with database activity) in some named collection calling it a
namespace (e.g., Data Activity).
As C# does not allow two classes with the same name to be used in a program, the sole purpose of using
namespaces is to prevent name conflicts.
This may happen when you have a large number of classes, as is the case in the Framework Class Library
(FCL).
It is very much possible that our Connection Class in DataActivity conflicts with the Connection Class of
Interne tActivity.
To avoid this, these classes are made part of their respective namespace. So the fully qualified name of these
classes will be Data Activity. Connection and Internet Activity. Connection, hence resolving any ambiguity
for the compiler.
So, in the second line of our program we are declaring that the following classes (within { } block) are part
of MyHelloWorldApplication namespace.
namespace MyHelloWorldApplication
{
...
}
Example
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Namespace!");
}
}
}

The C# namespaces have NO physical mapping as is the case in Java. Classes with same namespace can be
in different folders. The C# concept of mapping is similar to packages in Java and namespaces in standard
C++. The namespace may contain classes, events, exceptions, delegates and even other namespaces called
'Internal namespace'.
These internal namespaces can be defined like this:
namespace Parent
{
namespace Child
{
...
}
}

The using Keyword


The first line of our program was:
using System;
The using keyword above allows us to use the classes in the following 'System' namespace. By doing this, we
can now access all the classes defined in the System namespace like we are able to access the Console class
in our Main method later. One point to remember here is using allows you to access the classes in the
referenced namespace only and not in its internal/child namespaces. Hence we might need to write
using System.Collections;
in order to access the classes defined in Collection namespace which is a sub/internal namespace of System
namespace.
Example
using System;
using First;
using Second;
namespace First {
public class Hello
{
public void sayHello() { Console.WriteLine("Hello Namespace"); }
}
}
namespace Second
{
public class Welcome
{
public void sayWelcome() { Console.WriteLine("Welcome Namespace"); }
}
}
public class TestNamespace
{
public static void Main()
{
Hello h1 = new Hello();
Welcome w1 = new Welcome();
h1.sayHello();
w1.sayWelcome();
}
}

The class Keyword


All of our C# programs contain at least one class.
The Main() method resides in one of these classes.
Classes are a combination of data (fields) and functions (methods) that can be performed on this data in
order to achieve the solution to our problem.
Classes in C# are defined using the class keyword followed by the name of class.
Example 1
using System;
public class Student
{
int id;//field or data member
String name;//field or data member
public static void Main(string[] args)
{
Student s1 = new Student();//creating an object of Student
s1.id = 101;
s1.name = "Sonoo Jaiswal";
Console.WriteLine(s1.id);
Console.WriteLine(s1.name);
}
}
Example 2:
using System;
public class Student
{
public int id;
public String name;
}
class TestStudent{
public static void Main(string[] args)
{
Student s1 = new Student();
s1.id = 101;
s1.name = "Sonoo Jaiswal";
Console.WriteLine(s1.id);
Console.WriteLine(s1.name);
}
}
The Main() Method
In the next line we defined the Main() method of our program:
static void Main(string[] args)
This is the standard signature of the Main method in C#.
The Main method is the entry point of our program, i.e., our C# program starts its execution from the first line
of Main method and terminates with the termination of Main method.
The Main method is designated as static as it will be called by the common language runtime(CLR)
The method is also declared void as it does not return anything.
Main is the (standard) name of this method, while string [] args is the list of parameters that can be passed to
main while executing the program from command line.
We can have multiple Main() methods in C# program. But, you have toexplicitly identify which Main method
is the entry point at the run-time. C++ and Java Programmers, take note that Main starts with capital 'M' and
the return type is void.

Printing on the Console


Our next line prints Hello World on the Console screen:
In C#, to print the data on the console output screen the following method are used
Console.Write() and Console.WriteLine() method.
Console is a predefined class of System namespace.
While Write() and WriteLine() both are the Console Class methods.
The only difference between the Write() and WriteLine() is that Console.Write is used to print
data without printing the new line, while Console.WriteLine is used to print data along with printing the
new line.

Example 1: Example of Console.Write() in C#.


using System;
public class GFG{
static void Main(string[] args)
{
// use of Write() method
Console.Write("Hello");
Console.Write(“World");
}
}
Example 2: Example of Console.WriteLine() in C#.
using System;
public class GFG{
static void Main(string[] args)
{
// use of WriteLine() method
Console.WriteLine("Hello World");
}
}
Here we called WriteLine(), a static method of the Console class defined in the System namespace. This
method takes a string (enclosed in double quotes) as its parameter and prints it on the Console window.

C#, like other Object Oriented languages, uses the dot (.) operator to access the member variables (fields)
and methods of a class. Also, braces () are used to identify methods in the code and string literals are enclosed
in double quotation marks ("). Lastly, each statement in C# (like C, C++ and Java) ends with a semicolon (;),
also called the statement terminator.
Comments
Comments are the programmer's text to explain the code, are ignored by the compiler and are not included in
the final executable code. C# uses syntax for comments that is similar to Java and C++. The text following
double slash marks (// any comment) are line comments. The comment ends with the end of the line:
Example
// This is my main method of programstatic void Main()
{
...
}
C# also supports the comment block. In this case, the whole block is ignored by the compiler. The start of the
block is declared by slash-asterisk (/*) and ends with asterisk-slash mark (*/):
static void Main()
{
/* These lines of text
will be ignored by the compiler */
}
C# BASICS
Data Types
There are two kinds of data types in C#.

1. Value Types (implicit data types, structs and enumeration)


2. Reference Types (objects, delegates)

Value types are passed to methods by passing an exact copy


Reference types are passed to methods by passing only their reference (handle).

Implicit data types are defined in the language core by the language vendor
explicit data types are types that are made by using or composing implicit data types.

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.

C# type .Net type Size in Description


bytes
Integral Types
byte Byte 1 May contain integers from 0-255

sbyte SByte 1 Signed byte from -128 to 127

short Int16 2 Ranges from -32,768 to 32,767

ushort UInt16 2 Unsigned, ranges from 0 to 65,535

int (default) Int32 4 Ranges from -2,147,483,648 to 2,147,483,647

uint UInt32 4 Unsigned, ranges from 0 to 4,294,967,295

long Int64 8 Ranges from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807
ulong UInt64 8 Unsigned, ranges from 0 to
18,446,744,073,709,551,615
Floating Point Types
float Single 4 Ranges from ±1.5 × 10-45 to ±3.4 × 1038 with 7
digits
precision. Requires the suffix 'f' or 'F'
double Double 8 Ranges from ±5.0 × 10-324 to ±1.7 × 10308 with
(default) 15-16 digits
Precision
Other Types
bool Boolean 1 Contains either true or false

char Char 2 Contains any single Unicode character enclosed


in single
quotation mark such as 'c'
decimal Decimal 12 Ranges from 1.0 × 10-28 to 7.9 × 1028 with 28-29
digits
precision. Requires the suffix 'm' or 'M'

Implicit data types are represented in language using keywords, so each of the above is a keyword in C#
(Keyword are the words defined by the language and can not be used as identifiers).
It is worth noting that string is also an implicit data type in C#, so string is a keyword in C#.
The last point about implicit data types is that they are value types and thus stored on the stack, while user
defined types or referenced types are stored using the heap.
A stack is a data structure that store items in a first in first out (FIFO) fashion. It is an area of memory
supported by the processor and its size is determined at the compile time.
A heap consists of memory available to the program at runtime.
Reference types are allocated using memory available from the heap dynamically (during the execution of
program). The garbage collector searches for non-referenced data in heap during the execution of program
and returns that space to Operating System.

Reference Data Type


The reference data types do not contain the actual data stored in a variable, but they contain a reference to
the variables.
If the data is changed by one of the variables, the other variable automatically reflects this change in value.
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.
Variables and constants
variables
During the execution of a program, data is temporarily stored in memory. A variable is the name given to a
memory location holding a particular type of data. So, each variable has associated with it a data type and a
value. In C#, variables are declared as:
Syntax:
datatype variableName = value;
Ex: int i;
The above line will reserve an area of 4 bytes in memory to store an integer type values, which will be
referred to in the rest of program by the identifier 'i'. You can initialize the variable as you declare it and can
also declare/initialize multiple variables of the same type in a single statement.
Ex:
bool a = True;
float b = 88.6, c = 43.9;
char digit = ‘7’;

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.

Naming Conventions for variables and methods


Microsoft suggests using Camel Notation (first letter in lowercase) for variables and Pascal Notation (first
letter inuppercase) for methods.
Each word after the first word in the name of both variables and methods should start with a capital letter. For
example, variable names following Camel notation could be:
salary
myMathsMarks
totalSalary
isPaid
typical names of method following Pascal Notation are
GetTotal()
Start()
WriteLine()
LastIndexOf()
Constant Variables or Symbols
Constants are variables whose values, once defined, can not be changed by the program. Constant variables
are declared using the const keyword, like:
const double PI = 3.142;
Constant variables must be initialized as they are declared. It is a syntax error to write:
const int MARKS;
It is conventional to use capital letters when naming constant variables.

Operators in C#
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operators
o Unary Operators
o Ternary Operators

In C#, 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.

Arithmetic Operators
Several common arithmetic operators are allowed in C#.
Operand Description
+ Add
- Subtract
* Multiply
/ Divide
% Remainder or modulo
++ Increment by 1
-- Decrement by 1
Example
using System;
namespace Arithmetic
{
class GFG
{
// Main Function
static void Main(string[] args)
{
int result;
int x = 10, y = 5;

// Addition
result = (x + y);
Console.WriteLine("Addition Operator: " + result);

// Subtraction
result = (x - y);
Console.WriteLine("Subtraction Operator: " + result);

// Multiplication
result = (x * y);
Console.WriteLine("Multiplication Operator: "+ result);

// Division
result = (x / y);
Console.WriteLine("Division Operator: " + result);

// Modulo
result = (x % y);
Console.WriteLine("Modulo Operator: " + result);
}
}
}
Increment: The ‘++’ operator is used to increment the value of an integer. When placed before the
variable name (also called pre-increment operator), its value is incremented instantly. For example, ++x.
And when it is placed after the variable name (also called post-increment operator), its value is
preserved temporarily until the execution of this statement and it gets updated before the execution of the
next statement. For example, x++.
Decrement: The ‘- -‘ operator is used to decrement the value of an integer. When placed before the
variable name (also called pre-decrement operator), its value is decremented instantly. For example, --x.
And when it is placed after the variable name (also called post-decrement operator), its value is
preserved temporarily until the execution of this statement and it gets updated before the execution of the
next statement. For example, x--.
Example
using System;
namespace Arithmetic {
class GFG {
// Main Function
static void Main(string[] args)
{
int a = 10, res;
// post-increment example:
// res is assigned 10 only,
// a is not updated yet
res = a++;

//a becomes 11 now


Console.WriteLine("a is {0} and res is {1}", a, res);

// post-decrement example:
// res is assigned 11 only, a is not updated yet
res = a--;

//a becomes 10 now


Console.WriteLine("a is {0} and res is {1}", a, res);

// pre-increment example:
// res is assigned 11 now since a
// is updated here itself
res = ++a;
// a and res have same values = 11
Console.WriteLine("a is {0} and res is {1}", a, res);

// pre-decrement example:
// res is assigned 10 only since
// a is updated here itself
res = --a;

// a and res have same values = 10


Console.WriteLine("a is {0} and res is {1}",a, res);
}
}
}

Prefix and Postfix notation


Both the ++ and -- operators can be used as prefix or postfix operators. In prefix form:
num1 = 3;
num2 = ++num1; // num1 = 4, num2 = 4
The compiler will first increment num1 by 1 and then will assign it to num2. While in postfix form:
num2 = num1++; // num1 = 4, num2 = 3
The compiler will first assign num1 to num2 and then increment num1 by 1.

Assignment Operators
Assignment operators are used to assign values to variables. Common assignment operators in C# are:
Operand Description
= Simple assignment
+= Additive assignment
-= Subtractive assignment
*= Multiplicative
assignment
/= Division assignment
%= Modulo assignment

The equals (=) operator is used to assign a value to an object.


bool isPaid = false;
assigns the value 'false' to the isPaid variable of Boolean type. The left hand and right hand side of the equal or
any other assignment operator must be compatible, otherwise the compiler will complain about a syntax
error.
Example
using System;
namespace Assignment {
class GFG {
// Main Function
static void Main(string[] args)
{
// initialize variable x
// using Simple Assignment
// Operator "="
int x = 15;

// it means x = x + 10
x += 10;
Console.WriteLine("Add Assignment Operator: " + x);

// initialize variable x again


x = 20;

// it means x = x - 5
x -= 5;
Console.WriteLine("Subtract Assignment Operator: " + x);

// initialize variable x again


x = 15;

// it means x = x * 5
x *= 5;
Console.WriteLine("Multiply Assignment Operator: " + x);

// initialize variable x again


x = 25;

// it means x = x / 5
x /= 5;
Console.WriteLine("Division Assignment Operator: " + x);

// initialize variable x again


x = 25;

// it means x = x % 5
x %= 5;
Console.WriteLine("Modulo Assignment Operator: " + x);

// initialize variable x again


x = 8;

// it means x = x << 2
x <<= 2;
Console.WriteLine("Left Shift Assignment Operator: " + x);

// initialize variable x again


x = 8;

// it means x = x >> 2
x >>= 2;
Console.WriteLine("Right Shift Assignment Operator: " + x);

// initialize variable x again


x = 12;

// it means x = x >> 4
x &= 4;
Console.WriteLine("Bitwise AND Assignment Operator: " + x);

// initialize variable x again


x = 12;

// it means x = x >> 4
x ^= 4;
Console.WriteLine("Bitwise Exclusive OR Assignment Operator: " + x);

// initialize variable x again


x = 12;

// it means x = x >> 4
x |= 4;
Console.WriteLine("Bitwise Inclusive OR Assignment Operator: " + x);
}
}
}
Sometimes casting is used for type conversion, e.g., to convert and store a value in a variable of type double
to a variable of type int, we need to apply an integer cast.
double doubleValue = 4.67;
// intValue will be equal to 4
int intValue = (int) doubleValue;
Of course, when casting there is always a danger of some loss of precision; in the case above, we only got the
4 of the original 4.67. Sometimes, the casting may result in strange values:
int intValue = 32800;
short shortvalue = (short) intValue;
//short value would be equal to -32736
Variables of type short can only take values ranging from -32768 to 32767, so the cast above can not assign
32800 to shortValue. Hence shortValue took the last 16 bits (as a short consists of 16 bits) of the integer
32800, which gives the value -32736 (since bit 16, which represents the value 32768 in an int, now represents
-32768). If you try to cast incompatible types like:
bool isPaid = false;
int intValue = (int) isPaid;
It won't get compiled and the compiler will generate a syntax error.

Relational Operators
Relational operators are used for comparison purposes in conditional statements. Common relational
operators in C# are:
Operand Description
== Equality check
!= Un-equality check
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Relational operators always result in a Boolean statement; either true or false. For example if we have two
variables
int num1 = 5, num2 = 6;
num1 == num2 // false
num1 != num2 // true
num1 > num2 // false
num1 < num2 // true
num1 <= num2 // true
num1 >= num2 // false
Only compatible data types can be compared. It is invalid to compare a bool with an int, so if you have

int i = 1;

bool b = true;

you cannot compare i and b for equality (i==b). Trying to do so will result in a syntax error.
Example
using System;
namespace Relational {
class GFG {
// Main Function
static void Main(string[] args)
{
bool result;
int x = 5, y = 10;

// Equal to Operator
result = (x == y);
Console.WriteLine("Equal to Operator: " + result);

// Greater than Operator


result = (x > y);
Console.WriteLine("Greater than Operator: " + result);

// Less than Operator


result = (x < y);
Console.WriteLine("Less than Operator: " + result);

// Greater than Equal to Operator


result = (x >= y);
Console.WriteLine("Greater than or Equal to: "+ result);

// Less than Equal to Operator


result = (x <= y);
Console.WriteLine("Lesser than or Equal to: "+ result);

// Not Equal To Operator


result = (x != y);
Console.WriteLine("Not Equal to Operator: " + result);
}
}
}

Logical and Bitwise Operators


These operators are used for logical and bitwise calculations. Common logical and bitwise operators in C#
are:
Operand Description
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Left shift
>> Right shift
! Bitwise NOT
&& “Logical” or “short circuit”
AND
|| “Logical” or “short circuit”
OR

The operators &, | and ^ are rarely used in usual programming practice. The NOT operator is used to negate
a Boolean or bitwise expression like:
bool b = false;
bool bb = !b;
// bb would be true
Logical Operators && and || are used to combine comparisons like
int i=6, j=12;
bool firstVar = i>3 && j<10;
// firstVar would be false bool secondVar = i>3 || j<10;
// secondVar would be true
In the first comparison: i>3 && j<10 will result in true only if both the conditions i>3 and j<10 result in
true. In the second comparison: i>3 || j<10 will result in true if any of the conditions i>3 and j<10 result in
true. You can, of course, use both && and || in single statement like:
bool firstVar = (i>3 && j<10) || (i<7 && j>10) // firstVar would be true
In the above statement we used parenthesis to group our conditional expressions and to avoid any ambiguity.
Example : logical operator
using System;
namespace Logical {
class GFG {
// Main Function
static void Main(string[] args)
{
bool a = true,b = false, result;

// AND operator
result = a && b;
Console.WriteLine("AND Operator: " + result);

// OR operator
result = a || b;
Console.WriteLine("OR Operator: " + result);

// NOT operator
result = !a;
Console.WriteLine("NOT Operator: " + result);
}
}
}

Example: bitwise operator


using System;
namespace Bitwise {
class GFG {
// 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);
}
}
}

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;
using System;
namespace Conditional {
class GFG {
// 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);

// To find which value is greater


// Using Conditional Operator
result = x < y ? x : y;

// To display the result


Console.WriteLine("Result: " + result);
}
}
}

Other Operators
There are some other operators present in C#. A short description of these is given below:

Operand Description
. Member access for objects
[] Index operator used in arrays and
collections
() Cast operator
?: Ternary operator

Operator Precedence
All operators are not treated equally. There is a concept of "operator precedence" in C#. For example:

int i = 2 + 3 * 6;

// i would be 20 not 30

3 will be multiplied by 6 first then the result will be added to 2. This is because the multiplication operator *
has precedence over the addition operator +. For a complete table of operator precedence, consult MSDN or
the .Net framework documentation.
Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right


Control statements
Flow Control And Conditional StatementsThe
o if statement
o if-else statement
o nested if statement
o if-else-if ladder

C# IF Statement
The C# if statement tests the condition. It is executed if condition is true.
Syntax:
if(condition){
//code to be executed
}

Example
using System;
public class IfExample
{
public static void Main(string[] args)
{
int num = 10;
if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}
}
}

C# IF-else Statement
The C# if-else statement also tests the condition. It executes the if block if condition is true otherwise else
block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Example
using System;
public class IfExample
{
public static void Main(string[] args)
{
int num = 11;
if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}
else
{
Console.WriteLine("It is odd number");
}
}
}
nested if statement
Since if...else is also a statement, you can use it under other if...else statement (nesting), like
if(i>5)
{
if(i==6)
{
Console.WriteLine("Ok, 6 is close to 5.");
}
else // line 7
{
Console.WriteLine("Oops! I'm older than 5 but not 6!");
}
Console.WriteLine("Thank God, I finally became older than 5.");
}
else // line 13
{
Console.WriteLine("Missed...When will I become 5 or close to 5?");
}
C# IF-else-if ladder Statement
The C# if-else-if ladder statement executes one condition from multiple statements.
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
using System;
public class IfExample
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a number to check grade:");
int num = Convert.ToInt32(Console.ReadLine());

if (num <0 || num >100)


{
Console.WriteLine("wrong number");
}
else if(num >= 0 && num < 50){
Console.WriteLine("Fail");
}
else if (num >= 50 && num < 60)
{
Console.WriteLine("D Grade");
}
else if (num >= 60 && num < 70)
{
Console.WriteLine("C Grade");
}
else if (num >= 70 && num < 80)
{
Console.WriteLine("B Grade");
}
else if (num >= 80 && num < 90)
{
Console.WriteLine("A Grade");
}
else if (num >= 90 && num <= 100)
{
Console.WriteLine("A+ Grade");
}
}
}

The switch...case statement


The C# switch statement executes one statement from multiple conditions. It is like if-else-if ladder
statement in C#.
Syntax:
switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
//code to be executed if all cases are not matched;
break;
}
Example
using System;
public class SwitchExample
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a number:");
int num = Convert.ToInt32(Console.ReadLine());

switch (num)
{
case 10: Console.WriteLine("It is 10"); break;
case 20: Console.WriteLine("It is 20"); break;
case 30: Console.WriteLine("It is 30"); break;
default: Console.WriteLine("Not 10, 20 or 30"); break;
}
}
}

There are some important points to remember when using the switch...case statement in C#:

 You can use either integers (enumeration) or strings in a switch statement


 The expression following case must be constant. It is illegal to use a variable after case:
case i: // incorrect, syntax error

case "Pakistan":
continent ="Asia";
Console.WriteLine("Pakistan is an Asian Country");
break;
default:
continent = "Un-recognized";
Console.WriteLine
("Un-recognized country discovered");
break;
 The end of the case and default statements is marked with break (or goto) statement. We don't use {}
brackets to mark the block in switch...case as we usually do in C#
 C# does not allow fall-through. So, you can't leave case or default without break statement (as you can in
Java or C/C++). The compiler will detect and complain about the use of fall-through in the switch...case
statement.
 The break statement transfers the execution control out of the current block.
 Statements under default will be executed if and only if all the case checks fail.
 It is not necessary to place default at the end of switch...case statement. You can even place the default
block before the first case or in between cases; default will work the same regardless of its position.
However, making default the last block is conventional and highly recommended. Of course, you can't
have more than one default block in a single switch...case.

Loops In C#
Loops are used for iteration purposes, i.e., doing a task multiple times (usually until a termination condition is
met)
Loops are mainly divided into two categories:
Entry Controlled Loops: The loops in which condition to be tested is present in beginning of loop body
are known as Entry Controlled Loops. while loop and for loop are entry controlled loops.
The for Loop
for loops are preferred when the number of times loop statements are to be executed is known beforehand.
The loop variable initialization, condition to be tested, and increment/decrement of the loop variable is
done in one line in for loop thereby providing a shorter, easy to debug structure of looping.
The C# for loop is same as C/C++. We can initialize variable, check condition and increment/decrement
value.
Syntax:
for(initialization; condition; incr/decr){
//code to be executed
}
Example
using System;
public class ForExample
{
public static void Main(string[] args)
{
for(int i=1;i<=10;i++){
Console.WriteLine(i);
}
}
}
C# Nested For Loop
In C#, we can use for loop inside another for loop, it is known as nested for loop. The inner loop is executed
fully when outer loop is executed one time. So if outer loop and inner loop are executed 3 times, inner loop
will be executed 3 times for each outer loop i.e. total 9 times.
using System;
public class ForExample
{
public static void Main(string[] args)
{
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
Console.WriteLine(i+" "+j);
}
}
}
}

If you don't use the {} brackets, the statement immediate following for() will be treated as the iteration
statement. The example below is identical to the one given above:
for(int i=1; i<=10; i++)
Console.WriteLine("In the loop, value of i is {0}.", i);

C# While Loop
In C#, while loop is used to iterate a part of the program several times. If the number of iteration is not fixed,
it is recommended to use while loop than for 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(condition){
//code to be executed
}
using System;
public class WhileExample
{
public static void Main(string[] args)
{
int i=1;
while(i<=10)
{
Console.WriteLine(i);
i++;
}
}
}

C# Nested While Loop Example:


In C#, we can use while loop inside another while loop, it is known as nested while loop. The nested while
loop is executed fully when outer loop is executed once.
using System;
public class WhileExample
{
public static void Main(string[] args)
{
int i=1;
while(i<=3)
{
int j = 1;
while (j <= 3)
{
Console.WriteLine(i+" "+j);
j++;
}
i++;
}
}
}

Exit Controlled Loops: The loops in which the testing condition is present at the end of loop body are
termed as Exit Controlled Loops. do-while is an exit controlled loop. Note: In Exit Controlled Loops,
loop body will be evaluated for at-least one time as the testing condition is present at the end of loop body
do-while loop
The C# do-while loop is used to iterate a part of the program several times. If the number of iteration is not
fixed and you must have to execute the loop at least once, it is recommended to use do-while loop.
do while loop is similar to while loop with the only difference that it checks the condition after executing
the statements, i.e it will execute the loop body one time for sure because it checks the condition after
executing the statements.
There is a semicolon ; after the while statement.
Syntax:
do{
//code to be executed
}while(condition);

Example
using System;
public class DoWhileExample
{
public static void Main(string[] args)
{
int i = 1;

do{
Console.WriteLine(i);
i++;
} while (i <= 10) ;

}
}

C# Nested do-while Loop


In C#, if you use do-while loop inside another do-while loop, it is known as nested do-while loop. The
nested do-while loop is executed fully for each outer do-while loop.
using System;
public class DoWhileExample
{
public static void Main(string[] args)
{
int i=1;

do{
int j = 1;
do{
Console.WriteLine(i+" "+j);
j++;
} while (j <= 3) ;
i++;
} while (i <= 3) ;
}
}

Arrays in C#
Array Declaration
An Array is a collection of values of a similar data type.
Technically, C# arrays are a reference type.
Each array in C# is an object and is inherited from the System.Array class.
Arrays are declared as:
<data type> [] <identifier> = new <data type>[<size of array>];
int [] integers = new int[10];
The size of an array is fixed and must be defined before using it. However, you can use variables to define the
size of the array:
int size = 10;
int [] integers = new int[size];
It is also possible to define arrays using the values it will hold by enclosing values in curly brackets and
separating individual values with a comma:
int [] integers = {1, 2, 3, 4, 5};
This will create an array of size 5, whose successive values will be 1, 2, 3, 4 and 5.
C# Array Types
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
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[2] = 20;
arr[4] = 30;

//traversing array
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
}
}

C# Multidimensional Arrays
The multidimensional array is also known as rectangular arrays in C#. It can be two dimensional or three
dimensional. The data is stored in tabular form (row * column) which is also known as matrix.
To create multidimensional array, we need to use comma inside the square brackets. For example:
int[,] arr=new int[3,3];//declaration of 2D array
int[,,] arr=new int[3,3,3];//declaration of 3D array

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

C# Multidimensional Array Example: Declaration and initialization at same time


int[,] arr = new int[3,3]= { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
We can omit the array size.
int[,] arr = new int[,]{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
We can omit the new operator also.
int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
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
}
}
}

C# Jagged Arrays
In C#, jagged array is also known as "array of arrays" because its elements are arrays. The element size of
jagged array can be different.
Declaration of Jagged array
int[][] arr = new int[2][];
Initialization of Jagged array
Let's see an example to initialize jagged array. The size of elements can be different.
arr[0] = new int[4];
arr[1] = new int[6];
Initialization and filling elements in Jagged array
arr[0] = new int[4] { 11, 21, 56, 78 };
arr[1] = new int[6] { 42, 61, 37, 41, 59, 63 };
Example
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();
}
}
}

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 }
};
Accessing the values stored in an array
To access the values in an Array, we use the indexing operator [int index]. We do this by passing an int to
indicate which particular index value we wish to access. It's important to note that index values in C# start
from 0. So if an array contains 5 elements, the first element would be at index 0, the second at index 1 and the
last (fifth) at index 4. The following lines demonstrate how to access the 3rd element of an array:
int [] intArray = {5, 10, 15, 20};
int j = intArray[2];

foreach Loop
The foreach loop is used to iterate over the elements of the collection. The collection may be an array
or a list. It executes for each element present in the array.
 It is necessary to enclose the statements of foreach loop in curly braces {}.
 Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type
as the base type of the array, followed by a colon, which is then followed by the array name.
 In the loop body, you can use the loop variable you created rather than using an indexed array element.

There is another type of loop that is very simple and useful to iterate through arrays and collections. This is
the foreach loop. The basic structure of a foreach loop is
Syntax
foreach(<type of elements in collection> <identifier> in <array or collection>)
{
// statements to be executed
}
Example
using System;

class GFG {

// Main Method
static public void Main()
{

Console.WriteLine("Print array:");

// creating an array
int[] a_array = new int[] { 1, 2, 3, 4, 5, 6, 7 };

// foreach loop begin


// it will run till the
// last element of the array
foreach(int items in a_array)
{
Console.WriteLine(items);
}
}
}
Important points to note here:

 The variable used to hold the individual elements of array in each iteration (items in the above example) is
read only. You can't change the elements in the array through it. This means that foreach will only allow you
to iterate through the array or collection and not to change the contents of it. If you wish to perform some
work on the array to change the individual elements, you should use a for loop.
 foreach can be used to iterate through arrays or collections. By a collection, we mean any class, struct or
interface that implements the IEnumerable interface
 The string class is also a collection of characters (implements IEnumerable interface and returns char value
in Current property). The following code example demonstrates this and prints all the characters in the
string.

static void Main()


{
string name = "Faraz Rasheed";foreach(char ch in name)
{
Console.WriteLine(ch);
}
}

You might also like