0% found this document useful (0 votes)
32 views309 pages

.NET Programming Course Overview

Uploaded by

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

.NET Programming Course Overview

Uploaded by

Jeya lakshmi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

ARULMIGU KALASALINGAM COLLEGE OF ARTS AND SCIENCE

Anand Nagar, Krishnankoil - 626126.


[Link].04563 – 289323. Email: akcas_98@[Link]
(Affiliate to Madurai Kamaraj University )

DEPARTMENT OF INFORMATION TECHNOLOGY

.NET PROGRAMMING

Prepared by,
[Link]., [Link]., [Link].,
DEPARTMENT OF INFORMATION
TECHNOLOGY, AKCAS
.NET PROGRAMMING
Unit I
The Creation of C#: C# Relates to the .Net Framework - Common Language
Runtime - Managed vs unmanaged code - An Overview of C#: Object-Oriented
Programming - First Simple Program-Handling Syntax errors - Using code
blocks-semicolon, positioning and Indentation-The C# Keywords-Identifiers-
The .Net Framework Class Library-Data Types, Literals and Variables-
Operators.
Unit II
Program Control Statements: If Statement- switch Statement-For Loop- While
loop do-while loop- foreach loop-using break to exit a loop using continue-
goto- Introducing Classes and objects: Class Fundamentals- objects creation-
Methods-constructors-Garbage Collection and Destructors-Exception Handling.
Unit III
Arrays and Strings: Arrays-Multidimensional Arrays-Jagged Arrays- for each
loop Strings- Methods and classes: Method overloading- Main Method-
Recursion-static Classes Delegates, Events and Lambda Expressions: Delegates
-Lambda Expressions-LINQ
Unit IV
Developing [Link] Applications: Visual Studio: Creating Websites- The
Anatomy of a Web Form – Web Form Fundamentals: Converting HTML Page
to an [Link] Page – Page Class – Web Controls. State Management: View
State - Transferring Information between Pages – Cookies – Session State –
Application State.
Unit V
Validation Controls – AdRotator Control. Working with Data: [Link]
Fundamentals:– Direct Data Access – Disconnected Data Access - Data
Binding: Data Binding with [Link] –Data Source Controls - The Data
Controls: The Grid View – Formatting the GridView – Selecting GridView
Row – Editing, Sorting and Paging the GridView Generating Crystal Reports.
Textbooks
1. Herbert Schildt (2010), C# 4.0 The Complete Reference, Tata McGraw-Hill
Pvt Ltd
2. Mathew MacDonald, (2010), Beginning [Link] 4 in C# 2010, Second
Edition, Apress.
UNIT I

UNIT I
THE CREATION OF C#
1.1 C# Relates to the .Net Framework
 Microsoft created the language C#, known as C Sharp, in the year 2000.
 C# is an object-oriented programming language that is used in .NET
Framework.
 C# is designed to be simple, efficient, and versatile, and is often used to
build a wide range of desktop, web, and mobile applications.
 The .NET Framework is a software development framework 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, including C#,
and supports a range of application types, including desktop, web,
mobile, and gaming applications.
The .NET Framework’s basic architecture consists of two key elements:
1. Common Language Runtime (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.
2. .NET Framework Class Library (FCL): The .NET Framework Class
Library provides a large set of pre-built functions and classes that can be
used to create a wide range of applications. The library includes a variety
of namespaces that provide access to classes that provide features such as
file I/O, networking, database access, and graphical user interface (GUI)
design. The library also includes a number of development tools, such as
the Visual Studio integrated development environment (IDE), which
provides a powerful set of tools for developing and debugging .NET
applications.
.NET is a software framework which is designed and developed by Microsoft. The
first version of .Net framework was 1.0 which came in the year 2002. In easy
words, it is a virtual machine for compiling and executing programs written in
different languages like C#, [Link], etc. It is used to develop Form- based
applications, Web-based applications, and Web services. There is a
.NET PROGRAMMING Page 1
UNIT I

variety of programming languages available on the .Net platform, [Link]


and C# being the most common ones are. It is used to build applications for
Windows, phone, web, etc. It provides a lot of functionalities and also supports
industry standards.
1.2 COMMON LANGUAGE RUNTIME
.NET CLR is an execution engine and is the integral part of .NET Framework
that is responsible for executing and managing the lifecycle of an executable.
CLR stands for Common Language Runtime and also knows as the runtime.
CLR’s responsibility is to mange any code written in .NET languages such as
C#, [Link], or F#.
The code that targets CLR is also knows as the “managed
code”. CLR is the common runtime for all .NET languages.
Each language that supports .NET must follow a common standard and must
emit and attach metadata with every binary, or portable executable (PE).
The metadata includes the types, objects, members, and references. The
runtime uses metadata to understand types, load types, allocate memory and
manages memory lifetime, resolve method invocations, generate native code,
enforce security, and set run-time context boundaries.
Here is a list of CLR functions:
 Automatic memory management with Garbage collection (GC) including
releasing unused objects, managing pool of threads, and reserve
locations.
 Cross language interoperability
 Structured exception handling
 Code access security
 Thread execution, thread pooling, and context
 Debugging
 Verification and compliance
The following diagram shows the execution model of CLR.

.NET PROGRAMMING Page 2


UNIT I

Here is a more detailed article on .NET CLR: What is Common Language


Runtime
Common Language Infrastructure (CLI)
The CLR code uses a common type system (CTS) that is based on a common
language infrastructure (CLI).
CLI is a specification developed by Microsoft that describes the executable
code and runtime environment. In simple terms this allows us to use various
high-level programming languages on various machines without rewriting the
code.
CLI is divided into four main components.
i) Common type system (CTS)
CTS defines some basic data types and every language that is designed for use
with .NET framework should be able to match its data types to these defined
basic data types. So when various languages are designed following CTS, they
will be able to communicate with each other and this is nothing but cross-
language interoperability or communication.
ii) Common Language Specification (CLS)

.NET PROGRAMMING Page 3


UNIT I

CLS is a set of specifications that must be met by every language to be


considered as .NET compliant. It is a subset of CTS types and a set of rules.
Example: Elimination of pointers and multiple inheritance.
iii) Metadata
Metadata gives information about all the classes and the class members defined
in the assembly. You will learn later what an assembly means.
iv) Virtual Execution System (VES)
VES loads and runs the programs that are compatible with the CLI using
metadata. To make it clear, CLI is a set of specifications for a virtual operating
system that is nothing but a Common Language Runtime (CLR)
1.3 Managed vs unmanaged code
1.3.1 Managed Code
Managed code is the type of code that is executed by the Common Language
Runtime (CLR), which is a component of the .NET. The CLR provides a set of
services and features that make the development of managed code easier and
more efficient.
Characteristics of Managed Code
Some of the main characteristics of managed code.
 Memory management: The CLR handles the allocation and deallocation
of memory for managed code, so the developer does not have to worry
about manual memory management. This reduces the risk of memory
leaks, fragmentation, and corruption.
 Garbage collection: The CLR periodically performs garbage collection,
which is a process of reclaiming the memory that is no longer used by
managed objects. This frees up the memory for other purposes and
improves the performance of the application.
 Safety and security: The CLR enforces strict rules and checks on
managed code to ensure its safety and security. For example, it verifies
the type and format of the code before executing it, prevents unauthorized
access to memory locations, and protects against malicious or harmful
code.
Use Managed Code

.NET PROGRAMMING Page 4


UNIT I

Managed code is preferable in most scenarios where the developer wants to


create applications.
 Cross-platform: Managed code can run on any platform that supports the
.NET, such as Windows, Linux, or Mac OS. This can increase the
portability and compatibility of the application across different devices
and environments.
 High-level: Managed code can use high-level features and abstractions
provided by the .NET, such as LINQ, generics, delegates, or lambda
expressions. These features can simplify the development process and
enhance the readability and maintainability of the code.
 Secure: Managed code can benefit from the security features provided by
the CLR, such as code access security, role-based security, and
cryptography. These features can protect the application from potential
threats or attacks and ensure its safety and reliability.
Examples of Managed Code Applications
Some examples of applications that are typically developed using managed
code are.
 Web applications: Web applications are applications that run on a web
server and can be accessed through a web browser. Web applications can
use managed code to create dynamic and interactive web pages using
technologies such as [Link] Core, which is a framework for building
web applications using C# and other .NET languages.
 Mobile applications: Mobile applications are applications that run on
mobile devices such as smartphones or tablets. Mobile applications can
use managed code to create native or cross-platform apps using
technologies such as Xamarin, which is a platform for building mobile
apps using C# and .NET.
 Desktop applications: Desktop applications are applications that run on
a desktop computer or laptop. Desktop applications can use managed
code to create rich and responsive user interfaces using technologies such
as Windows Forms or WPF, which are frameworks for building desktop
applications using C# and .NET.
1.3.2 Unmanaged Code
Unmanaged code is the type of code that is executed directly by the operating
system or hardware without any intervention from the CLR. Unmanaged code is

.NET PROGRAMMING Page 5


UNIT I

usually written in languages such as C or C++, which are closer to the machine
level than C#.
Characteristics of Unmanaged Code
Some of the main characteristics of unmanaged code are:
 Manual memory management: The developer has to allocate and
deallocate memory for unmanaged code manually, using functions such
as malloc() or free(). This gives more control over the memory usage and
performance of the application but also increases the complexity and
responsibility of the developer.
 No garbage collection: Unmanaged code does not benefit from garbage
collection, so the developer has to ensure that no memory leaks occur in
the application. Memory leaks can degrade the performance and stability
of the application and cause unexpected errors or crashes.
 Potential for memory leaks and vulnerabilities: Unmanaged code can
access any memory location directly without any checks or restrictions
from the CLR. This can lead to memory leaks, corruption, or overflows,
which can compromise the safety and security of the application.
Moreover, unmanaged code can be vulnerable to attacks such as buffer
overflow or injection, which can exploit these weaknesses to execute
malicious or harmful code.
Use Unmanaged Code
Unmanaged code is necessary in some scenarios where the developer needs to
create applications that are.
 Platform-specific: Unmanaged code can run only on the platform that it
is compiled for, such as Windows, Linux, or Mac OS. This can increase
the performance and optimization of the application for a specific
platform or environment.
 Low-level: Unmanaged code can access low-level features and resources
that are not available or restricted in managed code, such as device
drivers, kernel modules, or embedded systems. These features can enable
direct interaction with hardware resources or operating system functions.
 Interoperable with native libraries: Unmanaged code can interoperate
with native libraries or frameworks that are written in languages other
than C#, such as Win32 API, DirectX, or OpenGL. These libraries or

.NET PROGRAMMING Page 6


UNIT I

frameworks can provide functionality or performance that are not supported


or optimized in managed code.
Examples of Unmanaged Code Applications
Some examples of applications that are typically developed using unmanaged code.
 Game development: Game development is the process of creating video
games that run on various platforms such as consoles, computers, or
mobile devices. Game development can use unmanaged code to create
high-performance and realistic graphics, physics, and sound effects using
technologies such as DirectX, OpenGL, or Unreal Engine, which are
native libraries or frameworks for game development.
 System utilities: System utilities are applications that perform specific
tasks or functions related to the system or hardware, such as file
management, disk cleanup, or antivirus. System utilities can use
unmanaged code to access low-level system features or resources that are
not available or restricted in managed code.
 Native applications: Native applications are applications that are
designed and optimized for a specific platform or device, such as
Windows, Linux, or Mac OS. Native applications can use unmanaged
code to create native user interfaces and experiences that are consistent
and compatible with the platform or device.

Sr.
Key Managed Code Unmanaged code
No.
Executed by CLR, Common
Executed by Operating System
Executed Language Runtime, also named
1 directly on the underlying
By as Managed Runtime
hardware.
Environment.
CLR handles security concerns andNo inbuilt security present. It is
2 Security provides inbuilt security to code developer's responsibility to
written in .NET. write safe and secure code.
Memory buffer overflow never
Memory buffer overflow can occur
Memory happens, as CLR handles
3 and can hamper the program
Overflow memory allocation and
execution badly.
deallocation automatically.
4 Runtime CLR provides automatic garbage
No automatic garbage collection

.NET PROGRAMMING Page 7


UNIT I

Sr.
Key Managed Code Unmanaged code
No.
Services collection, exception handling to and other services are provided
managed code. to unmanaged code.
Managed Code is converted to
Unmanaged Code is converted to
5 Output IL, Intermiddiate Language also
native language code.
termed as CIL of MSIL.
Low Programmer can write low level
Programmer has no low level
6 Level access code using unmanaged
access using Managed Code.
Access code.

An Overview of C#
C# (pronounced as C sharp) is a general-purpose, object-oriented programming
language. It is one of the most popular languages used for developing desktop
and web applications.
Features of C# Programming
Simple to write and understand
The code written in C# is much simpler and easier to understand. It is
syntactically very similar to Java. Hence, for a person with experience in Java,
C# won't be a difficult language to learn.
Object-oriented
Like Java and C++, C# is an object-oriented programming language. It supports
the features of object-oriented paradigms such as objects, classes, inheritance,
polymorphism, etc.
Type-Safe
A type-safe language ensures that each variable of a particular type does not
hold values of other types. For example, an integer variable will not hold
character values.
Modern
C# is a modern and powerful language that allows developers to build robust
applications quickly and easily. It is built based on the current trend.

.NET PROGRAMMING Page 8


UNIT I

Why should you learn C# programming?


When you start learning a new programming language, it is important to know
about the prospect of the language. Is the language really helpful? Is it worth
learning it? Before diving into a new programming language, these are the
things you must know.
1. Easy to start
Being a high-level language, the basic constructs of C# is easy to understand. It
is closer to other popular languages like Java and C++. Hence, it is very easy for
someone with experience in these programming languages to switch to C#.
2. Widely used for developing Desktop and Web Application
According to the 2017 survey of StackOverflow, C# is 3rd most popular
language used by professional desktop and web application developers.
Besides web and desktop, C# is also popularly used by DevOps engineers and
data scientists.
3. Community
Community is one of the most important factors to be considered before moving
into a new programming language. Communities provide supports and answers
to your questions.
4. Game development
Unity is the most popular game engine with a very large community. And C# is
often the recommended language to be used along with the unity game engine
for making games.
5. Future as a C# developer
C# was developed by Microsoft and is still being maintained by them. It is the
choice of language for making Windows apps. Hence, C# is going to be in the
market for a long time.
1.4 C# OBJECT-ORIENTED PROGRAMMING

.NET PROGRAMMING Page 9


UNIT I

The four pillars of Object-Oriented Programming are:


1. Inheritance
2. Encapsulation
3. Polymorphism
4. Abstraction
These pillars form the foundation of OOP and are essential concepts to
understand when working with object-oriented programming languages like C#.
1. Inheritance
In C#, inheritance allows us to create a new class from an existing class. It is a
key feature of Object-Oriented Programming (OOP).
The class from which a new class is created is known as the base class (parent
or superclass). And, the new class is called derived class (child or subclass).
The derived class inherits the fields and methods of the base class. This helps
with the code reusability in C#.
How to perform inheritance in C#
In C#, we use the : symbol to perform inheritance. For example,
class Animal {
// fields and methods
}
// Dog inherits from Animal
class Dog : Animal {
// fields and methods of Animal
// fields and methods of Dog
}
Here, we are inheriting the derived class Dog from the base class Animal.
The Dog class can now access the fields and methods of Animal class.

.NET PROGRAMMING Page 10


UNIT I

Example: C# Inheritance
using System;
namespace Inheritance {
// base class
class Animal
{
public string name;
public void display() {
[Link]("I am an animal");
}
}
// derived class of Animal
class Dog : Animal {
public void getName()
{ [Link]("My name is " + name);
}
}
class Program {
static void Main(string[] args) {
// object of derived class
Dog labrador = new Dog();
// access field and method of base class
[Link] = "Rohu";
[Link]();
// access method from own class
[Link]();
[Link]();
}
}
}
Output
I am an animal
My name
In is Rohu example, we have derived
the above a subclass Dog from the
superclass Animal. Notice the statements,
[Link] =
"Rohu";
[Link]();
Here, we are using labrador (object of Dog) to access the name and display() of
the Animal class. This is possible because the derived class inherits all fields
.NET PROGRAMMING Page 11
UNIT I
and methods of the base class.

.NET PROGRAMMING Page 12


UNIT I

Also, we have accessed the name field inside the method of the Dog class.
is-a relationship
In C#, inheritance is an is-a relationship. We use inheritance only if there is an
is-a relationship between two classes. For example,
 Dog is an Animal
 Apple is a Fruit
 Car is a Vehicle
We can derive Dog from Animal class. Similarly, Apple from Fruit
class and Car from Vehicle class.
Types of inheritance
There are the following types of inheritance:
1. Single Inheritance
In single inheritance, a single derived class inherits from a single base class.

C# Single Inheritance

2. Multilevel Inheritance
In multilevel inheritance, a derived class inherits from a base and then the same
derived class acts as a base class for another class.

C# Multilevel Inheritance

3. Hierarchical Inheritance
In hierarchical inheritance, multiple derived classes inherit from a single base
class.

.NET PROGRAMMING Page 13


UNIT I

C# Hierarchical Inheritance
4. Multiple Inheritance
In multiple inheritance, a single derived class inherits from multiple base
classes. C# doesn't support multiple inheritance. However, we can achieve
multiple inheritance through interfaces.

Multiple Inheritance

5. Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of inheritance. The
combination of multilevel and hierarchical inheritance is an example of Hybrid
inheritance.

2. Encapsulation
Consider a gift box that contains a gift. The gift box acts as a container that
encapsulates the gift. The gift is hidden from the outside world and can only be

.NET PROGRAMMING Page 14


UNIT I

accessed through the gift box. This is akin to Encapsulation in object-oriented


programming.
Encapsulation is the principle of bundling the data (fields) and methods
(functions) that operate on the data into a single unit, known as a class. It
restricts direct access to some of an object's components and allows access only
through the methods of the class. In essence, Encapsulation conceals the
internal state of an object and only exposes the necessary information to the
outside world.
Let's see an example in C#:
public class Person
{
private string name;
private int age;
public string Name
{
get { return name; }
set { name = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
public void Display()
{
[Link]($"Name: {Name}, Age: {Age}");
}
}
In the above code snippet, the Person class encapsulates the data
(fields name and age) and methods (Display) into a single unit. The
fields name and age are private, meaning they cannot be accessed directly from
outside the class. The properties Name and Age provide controlled access to the
private fields using get and set accessors.

3. Polymorphism
Polymorphism is a core concept in object-oriented programming that allows
objects of different classes to be treated as objects of a common super class. It

.NET PROGRAMMING Page 15


UNIT I

provides a single interface to represent multiple underlying forms (classes) and


enables objects to be processed in a generic manner.
In C#, there are two types of Polymorphism:
1. Compile-time Polymorphism (Method Overloading)
2. Run-time Polymorphism (Method
Overriding) Compile-time Polymorphism (Method
Overloading)
Compile-time Polymorphism, also known as Method Overloading, allows a
class to have multiple methods with the same name but different parameters.
The compiler determines which method to invoke based on the number and
types of arguments.
Here's an example of Method Overloading in C#:
public class Printer
{
public void Print(string message)
{
[Link]($"Printing string: {message}");
}

public void Print(int number)


{
[Link]($"Printing number: {number}");
}

public void Print(string message, int copies)


{
for (int i = 0; i < copies; i++)
{
[Link]($"Printing string: {message}");
}
}
}
In this example, the Printer class has three Print methods with the same name
but different parameters. This is an example of Method Overloading in C#.
Run-time Polymorphism (Method Overriding)

.NET PROGRAMMING Page 16


UNIT I

Run-time Polymorphism, also known as Method Overriding, allows a subclass


to provide a specific implementation of a method that is already provided by its
superclass.
Here's an example of Method Overriding in C#:
public class MusicPlayer
{
public virtual void Play()
{
[Link]("Playing music");
}
}

public class Mp3Player : MusicPlayer


{
public override void Play()
{
[Link]("Playing MP3 music");
}
}

public class WavPlayer : MusicPlayer


{
public override void Play()
{
[Link]("Playing WAV music");
}
}
In this example, the MusicPlayer class has a virtual method Play.
The Mp3Player and WavPlayer classes override the Play method with specific
implementations for playing MP3 and WAV music, respectively. This is an
example of Method Overriding in C#.
Let's see how Polymorphism can be used in a program:
MusicPlayer player = new Mp3Player();
[Link](); // Output: Playing MP3 music

player = new WavPlayer();

.NET PROGRAMMING Page 17


UNIT I

[Link](); // Output: Playing WAV music


In this code snippet, we created an object of the Mp3Player class and assigned it
4. Abstraction
Abstraction is a key concept in object-oriented programming that allows you to
create a blueprint for a class with some abstract methods that must be
implemented by the derived classes. It enables you to define the structure of a
class without providing the implementation details.
In C#, Abstraction can be achieved using abstract classes and interfaces. Let's
explore both concepts:
Abstract Classes
An abstract class is a class that cannot be instantiated and can contain both
abstract and non-abstract methods. An abstract method is a method without a
body that must be implemented by the derived classes.
Here's an example of an abstract class in C#:

public abstract class Animal


{
public abstract void Speak();
}

public class Dog : Animal


{
public override void Speak()
{
[Link]("The dog barks");
}
}

public class Cat : Animal


{
public override void Speak()
{
[Link]("The cat meows");
}
}

.NET PROGRAMMING Page 18


UNIT I

In this example, the Animal class is an abstract class with an abstract


method Speak. The Dog and Cat classes inherit from the Animal class and
provide specific implementations for the Speak method. This is an example
of Abstraction using abstract classes in C#.

1.5 FIRST SIMPLE PROGRAM


[Link]
using System;

namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
[Link]("Hello World!");
}
}
}
Result:
Hello World!

Example explained
Line 1: using System means that we can use classes from
the System namespace.
Line 2: A blank line. C# ignores white space. However, multiple lines makes the
code more readable.
Line 3: namespace is used to organize your code, and it is a container for classes
and other namespaces.
Line 4: The curly braces {} marks the beginning and the end of a block of code.
Line 5: class is a container for data and methods, which brings functionality to
your program. Every line of code that runs in C# must be inside a class. In our
example, we named the class Program.
Line 7: Another thing that always appear in a C# program is the Main method.
Any code inside its curly brackets {} will be executed. You don't have to

.NET PROGRAMMING Page 19


UNIT I

understand the keywords before and after Main. You will get to know them bit
by bit while reading this tutorial.
Line 9: Console is a class of the System namespace, which has
a WriteLine() method that is used to output/print text. In our example, it will
output "Hello World!".
If you omit the using System line, you would have to
write [Link]() to print/output text.

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 201

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

.NET PROGRAMMING Page 20


UNIT I

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

.NET PROGRAMMING Page 21


UNIT I

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;
using [Link];
using [Link];
using [Link];
using [Link];

namespace CSharpTutorials
{
class Program
{
static void Main(string[] args)
{
string message = "Hello World!!";

[Link](message);
}
}
}
The following image illustrates the important parts of the above example.

C# Code Structure

.NET PROGRAMMING Page 22


UNIT I

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 [Link].
2. Declare the namespace for the current class using
the namespace keyword, e.g., namespace [Link]
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 [Link]() is a static method, which is used to display a
text on the console.
9. Every line or statement in C# must end with a semicolon (;).
Compile and Run C# Program
To see the output of the above C# program, we have to compile it and run it by
pressing Ctrl + F5 or clicking the Run button or by clicking the "Debug" menu
and clicking "Start Without Debugging". You will see the following output in
the console:
Output:
Hello World!!

1.6 HANDLING SYNTAX ERRORS


 If you are new to programming, it is important to learn how to interpret
and respond to errors that may occur when you try to compile a program.
 Most compilation errors are caused by typing mistakes.
 As all programmers soon find out, accidentally typing something
incorrectly is quite easy.
 Fortunately, if you type something wrong, the compiler will report a
syntax error message when it tries to compile your program.
 This message gives you the line number at which the error is found and a
description of the error itself.

.NET PROGRAMMING Page 23


UNIT I

 Although the syntax errors reported by the compiler are, obviously,


helpful, they sometimes can also be misleading.
 The C# compiler attempts to make sense out of your source code no
matter what you have written.
 For this reason, the error that is reported may not always reflect the actual
cause of the problem.
 In the preceding program, for example, an accidental omission of the
opening curly brace after the Main( ) method generates the following
sequence of errors when compiled by the csc command-line compiler.
(Similar errors are generated when compiling using the IDE.)
1.7 USING CODE BLOCKS
 C# supports the code block.
 A code block is a grouping of statements.
 This is done by enclosing the statements between opening and closing
curly braces.
 Once a block of code has been created, it becomes a logical unit that can
be used any place a single statement can.
 For example, a block can be a target for if and for
statements. Consider this if statement:
if(w < h)
{
v = w * h;
w = 0;
}
Here, if w is less than h, then both statements inside the block will be executed. Thus,
the two statements inside the block form a logical unit, and one statement cannot
execute without the other also executing.
Whenever you need to logically link two or more statements, you do so by
creating a block.
Here is a program that uses a code block to prevent a division by zero:
// Demonstrate a block of code.

using System;

public class Program {


static void Main() {

.NET PROGRAMMING Page 24


UNIT I

int i, j, d;

i = 5;
j = 10;

// The target of this if is a block.


if(i != 0) {
[Link]("i does not equal zero");
d = j / i;
[Link]("j / i is " + d);
}
}
}
The output generated by this program is shown here:
In this case, the target of the if statement is a block of code and not just a single
statement.
If the condition controlling the if is true, the three statements inside the block
will be executed.
If, Else, If Else
The most basic of the selection statement keywords are if and else. We use
these keywords to evaluate Boolean expressions and direct the program to
execute specified lines of code if certain expressions are true.
if (expression) //If this expression evaluates to true...
{
//...Execute this
}
else
{
//Otherwise, execute this
}
We can also use an else if clause to add more conditions to our evaluation.
Switch, Case, Break
Sometimes we want to evaluate a given object against a large set of possible
values. For these situations, we use the keyword switch and its related
keywords case and break.
A switch statement is used when a single object needs to be evaluated against a
large number of potential values. Each of these possible values is identified by

.NET PROGRAMMING Page 25


UNIT I

using a case statement. The case statement can consist of multiple lines of code,
and ends when the system encounters the break keyword.
switch(variable)
{
case value1:
executeThis();
executeThat();
break;

case value2:
executeThisOtherThing();
break;

default:
break;
}
For example, let's imagine we have a company that is sponsoring us for a
tournament of some kind. We want to display the company a message, but we
need it to be a different message for each level of sponsorship that we offer. We
might implement a switch statement to output the correct message for each
sponsorship level:
Loops
In C#, loops are code blocks that are executed multiple times. The exact number
of times they are executed can differ, or be dependent on a variable, or on a
collection of objects.
There are four ways to implement a loop in C#, and they each have a distinct
use.
For Loop
A for loop is a loop that executes once for each value in a given range. The loop
must define a variable (commonly named i or j, termed the initializer);
a condition where the loop will execute again so long as the condition is true;
and an iterator which defines by how much the initializer will change after
every loop.
A common kind of for loop uses integers and a simple increment.
for(int i = 0; //Initializer
i < 10; //Condition

.NET PROGRAMMING Page 26


UNIT I

i++) //Iterator
{
//This code will execute ten times,
//one each for i = 0, i = 1, up to and including i = 9.
}

Foreach Loop
When dealing with collections of objects (such as an array or a List<T>; both of
which will be discussed later in this series), we can use a foreach loop to iterate
over every object in the collection. In this case, the iterator object is of the same
type as objects in said collection.
var items = new int[] {4, 5, 6, 7, 8};
foreach(int item in items)
{
[Link](item);
}

//Example class
public class Drawing
{
public string Name { get; set; }
}

//Make a collection of Drawings


List<Drawing> drawings = new List<Drawing>()
{
new Drawing()
{
Name = "Test Drawing 1"
},
new Drawing()
{
Name = "Test Drawing 2"
}
};

//Iterate over each drawing in the collection


foreach (Drawing iterator in drawings) //iterator is of type Drawing

.NET PROGRAMMING Page 27


UNIT I

{
[Link]([Link]);
}
Using a foreach loop to iterate over a collection is the most common scenario
for this kind of loop.

While Loop
A while loop evaluates a condition, and so long as that condition is true, the
loop will keep executing.
int myVal = 5;
while(myVal < 1000)
{
DoSomething();
DoSomethingElse();
//We didn't increment myVal, so this loop will never stop executing!
}
Because a while loop evaluates the condition before entering the loop, if that
condition is false before the loop starts, the loop will not be executed.
Do While Loop
By contrast, a do while loop will always execute at least once, because the
condition is evaluated at the end of the loop.
int myVal = 1;
do
{
DoSomething();
DoSomethingElse();
myVal++;
} while (myVal < 1000);
If you must guarantee that the code in a loop run at least one time, use a do
while loop.
Breaking the Loop
In many situations, we may want to stop executing the loop before the loop
reaches its end condition. There are several keywords we can use for these
situations.

Break
.NET PROGRAMMING Page 28
UNIT I

The break keyword ends execution of the loop. No further iterations of the loop
will execute.
for(int i = 0; i < 10; i++)
{
if(i == 7)
{
break; //Will exit the for loop
}
}
You might have noticed that this keyword was also used in the switch statement
examples above, and its function was similar there.
Continue
The continue keyword ends execution of the current iteration of the loop, but
will restart the loop at the next iteration.
int myVal = 5;
while (myVal <
10)
{
if (myVal == 7)
{
myVal++;
continue; //If i == 7, processing stops here and resumes
//at the top of the loop with the next value 8.
//[Link] is never called in that case.
}
//The below output will not happen when myVal = 7
[Link]("The current value of myVal is " + [Link]());
myVal++;
}Return
The return keyword, similarly to how it works in methods, will return a value to
the calling code. The loop will therefore stop executing.
var emails = GetEmails(); //Method not defined here

foreach(var email in emails)


{
if([Link] == "mybeloved@[Link]")
{

.NET PROGRAMMING Page 29


UNIT I

return email; //Loop stops executing


}
}
New Keywords
 if - Specifies a block of code that will executed if a particular condition
is true.
 else if - Specifies a block of code that will executed if a particular
condition is true. Must be used in tandem with an if.
 else - Specifies a block of code that will be executed if non of the
previous if statements were executed. Must be used with an if.
 for - Specifies a loop that will execute a defined number of times. Must
have an initializer, a condition, and an increment.
 foreach - Specifies a loop that will execute once for each item in a
collection, unless the loop is broken.
 while - Specifies a loop that will execute so long as a given condition
is true.
 do while - Specifies a loop that will execute at least once, and then will
continue executing as long as the condition is true.
 break - Stops execution of a loop OR marks the end point of a case in
a switch statement.
 continue - Stops the current iteration of a loop, and resumes execution at
the next iteration.
 return - Stops execution of a loop and returns a value to the calling code.

1.8 SEMICOLON, POSITIONING AND INDENTATION


Semicolon Usage
 Semicolons are used to terminate statements in C#. Every statement must
end with a semicolon (;).
int x = 10;
[Link](x);

Positioning

.NET PROGRAMMING Page 30


UNIT I

 Braces ({}): The positioning of braces can follow different styles, such as
Allman (braces on a new line) or K&R (braces on the same line).
Allman Style:
void MyMethod()
{
if (condition)
{
// code
}
}
K&R Style:
void MyMethod()
{ if (condition) {
// code
}
}
Indentation
 Indentation: Proper indentation improves code readability. In C#, the
typical indentation is 4 spaces per indentation level.
 Indentation Options:
o Block Contents: Indent the contents of blocks (e.g., methods,
loops).
o Case Contents: Indent the contents of case statements within a
switch.
o Labels: Indent labels in switch statements.
o Braces: Decide whether to indent braces or not.
Example:
void MyMethod()
{
if (condition)
{
// Indented block
[Link]("Hello, World!");
}
}
1.9 THE C# KEYWORDS

.NET PROGRAMMING Page 31


UNIT I

Keywords or Reserved words are the words in a language that are used for
some internal process or represent some predefined actions. These words are
therefore not allowed to use as variable names or objects. Doing this will result
in a compile-time error.
Example:

// C# Program to illustrate the keywords


using System;

class GFG {

// Here static, public, void


// are keywords
static public void Main () {

// here int is keyword


// a is identifier
int a = 10;

[Link]("The value of a is: {0}",a);

// this is not a valid identifier

// removing comment will give compile time error


// double int = 10;

}
}
Output:
The value of a is: 10
There are total 78 keywords in C# as follows:

abstract as base bool

break byte case catch

char checked class const

continue decimal default delegate

.NET PROGRAMMING Page 32


UNIT I

do double else enum

event explicit extern false

finally fixed float for

foreach goto if implicit

in in (generic modifier) int interface

internal is lock long

namespace new null object

operator out out (generic modifier) override

params private protected public

readonly ref return sbyte

sealed short sizeof stackalloc

static string struct switch

this throw true try

typeof uint ulong unchecked

unsafe ushort using using static

void volatile while

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


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

Example:

.NET PROGRAMMING Page 33


UNIT I

// C# Program to illustrate the


// value type keywords
using System;

class GFG {

// Here static, public, void


// are keywords
static public void Main () {

// here byte is keyword


// a is identifier
byte a = 47;
[Link]("The value of a is: {0}",a);

// here bool is keyword


// b is identifier
// true is a keyword
bool b = true;

[Link]("The value of b is: {0}",b);

}
}

Output:
The value of a is: 47
The value of b is: True
2. Reference Type Keywords: There are 6 keywords in reference types
which are used to store references of the data or objects. The keywords in
this category are: class, delegate, interface, object, string, void.

3. Modifiers Keywords: There are 17 keywords in modifiers which are


used to modify the declarations of type member.

.NET PROGRAMMING Page 34


UNIT I

public private internal protected abstract

const event extern new override

partial readonly sealed static unsafe

virtual volatile

Example:

// C# Program to illustrate the


// modifiers keywords
using System;
class Geeks
{ class Mod
{
// using public modifier
// keyword
public int n1;

}
// Main Method
static void Main(string[] args)
{ Mod obj1 = new Mod();
// access to public members
obj1.n1 = 77;
[Link]("Value of n1: {0}", obj1.n1);

Output:
Value of n1: 77
4. Statements Keywords: There are total 18 keywords which are used in
program instructions.

.NET PROGRAMMING Page 35


UNIT I

if else switch do for

foreach in while break continue

goto return throw try catch

finally checked unchecked

Example:

// C# program to illustrate the statement keywords


using System;

class demoContinue
{
public static void Main()
{

// using for as statement keyword


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

// here if and continue are keywords


if(i == 2)
continue;

[Link]("GeeksforGeeks");
}
}
}
Output:
GeeksforGeeks
5. Method Parameters Keywords: There are total 4 keywords which are
used to change the behavior of the parameters that passed to a method.
The keyword includes in this category are: params, in, ref, out.

.NET PROGRAMMING Page 36


UNIT I

6. Namespace Keywords: There are total 3 keywords in this category


which are used in namespaces. The keywords are: namespace, using,
extern.

7. Operator Keywords: There are total 8 keywords which are used for
different purposes like creating objects, getting a size of object etc. The
keywords are: as, is, new, sizeof, typeof, true, false, stackalloc.

8. Conversion Keywords: There are 3 keywords which are used in type


conversions. The keywords are: explicit, implicit, operator.

9. Access Keywords: There are 2 keywords which are used in accessing


and referencing the class or instance of the class. The keywords are base,
this.

[Link] Keywords: There are 2 keywords which are used as literal or


constant. The keywords are null, default.
Important Points:
 Keywords are not used as an identifier or name of a class, variable, etc.
 If you want to use a keyword as an identifier then you must use @ as a
prefix. For example, @abstract is valid identifier but
not abstract because it is a keyword.
Example:
int a = 10; // Here int is a valid keyword
double int = 10.67; // invalid because int is a keyword
double @int = 10.67; // valid identifier, prefixed with @
int @null = 0; // valid

// C# Program to illustrate the use of


// prefixing @ in keywords

.NET PROGRAMMING Page 37


UNIT I

using System;
class GFG {

// Here static, public, void


// are keywords
static public void Main () {

// here int is keyword


// a is identifier
int a = 10;

[Link]("The value of a is: {0}",a);

// prefix @ in keyword int which


// makes it a valid identifier
int @int = 11;

[Link]("The value of a is: {0}",@int);

}
}
Output:
The value of a is: 10
The value of a is: 11
1.10 IDENTIFIERS
 Identifiers are the name given to entities such as variables, methods,
classes, etc. They are tokens in a program which uniquely identify an
element. For example,
 int value;
 Here, value is the name of variable. Hence it is an identifier. Reserved
keywords can not be used as identifiers unless @ is added as prefix. For
example,
 int break;
 This statement will generate an error in compile time.
Rules for Naming an Identifier
 An identifier can not be a C# keyword.

.NET PROGRAMMING Page 38


UNIT I

 An identifier must begin with a letter, an underscore or @ symbol. The


remaining part of identifier can contain letters, digits and underscore
symbol.
 Whitespaces are not allowed. Neither it can have symbols other than
letter, digits and underscore.
 Identifiers are case-sensitive.
So, getName, GetName and getname represents 3 different identifiers.
Here are some of the valid and invalid identifiers:

Identifiers Remarks

number Valid

calculateMarks Valid

hello$ Invalid (Contains $)

name1 Valid

@if Valid (Keyword with prefix @)

if Invalid (C# Keyword)

My name Invalid (Contains whitespace)

_hello_hi Valid

Example: Find list of keywords and identifiers in a program


Just to clear the concept, let's find the list of keywords and identifiers in the
program we wrote in C# Hello World.
using System;
namespace HelloWorld
{
class Hello

.NET PROGRAMMING Page 39


UNIT I

{
static void Main(string[] args)
{
[Link]("Hello World!");
}
}
}

Keywords Identifiers

using System

namespace HelloWorld (namespace)

class Hello (class)

static Main (method)

void args

string Console

WriteLine

The "Hello World!" inside WriteLine method is a string literal.

1.11 THE .NET FRAMEWORK CLASS LIBRARY


.NET Framework Class Library is the collection of classes, namespaces,
interfaces and value types that are used for .NET applications.
It contains thousands of classes that supports the following functions.
o Base and user-defined data types
o Support for exceptions handling

.NET PROGRAMMING Page 40


UNIT I

o input/output and stream operations


o Communications with the underlying system
o Access to data
o Ability to create Windows-based GUI applications
o Ability to create web-client and server applications
o Support for creating web services
.NET Framework Class Library Namespaces
Following are the commonly used namespaces that contains useful classes and
interfaces and defined in Framework Class Library.

Namespaces Description

It includes all common datatypes,


string values, arrays and
System
methods for data conversion.

[Link], [Link],
[Link], These are used to access a database,
[Link], perform commands on a
[Link] database and retrieve database.

[Link], [Link],
These are used to access, read
[Link]
and write files.

It is used to debug and trace the


[Link]
execution of an application.

These are used to communicate


[Link], [Link] over the Internet when creating
peer-to-peer applications.

[Link], These namespaces are used to


[Link] create Windows-based

.NET PROGRAMMING Page 41


UNIT I

applications using Windows user


interface components.

[Link], [Link],
[Link],
[Link],
[Link], These are used to create ASP.
[Link], NET Web applications that run
[Link], over the web.
[Link],
[Link],
[Link]

[Link],
These are used to create XML
[Link],
Web services and components
[Link],
that can be published over the
[Link],
web.
[Link]

[Link],
[Link], These are used for
[Link], authentication, authorization,
[Link], and encryption purpose.
[Link]

[Link], [Link],
[Link], These namespaces are used to
[Link], create and access XML files.
[Link]

.NET Framework Base Class Library


.NET Base Class Library is the sub part of the Framework that provides library
support to Common Language Runtime to work properly. It includes the System

.NET PROGRAMMING Page 42


UNIT I

1.12 DATA TYPES, LITERALS AND VARIABLES


1.12.1 DATA TYPES
A data type specifies the type of data that a variable can store such as integer,
floating, character 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

.NET PROGRAMMING Page 43


UNIT I

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

-2,147,483,648 to -
int 4 byte
2,147,483,647

-2,147,483,648 to -
signed int 4 byte
2,147,483,647

unsigned int 4 byte 0 to 4,294,967,295

.NET PROGRAMMING Page 44


UNIT I

?9,223,372,036,854,775,808
long 8 byte to
9,223,372,036,854,775,807

?9,223,372,036,854,775,808
signed long 8 byte to
9,223,372,036,854,775,807

0 -
unsigned long 8 byte
18,446,744,073,709,551,615

1.5 * 10-45 - 3.4 * 1038, 7-


float 4 byte
digit precision

5.0 * 10-324 - 1.7 * 10308, 15-


double 8 byte
digit precision

at least -7.9 * 10?28 - 7.9 *


decimal 16 byte 1028, with at least 28-digit
precision

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.
Pointer Data Type
The pointer in C# language is a variable, it is also known as locator or indicator
that points to an address of a value.

.NET PROGRAMMING Page 45


UNIT I

Symbols used in pointer

Symbol Name Description

Determine the address


& (ampersand sign) Address operator
of a variable.

Access the value of an


* (asterisk sign) Indirection operator
address.

Declaring a pointer
The pointer in C# language can be declared using * (asterisk symbol).
1. int * a; //pointer to int
2. char * c; //pointer to char

// C# program to demonstrate
// the above data types
using System;
namespace ValueTypeTest {

class GeeksforGeeks {

// Main function
static void Main()
{

// declaring character
char a = 'G';

// Integer data type is generally


// used for numeric values
int i = 89;

short s = 56;

.NET PROGRAMMING Page 46


UNIT I

// this will give error as number


// is larger than short range
// short s1 = 87878787878;

// long uses Integer values which


// may signed or unsigned
long l = 4564;

// UInt data type is generally


// used for unsigned integer values
uint ui = 95;

ushort us = 76;
// this will give error as number is
// larger than short range

// ulong data type is generally


// used for unsigned integer values
ulong ul = 3624573;

// by default fraction value


// is double in C#
double d = 8.358674532;

// for float use 'f' as


suffix float f =
3.7330645f;

// for float use 'm' as suffix


decimal dec = 389.5m;

[Link]("char: " + a);


[Link]("integer: " + i);
[Link]("short: " + s);
[Link]("long: " + l);
[Link]("float: " + f);
[Link]("double: " + d);
[Link]("decimal: " + dec);
[Link]("Unsinged integer: " + ui);
[Link]("Unsinged short: " + us);

.NET PROGRAMMING Page 47


UNIT I
[Link]("Unsinged long: " + ul);

.NET PROGRAMMING Page 48


UNIT I

}
}
}

output:

char: G
integer: 89
short: 56
long: 4564
float: 3.733064
double: 8.358674532
decimal: 389.5
Unsinged integer: 95
Unsinged short: 76
Unsinged long: 3624573

1.12.3 LITERALS
 C# literals are fixed values (or hard-coded values) assigned to variables
that cannot be changed during program execution.
 They represent various types of constants such as integers, floats, chars,
and strings.
 Integer literals can be in decimal, binary, octal, or hexadecimal format.
Floating-point literals represent numbers with fractional parts.
 Character literals represent individual characters, whereas string literals
represent sequences.
 Boolean literals are 'true' or 'false', and 'null' represents absence.
 By providing direct, recognizable values for data initialization and
manipulation, C# literals enhance code clarity and efficiency.
Example:
x = 100;
In this example, x is a variable that holds the value 100, which is a literal value.
The assignment of a literal value to a variable allows you to store and
manipulate data in your program.
Top 5 Types of Literals in
C# Integer Literals

.NET PROGRAMMING Page 49


UNIT I

An integer literal is a value of the integer type. It can be represented as an


octal, decimal, binary, or hexadecimal constant. Decimal numbers don't need a
prefix. Integer literals can also have suffixes like U or u for unsigned numbers,
and l or L for long numbers. By default, all literals are treated as int type. We
have several ways of representing literals when working with integral data types
like as byte, short, int, and long:
 Decimal Literals (Base 10): For decimal literals, they can include digits
from 0 to 9, and no prefix is necessary.
 int x = 10; // decimal type
 Octal Literals (Base 8): The numbers from 0 to 7 are included in octal
literals, and 0 is used as a prefix to specify the form of octal-type literals.
 int x = 062; // octal literal
 Hexa-decimal Literals (Base 16): Hexadecimal literals can consist of
digits from 0 to 9 and characters from A to F, in both uppercase and
lowercase forms. They are preceded by 0x or 0X. C# is a case-sensitive
programming language, but it is not case-sensitive here.
 int x = 0x132f; // hexadecimal literal
 Binary Literals (Base 2): Binary literals, which are expressed in base 2,
only use the digits 1 and 0. To denote a binary number, it must be
prefixed with "0b".
 int x = 0b101; // binary literal
Floating-point Literals
A floating-point literal is a representation consisting of an integer component,
a dot (decimal point), a fractional component, and an exponent component.
These can be expressed in either standard decimal form or in exponential
notation.
Example:
double val = 2.13154; // Valid
double val = 213589E-5; // Valid
double val = 252E; // Invalid: Incomplete exponent
double val = 824f; // Valid
double val = .e54; // Invalid: Missing integer or fraction

.NET PROGRAMMING Page 50


UNIT I

Character Literals
Character literals are enclosed within single quotes (''). There are three ways to
represent character literals.
 Single Quote: Character literals can be expressed as individual
characters within single quotes.
 char ch = 'A'; // Character 'A'
 Unicode Representation: Character literals can also be created using
Unicode representation, which includes using the syntax uxxxx,
where xxxx represents hexadecimal values.
 char ch = '\u0041'; // Unicode representation of 'A'
 Escape Sequence: Certain escape characters are recognized as character
literals, allowing you to represent special characters using escape
sequences.
 char ch = '\n'; // Newline character
The following are various escape sequence literals and their meanings.
Escape Sequence Meaning
\ \ character
\’ ‘ character
? ? character
\” ” character
\b Backspace
\a Alert or Bell
\n New Line
\f Form Feed
\r Carriage Return
\v Vertical Tab
\xhh Hexadecimal number

.NET PROGRAMMING Page 51


UNIT I

String Literals
String literals are enclosed in double quotations (""). They can also start
with @"", making it simpler to handle large lines by breaking them into
multiple lines with string literals and separating them with spaces.
Example:
string str1 = "Hello, world!"; // String literal
string str2 = @"This is a long
string."; // Verbatim string literal
Boolean Literals
Boolean literals are restricted to just two values: true and false.
Example:
bool a = true;
bool b = false;
Examples of C# Literals
The examples below demonstrate how to implement all of the literals in C#.
Example 1: Integer Literal
using System;

class Scaler
{
public static void Main(String[] args)
{
// decimal literal
int a = 10;

// octal literal
int b = 062;

// Hexadecimal literal
int c = 0x132f;

// binary literal
int d = 0b101;

.NET PROGRAMMING Page 52


UNIT I

[Link](a);
[Link](b);
[Link](c);
[Link](d);
}
}
Output:
10
62
4911
5
Explanation:
The above C# code demonstrates the use of multiple integer literals and their
values. It uses variables to store these literals: a decimal literal (10), an octal
literal (062, which is equivalent to 50 in decimal), a hexadecimal literal
(0x132f0x132f, which is equivalent to 4911 in decimal), and a binary literal
(0b101, which is equivalent to 5 in decimal). The code then prints these values
using the [Link] statements.
Example 2: Floating Point Literal
using System;

class Scaler
{
public static void Main(String[] args)
{
double a = 632.281;
double b = 0574.951;
double c = 243183E-4F;

[Link](a);
[Link](b);
[Link](c);
}
}
Output:
632.281
574.951
24.3183002471924

.NET PROGRAMMING Page 53


UNIT I

Explanation: The above C# code initializes three double variables: a, b, and c.


The value 632.281 is assigned to a decimal-point literal, while 0574.951,
despite starting with a zero, is recognized as a decimal-point literal due to the
presence of the decimal point. The value of c is expressed in exponential
notation as 243183 multiplied by 10 to the power of -4 (0.0001), with the F
suffix implying a float type, although it's important to note that it doesn't affect
the default double-precision nature of these literals. Following that, the
[Link] statements output the values of these variables.
Example 3: Character Literals
using System;

class Scaler
{
public static void Main(String[] args)
{
char ch1 = 'a';
char ch2 = '\u0071';

[Link](ch1);
[Link](ch2);
[Link]("Hello\nWorld\t!");
}
}
Output:
a
q
Hello
World !
Explanation:
The above C# code initializes two character variables ch1 and ch2. The
character literal 'a' is allocated to ch1, while the Unicode representation of 'q' is
assigned to ch2 using the escape sequence u0071. The [Link]
statements then output the values of ch1 and ch2. Additionally, the last
[Link] statement prints the string "Hello" followed by a newline (\
n) and then "World" followed by a tab (\t) and finally an exclamation mark,
resulting in the formatted output "Hello\nWorld\t!".
Example 4: String Literal

.NET PROGRAMMING Page 54


UNIT I

using System;

class Scaler
{
public static void Main(String[] args)
{
string str1 = "Hello, world!"; // String literal
string str2 = @"This is a long string."; // Verbatim string literal

[Link](str1);
[Link](str2);
}
}
Output:
Hello, world!
This is a long string.
Explanation:
The C# code above declares two string variables, str1 and str2. The string literal
"Hello, world!" is assigned to str1, while the string literal @"This is a long
string." is assigned to str2. The values of str1 and str2 are then printed by the
[Link] statements, resulting in the display of the respective string
literals.
Example 5: Boolean Type Literal
using System;

class Scaler
{
public static void Main(String[] args)
{
bool a = true;
bool b = false;

[Link](a);
[Link](b);
}
}
Output:
True
False

.NET PROGRAMMING Page 55


UNIT I

Explanation: The above C# code initializes two boolean variables, a and b,


with the values true and false, respectively. The [Link] statements
then output the values of a and b, resulting in the display of the corresponding
boolean literals

1.12.3 VARIABLES
A variable is a symbolic name given to a memory location. Variables are used to
store data in a computer program.
How to declare variables in C#
Here's an example to declare a variable in C#.
int age;
In this example, a variable age of type int (integer) is declared and it can only
store integer values.
We can assign a value to the variable later in our program like such:
int age;
... ... ...
age = 24;
However, the variable can also be initialized to some value during declaration.
For example,
int age = 24;
Here, a variable age of type int is declared and initialized to 24 at the same
time. Since, it’s a variable, we can change the value of variables as well. For
example, int age = 24;
age = 35;
Here, the value of age is changed to 35 from 24.
Variables in C# must be declared before they can be used. This means, the name
and type of variable must be known before they can be assigned a value. This is
why C# is called a statically-typed language.
Once declared, the datatype of a variable can not be changed within a scope. A
scope can be thought as a block of code where the variable is visible or

.NET PROGRAMMING Page 56


UNIT I

available to use. If you don’t understand the previous statement, don’t worry
we’ll learn about scopes in the later chapters.
For now remember,we can not do the following in C#:
int age;
age = 24;
... ... ...
float age;
Implicitly typed variables
Alternatively in C#, we can declare a variable without knowing its type
using var keyword. Such variables are called implicitly typed local variables.
Variables declared using var keyword must be initialized at the time of
declaration.
var value = 5;
The compiler determines the type of variable from the value that is assigned to
the variable. In the above example, value is of type int. This is equivalent to:
int value;
value = 5;
You can learn more about implicitly typed local variables.
Rules for Naming Variables in C#
There are certain rules we need to follow while naming a variable. The rules for
naming a variable in C# are:
1. The variable name can contain letters (uppercase and lowercase),
underscore( _ ) and digits only.
2. The variable name must start with either letter, underscore or @ symbol.
For example,

Rules for naming variables in C#

Variable
Remarks
Names

.NET PROGRAMMING Page 57


UNIT I

Rules for naming variables in C#

Variable
Remarks
Names

name Valid

subject101 Valid

Valid (Best practice for naming private member


_age
variables)

@break Valid (Used if name is a reserved keyword)

101subject Invalid (Starts with digit)

your_name Valid

your name Invalid (Contains whitespace)

3. C# is case sensitive. It means age and Age refers to 2 different variables.


4. A variable name must not be a C# keyword. For
example, if, for, using can not be a variable name. We will be discussing
more about C# keywords in the next tutorial.

Best Practices for Naming a Variable


1. Choose a variable name that make sense. For
example, name, age, subject makes more sense than n, a and s.
2. Use camelCase notation (starts with lowercase letter) for naming local
variables. For example, numberOfStudents, age, etc.
3. Use PascalCase or CamelCase (starts with uppercase letter) for naming
public member variables. For example, FirstName, Price, etc.

.NET PROGRAMMING Page 58


UNIT I

4. Use a leading underscore (_) followed by camelCase notation for naming


private member variables. For example, _bankBalance, _emailAddress,
etc.
Various Types of Variables in C#

Local Variables in C#
Local variables in C# are variables declared within a method, constructor, or block
of code. They have limited scope and are accessible only within the block where
they are declared. Local variables must be initialized before use and are often
used for temporary storage of data in a program.
Example
using System;class StudentDetails {
public void StudentAge()
{
int age = 0;
age = age + 10;
[Link]("Student age is : " + age);
}
public static void Main(String[] args)
{
StudentDetails obj = new StudentDetails();
[Link]();
}
}

.NET PROGRAMMING Page 59


UNIT I

Explanation
This C# code defines a class named "StudentDetails" with a method
"StudentAge" that increments a local variable "age" by 10 and prints the result.
The Main method creates an instance of the class and calls the "StudentAge"
method, displaying the student's age as 10
Output
Student age is: 10
Instance Variables or Non-Static Variables
In C#, instance variables are data members declared within a class but outside
of any method. They represent the attributes or properties of objects created
from the class. Each object instance has its own set of instance variables, which
define the object's state and behaviour.
Example
using System;
class Marks
{

int engMarks;
int mathsMarks;
int phyMarks;

public static void Main(String[] args)


{

Marks obj1 = new Marks();


[Link] = 89;
[Link] = 76;
[Link] = 65;

Marks obj2 = new Marks();


[Link] = 85;
[Link] = 98;
[Link] = 91;

[Link]("Marks for first object:");


[Link]([Link]);
[Link]([Link]);

.NET PROGRAMMING Page 60


UNIT I

[Link]([Link]);

[Link]("Marks for second object:");


[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
}

Explanation
This C# program defines a class "Marks" with three instance variables
(engMarks, mathsMarks, and phyMarks) to store subject marks. It creates two
objects (obj1 and obj2), assigns different marks to each object, and displays the
marks for both objects using [Link], demonstrates the use of
instance variables to store and access data for different instances of the class.
Output
Marks for first object:
89
76
65
Marks for second object:
85
98
91
Static Variables or Class Variables
In C#, static variables are class-level variables that belong to the type itself
rather than to specific instances of the class. They are shared among all
instances of the class and retain their values throughout the program's
execution, providing a common storage location for all objects of that class.
Example
using System;
class Emp {static double salary;
static String name = "Rohan";

.NET PROGRAMMING Page 61


UNIT I

public static void Main(String[] args)


{
[Link] = 125000;
[Link]([Link] + "'s average salary:" + [Link]);
}
}

Explanation
This C# program defines a class "Emp" with static variables "salary" and
"name." It sets the static salary to 125000 and the name to "Rohan." In the Main
method, it prints the name and average salary using the static variables. Static
variables are shared among all instances of the class and can be accessed using
the class name.
Output
Rohan's average salary:125000
Constant Variables
In C#, a constant variable is a value that cannot be changed once it's defined. It's
declared using the 'const' keyword and must be initialized at the time of
declaration. Constants are typically used for values that should remain fixed
throughout the program, such as mathematical constants or configuration
settings, providing improved code readability and preventing accidental
modification.
Example
using System;
class Program
{

const float max;


public static void Main()
{
Program obj = new Program();
[Link]("The value of b is = " +
Program.b);
}
}

.NET PROGRAMMING Page 62


UNIT I

Explanation
This C# program in the C# Editor attempts to declare a constant variable "max"
of type float without providing an initial value. However, this will result in a
compilation error because constant variables must have a defined value at the
time of declaration. Additionally, it attempts to access an undefined constant
"b," which will also result in an error.
Output
The provided C# code has a compilation error because you cannot declare a
constant variable without initializing it with a value.
Read-only Variables
In C#, read-only variables are declared using the "readonly" keyword. They can
only be assigned a value at the time of declaration or within a constructor. Once
assigned, their value cannot be changed throughout the program's execution,
ensuring data integrity and immutability. This is useful for constants and values
that should not be modified after initialization.
Example
using System;
class Program
{
int a = 80;
static int b = 40;
const float max = 50;

readonly int k;

public static void Main()


{
Program obj = new Program();

[Link]("The value of a is = " + obj.a);


[Link]("The value of b is = " + Program.b);
[Link]("The value of max is = " +
[Link]); [Link]("The value of k is = " +
obj.k);
}
}

.NET PROGRAMMING Page 63


UNIT I

Explanation
This C# program demonstrates the use of instance variables (a), static variables
(b), constant variables (max), and readonly variables (k). It initializes a, b, and
max but doesn't initialize k, which is allowed for readonly variables. The
program then prints the values of these variables.
Output
The value of a is = 80
The value of b is = 40
The value of max is = 50
The value of k is = 0

1.13 OPERATORS
Operators allow us to perform different kinds of operations on operands.
In C#, operators Can be categorized based upon their different functionality :
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Conditional Operator
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.

.NET PROGRAMMING Page 64


UNIT I

1. Arithmetic Operators
These are used to perform arithmetic/mathematical operations on operands. The
Binary Operators falling in this category are :
 Addition: The ‘+’ operator adds two operands. For example, x+y.
 Subtraction: The ‘-‘ operator subtracts two operands. For example, x-y.
 Multiplication: The ‘*’ operator multiplies two operands. For
example, x*y.
 Division: The ‘/’ operator divides the first operand by the second. For
example, x/y.
 Modulus: The ‘%’ operator returns the remainder when first operand is
divided by the second. For example, x%y.
Example:
C#
// C# program to demonstrate the working
// of Binary Arithmetic Operators
using System;
namespace Arithmetic
{
class GFG
{

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

int result;
int x = 10, y = 5;

// Addition
result = (x + y);
[Link]("Addition Operator: " + result);

// Subtraction
result = (x - y);
[Link]("Subtraction Operator: " + result);

.NET PROGRAMMING Page 65


UNIT I

// Multiplication
result = (x * y);
[Link]("Multiplication Operator: "+ result);

// Division
result = (x / y);
[Link]("Division Operator: " + result);

// Modulo
result = (x % y);
[Link]("Modulo Operator: " + result);
}
}
}
Output:
Addition Operator: 15
Subtraction Operator: 5
Multiplication Operator: 50
Division Operator: 2
Modulo Operator: 0
The ones falling into the category of Unary Operators are:
 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:
C#
.NET PROGRAMMING Page 66
UNIT I

// C# program to demonstrate the working


// of Unary Arithmetic Operators
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


[Link]("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


[Link]("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


[Link]("a is {0} and res is {1}", a, res);

// pre-decrement example:
.NET PROGRAMMING Page 67
UNIT I

// res is assigned 10 only since


// a is updated here itself
res = --a;

// a and res have same values = 10


[Link]("a is {0} and res is {1}",a, res);

}
}
}
Output:
a is 11 and res is 10
a is 10 and res is 11
a is 11 and res is 11
a is 10 and res is 10

2. Relational Operators
Relational operators are used for comparison of two values. Let’s see them one
by one:
 ‘=='(Equal To) operator checks whether the two given operands are
equal or not. If so, it returns true. Otherwise it returns false. For
example, 5==5 will return true.
 ‘!='(Not Equal To) operator checks whether the two given operands are
equal or not. If not, it returns true. Otherwise it returns false. It is the
exact boolean complement of the ‘==’ operator. For example, 5!=5 will
return false.
 ‘>'(Greater Than) operator checks whether the first operand is greater
than the second operand. If so, it returns true. Otherwise it returns false.
For example, 6>5 will return true.
 ‘<‘(Less Than) operator checks whether the first operand is lesser than
the second operand. If so, it returns true. Otherwise it returns false. For
example, 6<5 will return false.
 ‘>='(Greater Than Equal To) operator checks whether the first operand
is greater than or equal to the second operand. If so, it returns true.
Otherwise it returns false. For example, 5>=5 will return true.

.NET PROGRAMMING Page 68


UNIT I

 ‘<='(Less Than Equal To) operator checks whether the first operand is
lesser than or equal to the second operand. If so, it returns true. Otherwise
it returns false. For example, 5<=5 will also return true.
Example:
C#
// C# program to demonstrate the working
// of Relational Operators
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);
[Link]("Equal to Operator: " + result);

// Greater than Operator


result = (x > y);
[Link]("Greater than Operator: " + result);

// Less than Operator


result = (x < y);
[Link]("Less than Operator: " + result);

// Greater than Equal to Operator


result = (x >= y);
[Link]("Greater than or Equal to: "+ result);

// Less than Equal to Operator


result = (x <= y);
[Link]("Lesser than or Equal to: "+ result);

// Not Equal To Operator

.NET PROGRAMMING Page 69


UNIT I

result = (x != y);
[Link]("Not Equal to Operator: " + result);
}
}
}
Output:
Equal to Operator: False
Greater than Operator: False
Less than Operator: True
Greater than or Equal to: False
Lesser than or Equal to: True
Not Equal to Operator: True

3. Logical Operators
They are used to combine two or more conditions/constraints or to complement
the evaluation of the original condition in consideration. They are described
below:
 Logical AND: The ‘&&’ operator returns true when both the conditions
in consideration are satisfied. Otherwise it returns false. For example, a
&& b returns true when both a and b are true (i.e. non-zero).
 Logical OR: The ‘||’ operator returns true when one (or both) of the
conditions in consideration is satisfied. Otherwise it returns false. For
example, a || b returns true if one of a or b is true (i.e. non-zero). Of
course, it returns true when both a and b are true.
 Logical NOT: The ‘!’ operator returns true the condition in consideration
is not satisfied. Otherwise it returns false. For example, !a returns true if a
is false, i.e. when a=0.
Example:
C#
// C# program to demonstrate the working
// of Logical Operators
using System;
namespace Logical {

class GFG {

// Main Function
static void Main(string[] args)

.NET PROGRAMMING Page 70


UNIT I

{
bool a = true,b = false, result;

// AND operator
result = a && b;
[Link]("AND Operator: " + result);

// OR operator
result = a || b;
[Link]("OR Operator: " + result);

// NOT operator
result = !a;
[Link]("NOT Operator: " + result);

}
}
}
Output:
AND Operator: False
OR Operator: True
NOT Operator: False

4. 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.
 ~ (bitwise Complement) Takes one number as operand and invert each
bits that is 1 to 0 and 0 to 1.
 << (left shift) Takes two numbers, left shifts the bits of the first operand,
the second operand decides the number of places to shift.

.NET PROGRAMMING Page 71


UNIT I

 >> (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#
// C# program to demonstrate the working
// of Bitwise Operators
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;
[Link]("Bitwise AND: " + result);

// Bitwise OR Operator
result = x | y;
[Link]("Bitwise OR: " + result);

// Bitwise XOR Operator


result = x ^ y;
[Link]("Bitwise XOR: " + result);

// Bitwise Complement Operator


result = ~x;
[Link]("Bitwise Complement: " + result);

// Bitwise LEFT SHIFT Operator


result = x << 2;
[Link]("Bitwise Left Shift: " + result);

// Bitwise RIGHT SHIFT Operator


result = x >> 2;
[Link]("Bitwise Right Shift: " + result);

.NET PROGRAMMING Page 72


UNIT I

}
}
}
Output:
Bitwise AND: 0
Bitwise OR: 15
Bitwise XOR: 15
Bitwise Complement: -6
Bitwise Left Shift: 20
Bitwise Right Shift: 1

5. Assignment Operators
Assignment operators are used to assigning a value to a variable. The left side
operand of the assignment operator is a variable and right side operand of the
assignment operator is a value. The value on the right side must be of the same
data-type of the variable on the left side otherwise the compiler will raise an
error.
Different types of assignment operators are shown below:
 “=”(Simple Assignment): This is the simplest assignment operator. This
operator is used to assign the value on the right to the variable on the left.
Example:
a = 10;
b = 20;
ch = 'y';
 “+=”(Add Assignment): This operator is combination of ‘+’ and ‘=’
operators. This operator first adds the current value of the variable on left
to the value on the right and then assigns the result to the variable on the
left.
Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
 “-=”(Subtract Assignment): This operator is combination of ‘-‘ and ‘=’
operators. This operator first subtracts the current value of the variable on
left from the value on the right and then assigns the result to the variable

.NET PROGRAMMING Page 73


UNIT I

on the left. Example:


(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
 “*=”(Multiply Assignment): This operator is combination of ‘*’ and ‘=’
operators. This operator first multiplies the current value of the variable
on left to the value on the right and then assigns the result to the variable
on the left.
Example:
(a *= b) can be written as (a = a * b)
If initially value stored in a is 5. Then (a *= 6) = 30.
 “/=”(Division Assignment): This operator is combination of ‘/’ and ‘=’
operators. This operator first divides the current value of the variable on
left by the value on the right and then assigns the result to the variable on
the left.
Example:
(a /= b) can be written as (a = a / b)
If initially value stored in a is 6. Then (a /= 2) = 3.
 “%=”(Modulus Assignment): This operator is combination of ‘%’ and
‘=’ operators. This operator first modulo the current value of the variable
on left by the value on the right and then assigns the result to the variable
on the left.
Example:
(a %= b) can be written as (a = a % b)
If initially value stored in a is 6. Then (a %= 2) = 0.
 “<<=”(Left Shift Assignment) : This operator is combination of ‘<<‘
and ‘=’ operators. This operator first Left shift the current value of the
variable on left by the value on the right and then assigns the result to the
variable on the left.
Example:
(a <<= 2) can be written as (a = a << 2)
If initially value stored in a is 6. Then (a <<= 2) = 24.

.NET PROGRAMMING Page 74


UNIT I

 “>>=”(Right Shift Assignment) : This operator is combination of ‘>>’


and ‘=’ operators. This operator first Right shift the current value of the
variable on left by the value on the right and then assigns the result to the
variable on the left.
Example:
(a >>= 2) can be written as (a = a >> 2)
If initially value stored in a is 6. Then (a >>= 2) = 1.
 “&=”(Bitwise AND Assignment): This operator is combination of ‘&’
and ‘=’ operators. This operator first “Bitwise AND” the current value of
the variable on the left by the value on the right and then assigns the
result to the variable on the left.
Example:
(a &= 2) can be written as (a = a & 2)
If initially value stored in a is 6. Then (a &= 2) = 2.
 “^=”(Bitwise Exclusive OR): This operator is combination of ‘^’ and ‘=’
operators. This operator first “Bitwise Exclusive OR” the current value of
the variable on left by the value on the right and then assigns the result to
the variable on the left.
Example:
(a ^= 2) can be written as (a = a ^ 2)
If initially value stored in a is 6. Then (a ^= 2) = 4.
 “|=”(Bitwise Inclusive OR) : This operator is combination of ‘|’ and ‘=’
operators. This operator first “Bitwise Inclusive OR” the current value of
the variable on left by the value on the right and then assigns the result to
the variable on the left.
Example :
(a |= 2) can be written as (a = a | 2)
If initially, value stored in a is 6. Then (a |= 2) = 6.
Example:
C#
// C# program to demonstrate the working
// of Assignment Operators
using System;
namespace Assignment
{
.NET PROGRAMMING Page 75
UNIT I

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;
[Link]("Add Assignment Operator: " + x);

// initialize variable x again


x = 20;

// it means x = x - 5
x -= 5;
[Link]("Subtract Assignment Operator: " + x);

// initialize variable x again


x = 15;

// it means x = x * 5
x *= 5;
[Link]("Multiply Assignment Operator: " + x);

// initialize variable x again


x = 25;

// it means x = x / 5
x /= 5;
[Link]("Division Assignment Operator: " + x);

// initialize variable x again


x = 25;

.NET PROGRAMMING Page 76


UNIT I

// it means x = x % 5
x %= 5;
[Link]("Modulo Assignment Operator: " + x);

// initialize variable x again


x = 8;

// it means x = x << 2
x <<= 2;
[Link]("Left Shift Assignment Operator: " + x);

// initialize variable x again


x = 8;

// it means x = x >> 2
x >>= 2;
[Link]("Right Shift Assignment Operator: " + x);

// initialize variable x again


x = 12;

// it means x = x >> 4
x &= 4;
[Link]("Bitwise AND Assignment Operator: " + x);

// initialize variable x again


x = 12;

// it means x = x >> 4
x ^= 4;
[Link]("Bitwise Exclusive OR Assignment Operator: " + x);

// initialize variable x again


x = 12;

// it means x = x >> 4
x |= 4;
[Link]("Bitwise Inclusive OR Assignment Operator: " + x);

}
.NET PROGRAMMING Page 77
UNIT I

}
}
Output :
Add Assignment Operator: 25
Subtract Assignment Operator: 15
Multiply Assignment Operator: 75
Division Assignment Operator: 5
Modulo Assignment Operator: 0
Left Shift Assignment Operator: 32
Right Shift Assignment Operator: 2
Bitwise AND Assignment Operator: 4
Bitwise Exclusive OR Assignment Operator: 8
Bitwise Inclusive OR Assignment Operator: 12

6. 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#
// C# program to demonstrate the working
// of Conditional Operator
using System;
namespace Conditional {

class GFG {

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

.NET PROGRAMMING Page 78


UNIT I

int x = 5, y = 10, result;

// To find which value is greater


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

// To display the result


[Link]("Result: " + result);

// To find which value is greater


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

// To display the result


[Link]("Result: " + result);
}
}
}
Output :
Result: 10
Result: 5

.NET PROGRAMMING Page 79


UNIT II

UNIT II
PROGRAM CONTROL STATEMENTS
2.1 IF STATEMENTS
if Statement
C# if-then statement will execute a block of code if the given condition is true.
The syntax of if-then statement in C# is:
if (boolean-expression)
{
// statements executed if boolean-expression is true
}
 The boolean-expression will return either true or false.
 If the boolean-expression returns true, the statements inside the body of if
( inside {...} ) will be executed.
 If the boolean-expression returns false, the statements inside the body of
if will be ignored.

Example 1: C# if Statement
using System;

namespace Conditional
{
class IfStatement
{
public static void Main(string[] args)
{
int number = 2;
if (number < 5)
{

.NET PROGRAMMING Page 80


UNIT II

[Link]("hii”);
}

[Link]("This statement is always executed.");


}
}
}

The output will be:


hiii
This statement is always executed.
The value of number is initialized to 2. So the expression number < 5 is
evaluated to true. Hence, the code inside the if block are executed. The code
after the if statement will always be executed irrespective to the expression.
Now, change the value of number to something greater than 5, say 10. When we
run the program the output will be:
This statement is always executed.
if...else Statement
The if statement in C# may have an optional else statement. The block of code
inside the else statement will be executed if the expression is evaluated to false.
The syntax of if...else statement
if (boolean-expression)
{
// statements executed if boolean-expression is true
}
else
{
// statements executed if boolean-expression is false
}

.NET PROGRAMMING Page 81


UNIT II

Example 2: C# if...else Statement


using System;
namespace Conditional
{
class IfElseStatement
{
public static void Main(string[] args)
{
int number = 12;

if (number < 5)
{
[Link](“hii);
}
else
{
[Link]("hello”);
}

[Link]("This statement is always executed.");


} } }
The output will be:
hii
This statement is always executed

.NET PROGRAMMING Page 82


UNIT II

Here, the value of number is initialized to 12. So the expression number < 5 is
evaluated to false. Hence, the code inside the else block are executed. The code
after the if..else statement will always be executed irrespective to the
expression.
if...else if Statement
When we have only one condition to test, if-then and if-then-else statement
works fine. But what if we have a multiple condition to test and execute one of
the many block of code.
For such case, we can use if..else if statement in C#. The syntax for if...else if
statement is:
if (boolean-expression-1)
{
// statements executed if boolean-expression-1 is true
}
else if (boolean-expression-2)
{
// statements executed if boolean-expression-2 is true
}
else if (boolean-expression-3)
{
// statements executed if boolean-expression-3 is true
}
.
.
.
else
{
// statements executed if all above expressions are false
}
The if...else if statement is executed from the top to bottom. As soon as a test
expression is true, the code inside of that if ( or else if ) block is executed. Then
the control jumps out of the if...else if block.
If none of the expression is true, the code inside the else block is executed.
Example 3: C# if...else if Statement
using System;

namespace Conditional

.NET PROGRAMMING Page 83


UNIT II

{
class IfElseIfStatement
{
public static void Main(string[] args)
{
int number = 12;

if (number < 5)
{
[Link]("{0} is less than 5", number);
}
else if (number > 5)
{
[Link]("{0} is greater than 5", number);
}
else
{
[Link]("{0} is equal to 5");
}
}
}
}
When we run the program, the output will be:
12 is greater than 5
The value of number is initialized to 12. The first test expression number <
5 is false, so the control will move to the else if block. The test
expression number > 5 is true hence the block of code inside else if will be
executed.
Similarly, we can change the value of number to alter the flow of execution.
Nested if...else Statement
An if...else statement can exist within another if...else statement. Such
statements are called nested if...else statement.
The general structure of nested if…else statement is:
if (boolean-expression)
{
if (nested-expression-1)
{

.NET PROGRAMMING Page 84


UNIT II

// code to be executed
}
else
{
// code to be executed
}
}
else
{
if (nested-expression-2)
{
// code to be executed
}
else
{
// code to be executed
}
}
Nested if statements are generally used when we have to test one condition
followed by another. In a nested if statement, if the outer if statement returns
true, it enters the body to check the inner if statement.
Example 4: Nested if...else Statement
The following program computes the largest number among 3 numbers using
nested if...else statement.
using System;

namespace Conditional
{
class Nested
{
public static void Main(string[] args)
{
int first = 7, second = -23, third = 13;
if (first > second)
{
if (firstNumber > third)
{
[Link]("{0} is the largest", first);
}
.NET PROGRAMMING Page 85
UNIT II

else
{
[Link]("{0} is the largest", third);
}
}
else
{
if (second > third)
{
[Link]("{0} is the largest",
second);
}
else
{
[Link]("{0} is the largest", third);
}
}
}
}
}
When we run the program, the output will be:
13 is the largest

2.2 SWITCH STATEMENT


 In C#, Switch statement is a multiway branch statement.
 It provides an efficient way to transfer the execution to different parts of
a code based on the value of the expression.
 The switch expression is of integer type such as int, char, byte, or short,
or of an enumeration type, or of string type.
 The expression is checked for different cases and the one match is
executed.
Syntax:
switch (expression) {

case value1: // statement sequence


break;

.NET PROGRAMMING Page 86


UNIT II

case value2: // statement sequence


break;
.
.
.
case valueN: // statement sequence
break;

default: // default statement sequence


}
Flow Chart:

Important points to remember:


 In C#, duplicate case values are not allowed.
 The data type of the variable in the switch and value of a case must be of
the same type.

.NET PROGRAMMING Page 87


UNIT II

 The value of a case must be a constant or a literal. Variables are not


allowed.
 The break in switch statement is used to terminate the current sequence.
 The default statement is optional and it can be used anywhere inside the
switch statement.
 Multiple default statements are not allowed.
Example:

// C# program to illustrate
// switch case statement
using System;

public class GFG {

// Main Method
public static void Main(String[] args)
{
int nitem = 5;
switch (nitem) {

case 1:
[Link]("case 1");
break;

case 5:
[Link]("case 5");
break;

case 9:
[Link]("case 9");
break;

default:
[Link]("No match
found"); break;
}
}

.NET PROGRAMMING Page 88


UNIT II

}
Output:
case 5

2.3 FOR LOOP


Looping in a programming language is a way to execute a statement or a set of
statements multiple times depending on the result of the condition to be
evaluated to execute statements. The result condition should be true to execute
statements within loops.
Loops are mainly divided into two categories:
1. Entry Controlled Loops
2. Exit Controlled Loops
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.
1. 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...
}
Flowchart:

.NET PROGRAMMING Page 89


UNIT II

Example:
csharp
// C# program to illustrate while loop
using System;

class whileLoopDemo
{
public static void Main()
{
int x = 1;

// Exit when x becomes greater than 4


while (x <= 4)
{
[Link]("GeeksforGeeks");

// Increment the value of x for


// next iteration
x++;
}
}
}
Output:
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks

.NET PROGRAMMING Page 90


UNIT II

2. for loop
for loop has similar functionality as while loop but with different syntax. 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.
for (loop variable initialization ; testing condition;
increment / decrement)
{
// statements to be executed
}

1.
1. Initialization of loop variable: Th expression / variable controlling the loop
is initialized here. It is the starting point of for loop. An already declared
variable can be used or a variable can be declared, local to loop only.
2. Testing Condition: The testing condition to execute statements of loop. It is
used for testing the exit condition for a loop. It must return a boolean value true
or false. When the condition became false the control will be out from the loop
and for loop ends.
3. Increment / Decrement: The loop variable is incremented/decremented
according to the requirement and the control then shifts to the testing condition
again.
Note: Initialization part is evaluated only once when the for loop starts.

.NET PROGRAMMING Page 91


UNIT II

Example:
csharp
// C# program to illustrate for loop.
using System;

class forLoopDemo
{
public static void Main()
{
// for loop begins when x=1
// and runs till x <= 4
for (int x = 1; x <= 4; x++)
[Link]("GeeksforGeeks");
}
}
Output:
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks

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.
1. 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.
Syntax :
do
{
statements..
}while (condition);

.NET PROGRAMMING Page 92


UNIT II

Flowchart:

Example:
csharp
// C# program to illustrate do-while loop
using System;

class dowhileloopDemo
{
public static void Main()
{
int x = 21;
do
{
// The line will be printed even
// if the condition is false
[Link]("GeeksforGeeks"); x+
+;
}
while (x < 20);
}
}
Output:
GeeksforGeeks

Infinite Loops:
The loops in which the test condition does not evaluate false ever tend to
execute statements forever until an external force is used to end it and thus they
are known as infinite loops.

.NET PROGRAMMING Page 93


UNIT II

Example:
csharp
// C# program to demonstrate infinite loop
using System;

class infiniteLoop
{
public static void Main()
{
// The statement will be printed
// infinite times
for(;;)
[Link]("This is printed infinite times");
}
}
Output:
This is printed infinite times
This is printed infinite times
This is printed infinite times
This is printed infinite times
This is printed infinite times
This is printed infinite times
This is printed infinite times
..........

Nested Loops: When loops are present inside the other loops, it is known as
nested loops.
Example:
csharp
// C# program to demonstrate nested loops
using System;

class nestedLoops
{
public static void Main()
{
// loop within loop printing GeeksforGeeks
for (int i = 2; i < 3; i++)
for (int j = 1; j < i; j++)

.NET PROGRAMMING Page 94


UNIT II

[Link]("GeeksforGeeks");
}
}
Output:
GeeksforGeeks

2.4 FOREACH LOOP


Looping in a programming language is a way to execute a statement or a set of
statements multiple numbers of times depending on the result of a condition to
be evaluated.
The resulting condition should be true to execute statements within loops.
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.
Syntax:
foreach(data_type var_name in collection_variable)
{
// statements to be executed
}
Flowchart:

.NET PROGRAMMING Page 95


UNIT II

Example 1:

// C# program to illustrate the


// use of foreach loop
using System;

class GFG {

// Main Method
static public void Main()
{

[Link]("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)

.NET PROGRAMMING Page 96


UNIT II

{
[Link](items);
}
}
}
Output:
Print array:
1
2
3
4
5
6
7
Explanation: foreach loop in above program is equivalent to:
for(int items = 0; items < a_array.Length; items++)
{
[Link](a_array[items]);
}

2.5 CONTINUE ,BREAK AND GOTO


In C#, Jump statements are used to transfer control from one point to another
point in the program due to some specified code while executing the program.
There are five keywords in the Jump Statements:
 break
 continue
 goto
 return
 throw

break statement
The break statement is used to terminate the loop or statement in which it
present. After that, the control will pass to the statements that present after the

.NET PROGRAMMING Page 97


UNIT II

break statement, if available. If the break statement present in the nested loop,
then it terminates only those loops which contains break statement.
Flowchart:

Example:

// C# program to illustrate the


// use of break statement
using System;

class Geeks {

// Main Method
static public void Main()
{

// GeeksforGeeks is printed only 2 times


// because of break statement
for (int i = 1; i < 4; i++)
{
if (i == 3)
break;

[Link]("GeeksforGeeks");
}
}
}
Output:

.NET PROGRAMMING Page 98


UNIT II

GeeksforGeeks
GeeksforGeeks

continue statement
This statement is used to skip over the execution part of the loop on a certain
condition. After that, it transfers the control to the beginning of the loop.
Basically, it skips its following statements and continues with the next iteration
of the loop.

Example:
// C# program to illustrate the
// use of continue statement
using System;

class Geeks {

// Main Method
public static void Main()
{

// This will skip 4 to print


for (int i = 1; i <= 10; i++) {

// if the value of i becomes 4 then


// it will skip 4 and send the

.NET PROGRAMMING Page 99


UNIT II

// transfer to the for loop and


// continue with 5
if (i == 4)
continue;

[Link](i);
}
}
}

Output:
1
2
3
5
6
7
8
9
10

goto statement
This statement is used to transfer control to the labeled statement in the
program. The label is the valid identifier and placed just before the statement
from where the control is transferred.

.NET PROGRAMMING Page


100
UNIT II

Example:
// C# program to illustrate the
// use of goto statement
using System;

class Geeks {

// Main Method
static public void Main()
{
int number = 20;
switch (number) {

case 5:
[Link]("case 5");
break;
case 10:
[Link]("case 10");
break;
case 20:
[Link]("case 20");

// goto statement transfer


// the control to case 5
goto case 5;

default:
[Link]("No match found");

}
}
}

Output:
case 20
case 5

.NET PROGRAMMING Page


101
UNIT II

return statement
This statement terminates the execution of the method and returns the control to
the calling method. It returns an optional value. If the type of method is void,
then the return statement can be excluded.
Example:
// C# program to illustrate the
// use of return statement
using System;

class Geeks {

// creating simple addition function


static int Addition(int a)
{

// add two value and


// return the result of addition
int add = a + a;

// using return statement


return add;
}

// Main Method
static public void Main()
{
int number = 2;

// calling addition function


int result = Addition(number);
[Link]("The addition is {0}", result);
}
}

Output:
The addition is 4

.NET PROGRAMMING Page


102
UNIT II

INTRODUCING CLASSES AND OBJECTS


2.6 CLASS AND OBJECTS
Class and Object are the basic concepts of Object-Oriented Programming which
revolve around the real-life entities.
A class is a user-defined blueprint or prototype from which objects are created.
Basically, a class combines the fields and methods(member function which
defines actions) into a single unit.
In C#, classes support polymorphism, inheritance and also provide the concept
of derived classes and base classes.
Declaration of class
Generally, a class declaration contains only a keyword class, followed by
an identifier(name) of the class. But there are some optional attributes that can
be used with class declaration according to the application requirement. In
general, class declarations can include these components, in order:
 Modifiers: A class can be public or internal etc. By default modifier of
the class is internal.
 Keyword class: A class keyword is used to declare the type class.
 Class Identifier: The variable of type class is provided. The identifier(or
name of the class) should begin with an initial letter which should be
capitalized by convention.
 Base class or Super class: The name of the class’s parent (superclass), if
any, preceded by the : (colon). This is optional.
 Interfaces: A comma-separated list of interfaces implemented by the
class, if any, preceded by the : (colon). A class can implement more than
one interface. This is optional.
 Body: The class body is surrounded by { } (curly braces).
Constructors in class are used for initializing new objects. Fields are variables
that provide the state of the class and its objects, and methods are used to
implement the behavior of the class and its objects.

Example:
// declaring public class
public class Geeks
{
.NET PROGRAMMING Page
103
UNIT II

// field variable
public int a, b;

// member function or method


public void display()
{
[Link](“Class & Objects in C#”);
}
}
Objects
It is a basic unit of Object-Oriented Programming and represents real-life
entities. A typical C# program creates many objects, which as you know,
interact by invoking methods. An object consists of :
 State: It is represented by attributes of an object. It also reflects the
properties of an object.
 Behavior: It is represented by the methods of an object. It also reflects
the response of an object with other objects.
 Identity: It gives a unique name to an object and enables one object to
interact with other objects.
Consider Dog as an object and see the below diagram for its identity, state, and
behavior.

Objects correspond to things found in the real world. For example, a graphics
program may have objects such as “circle”, “square”, “menu”. An online
shopping system might have objects such as “shopping cart”, “customer”, and
“product”.

Declaring Objects (Also called instantiating a class)

.NET PROGRAMMING Page


104
UNIT II

When an object of a class is created, the class is said to be instantiated. All the
instances share the attributes and the behavior of the class. But the values of
those attributes, i.e. the state are unique for each object. A single class may have
any number of instances.
Example:

As we declare variables like (type name;). This notifies the compiler that we
will use the name to refer to data whose type is type. With a primitive variable,
this declaration also reserves the proper amount of memory for the variable. So
for reference variable, the type must be strictly a concrete class name.
Dog tuffy;
If we declare a reference variable(tuffy) like this, its value will be
undetermined(null) until an object is actually created and assigned to it. Simply
declaring a reference variable does not create an object.

Initializing an object
The new operator instantiates a class by allocating memory for a new object and
returning a reference to that memory. The new operator also invokes the class
constructor.
Example:

// C# program to illustrate the


// Initialization of an object
using System;

// Class Declaration

.NET PROGRAMMING Page


105
UNIT II

public class Dog {

// Instance Variables
String name;
String breed;
int age;
String color;

// Constructor Declaration of Class


public Dog(String name, String breed,
int age, String color)
{
[Link] = name;
[Link] = breed;
[Link] = age;
[Link] = color;
}

// Property 1
public String GetName()
{
return name;
}

// Property 2
public String GetBreed()
{
return breed;
}

// Property 3
public int GetAge()
{
return age;
}

// Property 4
public String GetColor()
{

.NET PROGRAMMING Page


106
UNIT II

return color;
}

// Method 1
public String ToString()
{
return ("Hi my name is " + [Link]()
+ ".\nMy breed, age and color are " +
[Link]()
+ ", " + [Link]() + ", " + [Link]());
}

// Main Method
public static void Main(String[] args)
{

// Creating object
Dog tuffy = new Dog("tuffy", "papillon", 5, "white");
[Link]([Link]());
}
}
Output:
Hi my name is tuffy.
My breed, age and color are papillon, 5, white

Explanation: This class contains a single constructor. We can recognize a


constructor because its declaration uses the same name as the class and it has no
return type. The C# compiler differentiates the constructors based on the
number and the type of the arguments. The constructor in the Dog class takes
four arguments. The following statement provides “tuffy”, ”papillon”, 5,
”white” as values for those arguments:
Dog tuffy = new Dog("tuffy", "papillon", 5, "white");
The result of executing this statement can be illustrated as :

.NET PROGRAMMING Page


107
UNIT II

2.7 METHODS
Methods are generally the block of codes or statements in a program that gives
the user the ability to reuse the same code which ultimately saves the excessive
use of memory, acts as a time saver and more importantly, it provides a
better readability of code. So basically, a method is a collection of statements
that perform some specific task and return the result to the caller. A method can
also perform some specific task without returning anything.
Declaring a Method in C#
Here's the syntax to declare a method in C#.
returnType methodName()
{
// method body
}
Here,
 returnType - It specifies what type of value a method returns. For
example, if a method has an int return type then it returns an int value.
If the method does not return a value, its return type is void.
 methodName - It is an identifier that is used to refer to the particular
method in a program.
 method body - It includes the programming statements that are used to
perform some tasks. The method body is enclosed inside the curly
braces { }
Let's see an
example, void
display() {
// code
}
.NET PROGRAMMING Page
108
UNIT II

Here, the name of the method is display(). And, the return type is void.
Calling a Method in C#
In the above example, we have declared a method named display(). Now, to use
the method, we need to call it.
Here's how we can call the display() method.
// calls the method
display();

Working of C# method call


Example: C# Method
using System;

namespace Method

{ class Program {

// method declaration
public void display() {
[Link]("Hello World");
}

static void Main(string[] args) {

// create class object


Program p1 = new Program();

//call method
[Link]();

[Link]();

.NET PROGRAMMING Page


109
UNIT II

}
}
}
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,
[Link]();
Here, we are using the object to call the display() method.
C# Method Return Type
A C# method may or may not return a value. If the method doesn't return any
value, we use the void keyword (shown in the above example).
If the method returns any value, we use the return statement to return any value.
For example,
int addNumbers() {
...
return sum;
}
Here, we are returning the variable sum. One thing you should always
remember is that the return type of the method and the returned value should be
of the same type.
In our code, the return type is int. Hence, the data type of sum should be
of int as well.
Example: Method Return Type
using System;

namespace Method

{ class Program {

// method declaration
static int addNumbers() {

.NET PROGRAMMING Page


110
UNIT II

int sum = 5 + 14;


return sum;

static void Main(string[] args) {

// call method
int sum = addNumbers();

[Link](sum);

[Link]();

}
}
}
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.
C# Methods Parameters
In C#, we can also create a method that accepts some value. These values are
called method parameters. For example,
int addNumber(int a, int b) {
//code
}
Here, a and b are two parameters passed to the addNumber() function.

.NET PROGRAMMING Page


111
UNIT II

If a method is created with parameters, we need to pass the corresponding


values(arguments) while calling the method. For example,
// call the method
addNumber(100, 100);

Representation of the C# method returning a value


Here, We have passed 2 arguments (100, 100).
Example 1: C# Methods with Parameters
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();

.NET PROGRAMMING Page


112
UNIT II

//call method
int sum = [Link](100,100);

[Link]("Sum: " + sum);

[Link]();

}
}
}
Output
Sum: 200

C# Methods with Single Parameter


In C#, we can also create a method with a single parameter. For example,
using System;

namespace Method
{ class Program {

string work(string work)


{ return work;

}
static void Main(string[] args) {

// create class object


Program p1 = new Program();

//call method
string work = [Link]("Cleaning"); ;

[Link]("Work: " +

work); [Link]();

.NET PROGRAMMING Page


113
UNIT II

}
}
Output
Work: Cleaning
Here, the work() method has a single parameter work.
Built-in methods
So far we have defined our own methods. These are called user-defined
methods.
However, in C#, there are various methods that can be directly used in our
program. They are called built-in methods. For example,
 Sqrt() - computes the square root of a number
 ToUpper() - converts a string to uppercase
Example: [Link]() Method
using System;

namespace Method

{ class Program {
static void Main(string[] args) {

// Built in method
double a =
[Link](9);
[Link]("Square root of 9: " + a);
}
}
}
Output
Square root of 9: 3
In the above program, we have used
double a = [Link](9);
to compute the square root of 9. Here, the Sqrt() is a built-in method that is
defined inside the Math class.
We can simply use built-in methods in our program without writing the method
definition. To learn more, visit C# built-in methods.
Method Overloading in C#

.NET PROGRAMMING Page


114
UNIT II

In C#, we can create two or more methods with the same name. It is known as
method overloading. For example,
using System;
namespace MethodOverload

{ class Program {

// method with one parameter


void display(int a) {
[Link]("Arguments: " + a);
}

// method with two parameters


void display(int a, int b) {
[Link]("Arguments: " + a + " and " + b);
}
static void Main(string[] args) {

Program p1 = new Program();


[Link](100);
[Link](100, 200);
[Link]();
}
}
}
Output
Arguments: 100
Arguments: 100 and 200
In the above example, we have overloaded the display() method. It is possible
because:
 one method has one parameter

 another has two parameter


2.8 CONSTRUCTORS
In C#, a constructor is similar to a method that is invoked when an object of the
class is created.
However, unlike methods, a constructor:
 has the same name as that of the class

.NET PROGRAMMING Page


115
UNIT II

 does not have any return type


Create a C# constructor
Here's how we create a constructor in C#
class Car {

// constructor
Car() {
//code
}

}
Here, Car() is a constructor. It has the same name as its class.
Call a constructor
Once we create a constructor, we can call it using the new keyword. For
example,
new Car();
In C#, a constructor is called when we try to create an object of a class. For
example,
Car car1 = new Car();
Here, we are calling the Car() constructor to create an object car1. To learn more
about objects, visit C# Class and Objects.
Types of Constructors
There are the following types of constructors:
 Parameterless Constructor
 Parameterized Constructor
 Default Constructor
1. Parameterless Constructor
When we create a constructor without parameters, it is known as a
parameterless constructor. For example,
using System;

namespace Constructor {

.NET PROGRAMMING Page


116
UNIT II

class Car {

// parameterless constructor
Car() {
[Link]("Car Constructor");
}

static void Main(string[] args) {

// call constructor
new Car();
[Link]();

}
}
}
Output
Car Constructor
In the above example, we have created a constructor named Car().
new Car();
We can call a constructor by adding a new keyword to the constructor name.
2. C# Parameterized Constructor
In C#, a constructor can also accept parameters. It is called a parameterized
constructor. For example,
using System;

namespace Constructor {

class Car {

string brand;
int price;

// parameterized constructor
Car(string theBrand, int thePrice) {

brand = theBrand;

.NET PROGRAMMING Page


117
UNIT II

price = thePrice;
}

static void Main(string[] args) {

// call parameterized constructor


Car car1 = new Car("Bugatti", 50000);

[Link]("Brand: " + [Link]);


[Link]("Price: " + [Link]);
[Link]();

}
}
}
Output
Brand: Bugatti
Price: 50000
In the above example, we have created a constructor named Car(). The
constructor takes two parameters: theBrand and thePrice.
Notice the statement,
Car car1 = new Car("Bugatti", 50000);
Here, we are passing the two values to the constructor.
The values passed to the constructor are called arguments. We must pass the
same number and type of values as parameters.
3. Default Constructor
If we have not defined a constructor in our class, then the C# will automatically
create a default constructor with an empty code and no parameters. For
example,
using System;

namespace Constructor {

class Program {

int a;

.NET PROGRAMMING Page


118
UNIT II

static void Main(string[] args) {

// call default constructor


Program p1 = new Program();

[Link]("Default value of a: " + p1.a);


[Link]();

}
}
}
Output
Default value of a: 0
In the above example, we have not created any constructor in the Program class.
However, while creating an object, we are calling the constructor.
Program p1 = new Program();
Here, C# automatically creates a default constructor. The default constructor
initializes any uninitialized variable with the default value.
Hence, we get 0 as the value of the int variable a.
2.9 GARBAGE COLLECTION AND DESTRUCTORS
 A destructor is a method that which is called when a class object is no
longer required and is ready for grabage collection.
 The destructor function is preceded with a ~ (tilde) operator/symbol and
it has the same name as the class.
 The primary purpose of destructor method is to deallocate/destroy the
object or instance of classes.
 It is also known as Finalizer in C#
programming. Properties of a Destructor:
1. Destructor name must start with ~ (tilde) and must have the same name as
the class.
2. Destructor method is used in a class only and no more than one destructor
is allowed in a class.
3. Destructor can't be defined for a Structure.
4. Destructor method can neither be inherited nor overloaded.
5. Destructor method can neither have an access modifier nor parameters.

.NET PROGRAMMING Page


119
UNIT II

6. Destructor method has no return type.


7. Destructor method can't be called, it automatically gets invoked.
Example,
using System;

namespace Studytonight
{
public class Student
{
public Student()
{
[Link]("Default Constructor");
}
// the destructor
~Student()
{
[Link]("This is the destructor");
}
}

public class Program


{
public static void Main(string[] args)
{
Student s1 = new Student();
}
}
}

In the code above we have defined a destructor method for our class Student.
In C#, destructor (finalizer) is used to destroy objects of class when the
scope of an object ends. It has the same name as the class and starts with a
tilde ~. For example,

class Test {

.NET PROGRAMMING Page


120
UNIT II

...
//destructor
~Test() {
...
}
}
Here, ~Test() is the destructor.

Example 1: Working of C# Destructor


using System;
namespace CsharpDestructor {

class Person {

public Person() {
[Link]("Constructor called.");
}

// destructor
~Person() {
[Link]("Destructor called.");
}

public static void Main(string [] args) {

//creates object of Person


Person p1 = new Person();
}
}
}
Output
Constructor called.
Destructor called.
In the above example, we have created a destructor ~Person inside
the Person class.

.NET PROGRAMMING Page


121
UNIT II

When we create an object of the Person class, the constructor is called. After the
scope of the object ends, object p1 is no longer needed. So, the destructor is
called implicitly which destroys object p1.
Example 2: C# Destructor
using System;
namespace CsharpDestructor {

class Person {

string name;

void getName()
{ [Link]("Name: " +
name);
}

// destructor
~Person() {
[Link]("Destructor called.");
}

public static void Main(string [] args) {

// creates object of Person


Person p1 = new Person();

[Link] = "Ed Sheeran";


[Link]();
}
}
}
Output
Name: Ed Sheeran
Destructor called.

Features of Destructors
There are some important features of the C# destructor. They are as follows:
 We can only have one destructor in a class.

.NET PROGRAMMING Page


122
UNIT II

 A destructor cannot have access modifiers, parameters, or return types.


 A destructor is called implicitly by the Garbage collector of the .NET
Framework.
 We cannot overload or inherit destructors.
 We cannot define destructors in structs.
2.10 EXCEPTION HANDLING
An exception is defined as an event that occurs during the execution of a program
that is unexpected by the program code. The actions to be performed in case of
occurrence of an exception is not known to the program. In such a case, we
create an exception object and call the exception handler code.

Keyword Definition

Used to define a try block. This block holds the code that may
try throw an exception.

Used to define a catch block. This block catches the exception


catch thrown by the try block.

Used to define the finally block. This block holds the default
finally code.

throw Used to throw an exception manually.

An exception is an unexpected event that occurs during program execution. For


example,
int divideByZero = 7 / 0;
The above code causes an exception as it is not possible to divide a number by
0.
Exceptions abnormally terminate the flow of the program instructions, we need to
handle those exceptions. Responding or handling exceptions is called
Exception Handling.

C# Exception Handling Blocks

.NET PROGRAMMING Page


123
UNIT II

C# provides built-in blocks to handle exceptions. They


are: try..catch and finally.
try…catch block
The try..catch block is used to handle exceptions in C#. Here's the syntax
of try...catch block:
try
{
// code that may raise an exception
}
catch (Exception e)
{
// code that handles the exception
}
Here, we place the code that might generate an exception inside the try block.
The try block then throws the exception to the catch block which handles the
raised exception. For example,
try
{
int num = 0;
// code that may raise an exception
int divideByZero = 7 / num;
}
catch (Exception e)
{
[Link]("Exception has occurred");
}
Here, we are trying to divide a number by zero. In this case, an exception
occurs. Hence, we have enclosed this code inside the try block. The catch block
notifies the user about the occurred exception.
Example: Exception Handling Using try…catch
using System;
class Program
{
static void Main()
{
string[] colors = { "Red", "Blue", "Green" };

.NET PROGRAMMING Page


124
UNIT II

try
{
// code that may raise an exception
[Link](colors[5]);
}
catch (IndexOutOfRangeException e)
{
[Link]("An exception occurred: " + [Link]);
}
}
}
Output
An exception occurred: Index was outside the bounds of the array.

In the above example, notice the code,


[Link](colors[5]);
try…catch…finally block
We can also use finally block with try and catch block. The finally block is
always executed whether there is an exception or not.
The syntax of the try…catch…finally block is:
try
{
// code that may raise an exception
}
catch (Exception e)
{
// code that handles the exception
}
finally
{
// this code is always executed
}

.NET PROGRAMMING Page


125
UNIT II

C# finally block
We can see in the above image that the finally block is executed in both cases.
The finally block is executed:
 after try and catch block - when exception has occurred
 after try block - when exception doesn't occur
The try..catch..finally block can be collectively used to handle exceptions.
Now let's look at an example of exception handling using try…catch…
finally.

Example: Exception Handling Using try…catch…finally block


using System;
public class Program
{
static void Main()
{
// take first int input from user
[Link]("Enter first
number:");
int firstNumber = [Link]([Link]());
// take second int input from user
[Link]("Enter second
number:");
int secondNumber = [Link]([Link]());
try
{
// code that may raise raise an exception
int divisionResult = firstNumber / secondNumber;
[Link]("Division of two numbers is: " + divisionResult);
}
// this catch block gets executed only when an exception is raised
.NET PROGRAMMING Page
126
UNIT II
catch (Exception e)
{
[Link]("An exception occurred: " + [Link]);

.NET PROGRAMMING Page


127
UNIT II

}
finally
{
// this code is always executed whether of exception occurred or not
[Link]("Sum of two numbers is: " + (firstNumber +
secondNumber));
}}}
Output
Enter first number:
8
Enter second number:
0
An exception occurred: Attempted to divide by zero.
Sum of two numbers is: 8
In the above example, we have tried to perform division and addition operations
to two int input values using try...catch…finally.
Notice the code,
try
{
// code that may raise raise an exception
int divisionResult = firstNumber / secondNumber; }
Here, we have enclosed the code that performs division operation
inside try because this code may raise the DivideByZeroException exception.
There are two cases in this program:
Case I - When exception occurs in try, the catch block is executed followed by
the finally block.
Case II - The finally block is directly executed after the try block if an
exception doesn't occur. For example, if we enter 9 and 2, exception doesn't
occur in the try block and we get the following output:
// Output when exception doesn't occur
Enter first number:
9
Enter second number:
2
Division of two numbers is: 4
Sum of two numbers is: 11

.NET PROGRAMMING Page


128
UNIT III

UNIT III
ARRAYS AND
3.1 ARRAYS STRINGS

An array is a collection of similar types of data. For example,


Suppose we need to record the age of 5 students. Instead of creating 5 separate
variables, we can simply create an array:

Elements of an Array
1. C# Array Declaration
In C#, here is how we can declare an array.
datatype[] arrayName;
Here,
 dataType - data type like int, string, char, etc
 arrayName - it is an
identifier Let's see an example,
int[] age;
Here, we have created an array named age. It can store elements of int type.
2. Array initialization in C#
In C#, we can initialize an array during the declaration. For
example, int [] numbers = {1, 2, 3, 4, 5};
Here, we have created an array named numbers and initialized it with
values 1, 2, 3, 4, and 5 inside the curly braces.
Note that we have not provided the size of the array. In this case, the C#
automatically specifies the size by counting the number of elements in the array
(i.e. 5).
.NET PROGRAMMING Page 129
UNIT III

In an array, we use an index number to determine the position of each array


element. We can use the index number to initialize an array in C#. For example,
// declare an array
int[] age = new
int[5];
//initializing array
age[0] = 12;
age[1] = 4;
age[2] = 5;
...

3. Access Array Elements


We can access the elements in the array using the index of the array. For
example,
// access element at index 2
array[2];
// access element at index 4
array[4];
Here,
 array[2] - access the 3rd element
 array[4] - access the 5th element
Example: C# Array
using System;

namespace AccessArray
{ class Program {
static void Main(string[] args) {

// create
.NET an array
PROGRAMMING Page 130
UNIT III

int[] numbers = {1, 2, 3};

//access first element


[Link]("Element in first index : " + numbers[0]);

//access second element


[Link]("Element in second index : " + numbers[1]);

//access third element


[Link]("Element in third index : " + numbers[2]);

[Link]();

}
}
}
Output
Element in first index : 1
Element in second index : 2
Element in third index : 3
In the above example, we have created an array named numbers with
elements 1, 2, 3. Here, we are using the index number to access elements of the
array.
 numbers[0] - access first element, 1

 numbers[1] - access second element, 2


 numbers[3] - access third element, 3
4. Change Array Elements
We can also change the elements of an array. To change the element, we simply
assign a new value to that particular index. For example,
using System;

namespace ChangeArray
{ class Program {
static void Main(string[] args) {

// create an array
int[] numbers = {1, 2, 3};

.NET PROGRAMMING Page 131


UNIT III

[Link]("Old Value at index 0: " + numbers[0]);

// change the value at index 0


numbers[0] = 11;

//print new value


[Link]("New Value at index 0: " + numbers[0]);

[Link]();
}
}
}
Output
Old Value at index 0: 1
New Value at index 0: 11
In the above example, the initial value at index 0 is 1. Notice the line,
//change the value at index 0
numbers[0] = 11;
Here, we are assigning a new value of 11 to the index 0. Now, the value at index
0 is changed from 1 to 11.
Types of Arrays in C#
There are three types of arrays in C#, which are
1. Single-dimensional Array in C#
2. Multi-dimensional Array in C#
3. Jagged Array in C#
1. Single-Dimensional Arrays
In C#, a single-dimensional array is a data structure that stores elements of the
same data type in a linear sequence. Each element in the array is accessed by its
index, starting from zero. Single-dimensional arrays are versatile and commonly
used for various programming tasks, providing efficient data storage and

retrieval.
Declaring Single dimensional array
int[] arr = new int[10];

.NET PROGRAMMING Page 132


UNIT III

double numbers = new double[5];


string[] names = new string[2];
Initializing Single dimensional array
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6,7,8,9,10 };
string[] names = new string[] { "Roy", "Shiv", "Tara", "Urmi", "Luna",
"Samay" };
Example
using System;
class Program
{
static void Main()
{
// Declare and initialize an array
int[] numbers = { 10, 20, 30, 40, 50 };

// Output array elements


[Link]("Array elements:");
for (int i = 0; i < [Link]; i++)
{
[Link](numbers[i]);
}
}
}

Explanation
This C# code in the C# Compiler initializes an integer array "numbers" with
values {10, 20, 30, 40, 50} and then iterates through the array using a for loop
to print each element to the console. It demonstrates basic array declaration,
initialization, and traversal in a console application.
Output
Array elements:
10
20
30

.NET PROGRAMMING Page 133


UNIT III

40
50
2. Multi-Dimensional Arrays
Multi-dimensional arrays in C# are arrays that hold data in more than one
dimension, allowing for efficient storage and manipulation of complex data
structures. Unlike one-dimensional arrays, these arrays can be thought of as
matrices or tables, providing rows and columns to organize and access elements

based on multiple indices.


Declaring Multi-dimensional Array
string[,] names = new string[5, 5];
int[,] numbers = new int[7, 8];
Multi-dimensional Array Initialization
int[,] numbers = new int[4, 3] {{2,3}, {4,5}, {6,7}};
string[,] names = new string[2, 2] {{"Urmi", "Rumi"}, {"Ram", "Bheem"}};
Example
using System;
class Program
{
static void Main()
{
// Define a 2D array
int[,] myArray = new int[3, 4] {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};

// Get the dimensions of the array


int rows = [Link](0);
int columns = [Link](1);

// Display the array elements


[Link]("Array elements:");
for (int i = 0; i < rows; i++)

.NET PROGRAMMING Page 134


UNIT III

{
for (int j = 0; j < columns; j++)
{
[Link](myArray[i, j] + " ");
}
[Link]();
}
}
}

Explanation
This code defines a 2D array called myArray with 3 rows and 4 columns. It
initializes the array with specific values. Then, it retrieves the dimensions of the
array using the GetLength method. The code then uses nested loops to iterate
over the array and prints each element on the console. The output displays the
array elements in a tabular format, with each row on a separate line.
Output
Array elements:
1234
5678
9 10 11 12
3. Jagged Array in C#
In C#, a jagged array is an array of arrays where each element can hold arrays
of different sizes. Unlike regular multi-dimensional arrays, jagged arrays allow
for flexible and uneven lengths, making them ideal for storing complex
data

structures like tables or matrices with varying row lengths.


Declaring and initializing Jagged array.
int[][] jaggedArray = new int[2][];
jaggedArray[0] = new int[4];
jaggedArray[1] = new int[6];
jaggedArray[0] = new int[] { 4, 6, 8, };

.NET PROGRAMMING Page 135


UNIT III
jaggedArray[1] = new int[] { 1, 0, 2, 4, 6 };

.NET PROGRAMMING Page 136


UNIT III

You can also initialize the array upon declaration like this:
int[][] jaggedArray = new int[][]
{
new int[] { 4, 6, 8, },
new int[] { 1, 0, 2, 4, 6 }
};
You can use the following shorthand form:
int[][] jaggedArray =
{
new int[] { 4, 6, 8, },
new int[] { 1, 0, 2, 4, 6 }
};
Let’s see the practical implementation of Jagged Arrays in the following
example:
Example
using System;class Program
{
static void Main()
{
// Create a multi-dimensional jagged array int[]
[] jaggedArray = new int[3][]
{
new int[] { 1, 2, 3 },
new int[] { 4, 5 },
new int[] { 6, 7, 8, 9 }
};

// Display the elements of the jagged array


for (int i = 0; i < [Link]; i++)
{
[Link]("Row {0}: ", i);
for (int j = 0; j < jaggedArray[i].Length; j++)
{
[Link](jaggedArray[i][j] + " ");
.NET PROGRAMMING Page 137
UNIT III

}
[Link]();
}
}
}
Explanation
This code defines a 2D array called myArray with 3 rows and 4 columns. It
initializes the array with specific values. Then, it retrieves the dimensions of the
array using the GetLength method. The code then uses nested loops to iterate
over the array and prints each element on the console. The output displays the
array elements in a tabular format, with each row on a separate line.
Output
Row0:123
Row1:45
Row2:6789
3.2 STRINGS
A string is a sequence of characters. For example, "hello" is a string containing
a sequence of characters 'h', 'e', 'l', 'l', and 'o'.
We use the string keyword to create a string.
For example,
// create a string
string str = "C# Programming";
Here, we have created a string named str and assigned the text "C#
Programming". We use double quotes to represent strings in C#.
Example: Create string in C#
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

// create string
string str1 = "C# Programming";
string str2 = "Programiz";

.NET PROGRAMMING Page 138


UNIT III

// print string
[Link](str1);
[Link](str2);

[Link]();
}
}
}
Output
C# Programming
Programiz
In the above example, we have created two strings named str1 and str2 and
printed them.
Note: A string variable in C# is not of primitive types like int, char, etc. Instead,
it is an object of the String class.
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";
[Link]("string: " + str);

// get length of str


int length = [Link];

[Link]("Length: "+

length);

[Link]();
}
.NET PROGRAMMING Page 139
UNIT III

}
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# ";
[Link]("string str1: " + str1);

// create string
string str2 = "Programming";
[Link]("string str2: " + str2);

// join two strings


string joinedString = [Link](str1, str2);

[Link]("Joined string: " + joinedString);

[Link]();
}
}
}
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 = [Link](str1, str2);

.NET PROGRAMMING Page 140


UNIT III

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 = [Link](str2);

[Link]("string str1 and str2 are equal: " +

result1);

//compare str1 and str3


Boolean result2 = [Link](str3);

[Link]("string str1 and str3 are equal: " + result2);

[Link]();
}
}
}
Output
string
In the str1 and example,
above str2 are equal: True created 3 strings named str1, str2, and str3.
we have
Here, we are using the Equals() method to check if one string is equal to
another.
.NET PROGRAMMING Page 141
UNIT III

String Escape Sequences


The escape character is used to escape some of the characters present inside a
string. In other words, we use escape sequences to insert special characters
inside the string.
Suppose we need to include double quotes inside a string.
// include double quote
string str = "This is the "String" class";
Since strings are represented by double quotes, the compiler will treat "This is
the " as the string. And the above code will cause an error.
To solve this issue, we use the escape character \" in C#. For example,
// use the escape character
string str = "This is the \"String\" class.";
Now by using \ before double quote ", we can include it in the string.
Some of the escape sequences in C# are as follows:

Escape Sequence Character Name

\' single quote

\" double quote

\\ backslash

\0 null

\n new line

\t horizontal tab

Methods of C# string
There are various string methods in C#. Some of them are as follows:

.NET PROGRAMMING Page 142


UNIT III

Methods Description

Format() returns a formatted string

Split() splits the string into substring

Substring() returns substring of a string

Compare() compares string objects

replaces the specified old character with the specified


Replace()
new character

Contains() checks whether the string contains a substring

Join() joins the given strings using the specified separator

Trim() removes any leading and trailing whitespaces

EndsWith() checks if the string ends with the given string

returns the position of the specified character in the


IndexOf()
string

Remove() returns characters from a string

ToUpper() converts the string to uppercase

ToLower() converts the string to lowercase

returns string padded with spaces or with a specified


PadLeft()
Unicode character on the left

.NET PROGRAMMING Page 143


UNIT III

returns string padded with spaces or with a specified


PadRight()
Unicode character on the right

StartsWith() checks if the string begins with the given string

ToCharArray() converts the string to a char array

LastIndexOf() returns index of the last occurrence of a specified string

3.3 FOREACH 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.
Syntax
foreach (element in iterable-item)
{
// body of foreach loop
}
Here iterable-item can be an array or a class of collection.

Working of C# foreach loop

.NET PROGRAMMING Page 144


UNIT III

The in keyword used along with foreach loop is used to iterate over the iterable-
item. The in keyword selects an item from the iterable-item on each iteration
and store it in the variable element.
On first iteration, the first item of iterable-item is stored in element. On second
iteration, the second element is selected and so on.
The number of times the foreach loop will execute is equal to the number of
elements in the array or collection.
Example: Printing array using foreach loop
using System;

namespace Loop
{
class ForEachLoop
{
public static void Main(string[] args)
{
char[] myArray = {'H','e','l','l','o'};

foreach(char ch in myArray)
{
[Link](ch);
}
}
}
}
When we run the both program, the output will be:
H
e
l
l
o
In the above program, the foreach loop iterates over the array, myArray. On first
iteration, the first element i.e. myArray[0] is selected and stored in ch.
Similarly on the last iteration, the last element i.e. myArray[4] is selected.
Inside the body of loop, the value of ch is printed.
When we look at both programs, the program that uses foreach loop is more
readable and easy to understand. This is because of its simple and expressive
syntax.
.NET PROGRAMMING Page 145
UNIT III

Hence, foreach loop is preferred over for loop when working with arrays and
collections.
METHODS AND CLASSES
3.4 ACCESS MODIFIERS
In C#, access modifiers specify the accessibility of types (classes, interfaces,
etc) and type members (fields, methods, etc). For example,
class Student

{ public string

name; private int

num;
Here,
 name - public field that can be accessed from anywhere
 num - private field can only be accessed within the Student class
Types of Access Modifiers
In C#, there are 4 basic types of access modifiers.
 public
 private
 protected
 internal
1. public access modifier
When we declare a type or type member public, it can be accessed from
anywhere. For example,
using System;
namespace MyApplication
{ class Student {
public string name = "Sheeran";

public void print() {


[Link]("Hello from Student class");
}

.NET PROGRAMMING Page 146


UNIT III

class Program {
static void Main(string[] args) {

// creating object of Student class


Student student1 = new Student();

// accessing name field and printing it


[Link]("Name: " + [Link]);

// accessing print method from Student


[Link]();
[Link]();
}
}
}
Output
Name: Sheeran
Hello from Student class

In the above example, we have created a class named Student with a


field name and a method print().
// accessing name field and printing it
[Link]("Name: " + [Link]);
// accessing print method from Student
[Link]();
Since the field and method are public, we are able to access them from
the Program class.
Note: We have used the object student1 of the Student class to access its
members. To learn more, visit the C# class and objects.
2. private access modifier
When we declare a type member with the private access modifier, it can only be
accessed within the same class or struct. For example,
using System;

.NET PROGRAMMING Page 147


UNIT III

namespace MyApplication {

class Student {
private string name = "Sheeran";

private void print() {


[Link]("Hello from Student class");
}
}

class Program {
static void Main(string[] args) {

// creating object of Student class


Student student1 = new Student();

// accessing name field and printing it


[Link]("Name: " + [Link]);

// accessing print method from Student


[Link]();

[Link]();
}
}
}
In the above example, we have created a class named Student with a
field name and a method print().
// accessing name field and printing it
[Link]("Name: " + [Link]);
// accessing print method from Student
[Link]();
Since the field and method are private, we are not able to access them from
the Program class. Here, the code will generate the following error.
Error CS0122 '[Link]' is inaccessible due to its protection level
Error CS0122 '[Link]()' is inaccessible due to its protection level

.NET PROGRAMMING Page 148


UNIT III

3. protected access modifier


When we declare a type member as protected, it can only be accessed from the
same class and its derived classes. For example,
using System;

namespace MyApplication

{ class Student {
protected string name = "Sheeran";
}

class Program {
static void Main(string[] args) {

// creating object of student class


Student student1 = new Student();

// accessing name field and printing it


[Link]("Name: " + [Link]);
[Link]();
}
}
}
In the above example, we have created a class named Student with a field name.
Since the field is protected, we are not able to access it from the Program class.
Here, the code will generate the following error.
Error CS0122 '[Link]' is inaccessible due to its protection
level Now, let's try to access the protected member from a derived class.
using System;
namespace MyApplication {

class Student {
protected string name = "Sheeran";
}

// derived class
class Program : Student {

.NET PROGRAMMING Page 149


UNIT III

static void Main(string[] args) {

// creating object of derived class


Program program = new Program();

// accessing name field and printing it


[Link]("Name: " + [Link]);
[Link]();
}
}
}
Output
Name: Sheeran
In the above example, we have created a class Student with a protected
field name. Notice that we have inherited the Program class from
the Student class.
// accessing name field and printing it
[Link]("Name: " + [Link]);
Since the protected member can be accessed from derived classes, we are able
to access name from the Program class.
4. internal access modifier
When we declare a type or type member as internal, it can be accessed only
within the same assembly.
An assembly is a collection of types (classes, interfaces, etc) and resources
(data). They are built to work together and form a logical unit of functionality.
That's why when we run an assembly all classes and interfaces inside the
assembly run together.
Example: internal within the same Assembly
using System;

namespace Assembly

class Student {
internal string name = "Sheeran";
}
.NET PROGRAMMING Page 150
UNIT III

class Program {
static void Main(string[] args) {

// creating object of Student class


Student theStudent = new Student();

// accessing name field and printing it


[Link]("Name: " + [Link]);
[Link]();
}
}
}
Output
Name: Sheeran
In the above example, we have created a class named Student with a field name.
Since the field is internal, we are able to access it from the Program class as
they are in the same assembly.

3.5 PASS REFERENCES TO METHOD


The ref keyword in C# is used for passing or returning references of values to or
from Methods. Basically, it means that any change made to a value that is
passed by reference will reflect this change since you are modifying the value at
the address and not just the value.
There are three ways to pass parameters to a method.
1. Pass by Value
2. Pass by Reference
3. Pass by Output
1. Pass by Value
Passing parameters to a method by value is simple. When a simple variable is
passed as a parameter to any method, it is passed as a value.
The following example demonstrates the concept of passing a variable by value.
Filename: [Link]
using System;

namespace Studytonight

.NET PROGRAMMING Page 151


UNIT III

{
class Program
{
public static void Area(int a)
{
[Link]("Adding 2 to the value of a");
a = a+2;
[Link]("New value of a: " + a);
[Link]("Calculating the area of geometric shapes");
int result = a * a;
[Link]("Area of Square is " + result);
}

static void Main(string[] args)


{
int s = 18;
Area(s);
[Link]("Side Value is " + s);
[Link]();
}
}
}
Copy
Output:
Adding 2 to the value of a
New value of a: 20
Calculating the area of geometric shapes
Area of Square is 400
Side Value is 18
In the above code, the variable s is a variable which is passed as a value to
the Area method. The content of variable s is copied to the parameter a and after
that whatever processing is done on parameter a or using the parameter a, will
have no affect on the variable s. Hence, the side value remains 18 although we
add 2 to the value of a before calculating the area.
In case of pass by value a new storage location is allocated for each value
passed as parameters.
2. Pass by Reference
The ref keyword indicates a value that is passed by reference. When we pass
parameters by reference, unlike passing parameters by value, a new storage
.NET PROGRAMMING Page 152
UNIT III

location is not created for these parameters. The reference parameters represent
the same memory location as the actual parameters that are supplied to the
method.
In simpler words, when we pass a reference of a variable to a method, then we
pass the address or the memory location where the value is stored. So if, inside
the method, the value of the parameter is changed, then the actual value stored
at the memory location gets changed as no copy is getting created for the value
passed as parameter.
The following example demonstrates the concept of passing a variable by
reference
Filename: [Link]
using System;

namespace Studytonight
{
public class Program
{
public static void Area(ref int a)
{
[Link]("Calculating Area of Geometric Shapes");
a = a * a;
[Link]("Area of Square is " + a);
}

public static void Main()


{
int s = 20;
Area(ref s);
[Link]("Side Value is " + s);
}
}
}
Copy
Output:
Calculating the area of geometric shapes
Area of Square is 400
Side Value is 400

.NET PROGRAMMING Page 153


UNIT III

Passing the reference of the variable s to the variable a in Area method by


using ref keyword implies that the variable a will then contain the reference of
variable s so the changes that are made to the variable a will affect the value of
variable s. Hence, pass by reference must be used very carefully.

3. Pass by Output
The out keyword indicates a value that is passed by reference type. It is pretty
similar to the ref keyword, the only difference is that out doesn't require a
variable to be initialized before we pass it as an argument to the method.
However, the called method is required to assign a value to the passed reference
before the method returns.
The following example demonstrates the concept of passing a variable by
reference using the out keyword.
Filename: [Link]
using System;

namespace Studytonight
{
public class Program
{
public static void Area(out int a)
{
a = 50;
[Link]("Calculating Area of Geometric Shapes");
a = a * a;
[Link]("Area of Square is " + a);
}
public static void Main()
{
int s;
Area(out s);
[Link]("Side Value is " + s);
[Link]();
}
}
}
Copy
Output:

.NET PROGRAMMING Page 154


UNIT III

Calculating the area of geometric shapes


Area of Square is 400
Side Value is 400
In the code above, we declared a variable s and passed it to the Area method
using the out keyword without initializing any value to the variable s. However,
the called Area method is initializing the value before it returns the result to the
calling statement. And after the Area value assigns a value to the variable s, the
value can still be accessed even after the function ends.

3.6 METHOD OVERLOADING


Method overloading allows programmers to use multiple methods with the
same name.
The methods are differentiated by their number and type of method arguments.
Method overloading is an example of the polymorphism feature of an object-
oriented programming language.
Method overloading can be achieved by the following:
 By changing the number of parameters in a method
 By changing the order of parameters in a method
 By using different data types for parameters
For example:
void display() { ... }
void display(int a) { ... }
float display(double a) { ... }
float display(int a, float b) { ... }
Here, the display() method is overloaded. These methods have the same name
but accept different arguments.
Note: The return types of the above methods are not the same. It is because
method overloading is not associated with return types. Overloaded methods
may have the same or different return types, but they must have different
parameters.
We can perform method overloading in the following ways:
1. By changing the Number of Parameters
We can overload the method if the number of parameters in the methods is
different.

.NET PROGRAMMING Page 155


UNIT III

void display(int a) {
...
}
...
void display(int a, int b) {
...
}
Here, we have two methods in a class with the same name - display(). It is
possible to have more than one method with the same name because the number
of parameters in methods is different.
For example,
using System;

namespace MethodOverload

{ class Program {

// method with one parameter


void display(int a) {
[Link]("Arguments: " + a);
}

// method with two parameters


void display(int a, int b) {
[Link]("Arguments: " + a + " and " + b);
}
static void Main(string[] args) {

Program p1 = new Program();


[Link](100);
[Link](100, 200);
[Link]();
}
}
}
Output
Arguments: 100
Arguments: 100 and 200
In the above example, we have overloaded the display() method:

.NET PROGRAMMING Page 156


UNIT III

 one method has one parameter


 another has two parameter
Based on the number of the argument passed during the method call, the
corresponding method is called.
 [Link](100) - calls the method with single parameter
 [Link](100, 200) - calls the method with two parameters
2. By changing the Data types of the parameters
void display(int a) {
...
}
...
void display(string b) {
...
}
Here, we have two methods - display() with the same number of parameters. It
is possible to have more than one display() method with the same number of
parameters because the data type of parameters in methods is different.
For example,
using System;

namespace MethodOverload

{ class Program {

// method with int parameter


void display(int a) {
[Link]("int type: " + a);
}

// method with string parameter


void display(string b) {
[Link]("string type: " + b);
}
static void Main(string[] args) {

Program p1 = new Program();


[Link](100);
.NET PROGRAMMING Page 157
UNIT III

[Link]("Programiz");
[Link]();
}
}
}
Output
int type: 100
string type: Programiz
In the above program, we have overloaded the display() method with different
types of parameters.
Based on the type of arguments passed during the method call, the
corresponding method is called.
 [Link](100) - calls method with int type parameter
 [Link]("Programiz") - calls method with string type parameter

3. By changing the Order of the parameters


void display(int a, string b) {
...
}
...
void display(string b, int a) {
...
}
Here, we have two methods - display(). It is possible to have more than
one display() method with the same number and type of parameter because the
order of data type of parameters in methods is different.
For example,
using System;

namespace MethodOverload

{ class Program {

// method with int and string parameters


void display(int a, string b)
{ [Link]("int: " + a);
[Link]("string: " + b);

.NET PROGRAMMING Page 158


UNIT III

// method with string andint parameter


void display(string b, int a)
{ [Link]("string: " + b);
[Link]("int: " + a);
}
static void Main(string[] args) {

Program p1 = new Program();


[Link](100, "Programming");
[Link]("Programiz", 400);
[Link]();
}
}
}
Output
int: 100
string: Programming
string: Programiz
int: 400
In the above program, we have overloaded the display() method with different
orders of parameters.
Based on the order of arguments passed during the method call, the
corresponding method is called.
[Link](100, "Programming") - calls method with int and string parameter
respectively
[Link]("Programiz", 400) - calls method with string and int parameter
respectively

METHOD OVERRIDING
Method overriding is a concept in object-oriented programming (OOP) where a
subclass (derived class) provides a specific implementation of a method that is
already defined in its superclass (base class). The method in the subclass
overrides the method in the superclass, meaning the subclass method is called
instead of the superclass method when invoked on an object of the subclass.

.NET PROGRAMMING Page 159


UNIT III

Key Points About Method Overriding:


1. Same Method Signature: The method in the subclass must have the same
name, return type, and parameters (method signature) as the method in
the superclass.
2. Inheritance: The subclass must inherit from the superclass in order to
override its methods.
3. Dynamic Dispatch: In most OOP languages, method overriding is
resolved at runtime (also called dynamic method dispatch), meaning the
method that gets called depends on the object type (not the reference
type).
4. Polymorphism: Method overriding is an essential part of polymorphism,
allowing objects of different subclasses to have different implementations
of the same method.
5. super keyword: In many languages (like Python, Java), the super()
keyword can be used in the subclass method to call the method from the
superclass
If the same method is present in both the superclass and the subclass. Then, the
method in the subclass overrides the same method in the superclass. This is
called method overriding.
In this case, the same method will perform one operation in the superclass and
another operation in the subclass.
We can use virtual and override keywords to achieve method overriding.
using System;
class Polygon
{
// method to render a shape
public virtual void render()
{
[Link]("Rendering Polygon...");
}

class Square : Polygon


{

.NET PROGRAMMING Page 160


UNIT III

// overriding render() method


public override void render()
{
[Link]("Rendering Square...");
}

}
class myProgram
{
public static void Main()
{
// obj1 is the object of Polygon class
Polygon obj1 = new Polygon();

// calls render() method of Polygon Superclass


[Link]();

// here, obj1 is the object of derived class Square


obj1 = new Square();

// calls render() method of derived class Square


[Link]();
}
}
Output
Rendering Polygon...
Rendering Square…
In the above example, we have created a superclass: Polygon and a
subclass: Square.
Notice, we have used virtual and override with methods of the base class and
derived class respectively. Here,
 virtual - allows the method to be overridden by the derived class
 override - indicates the method is overriding the method from the base
class
Rules:
 The method in the subclass must have the same method signature as in
the superclass.

.NET PROGRAMMING Page 161


UNIT III

 The method in the subclass can have a different access modifier (in some
languages, like Java), but it cannot be more restrictive than the method in
the superclass.
3.7 MAIN METHOD
an entry point called Main Method. It is the first method which gets invoked
whenever an application started and it is present in every C# executable file.
The application may be Console Application or Windows Application. The
most common entry point of a C# program is static void Main() or static void
Main(String []args).
Different Declaration of Main() Method
Below are the valid declarations of Main Method in a C# program:
1. With command line arguments: This can accept n number of array type
parameters during the runtime. Example:
using System;

class GFG {

// Main Method
public static void Main(String[] args)
{

[Link]("Main Method");
}
}
Output:
Main Method

2. Without Command line arguments:


It is up to the user whether he wants to take command line arguments or not. If
there is a need for command-line arguments then the user must specify the
command line arguments in the Main method. Example:
using System;

.NET PROGRAMMING Page 162


UNIT III

class GFG {

// Main Method
public static void Main()
{

[Link]("Main Method");
}
}

Output:
Main Method

3. Applicable Access Modifiers:


public, private, protected, internal, protected internal access modifiers can be
used with the Main() method. The private protected access modifier cannot be
used with it. Example:
using System;

class GFG {

// Main Method
protected static void Main()
{

[Link]("Main Method");
}
}
Output:
Main Method

4. Without any access modifier: The default access modifier is private for a
Main() method. Example:
using System;

.NET PROGRAMMING Page 163


UNIT III

class GFG {

// Main Method without any


// access modifier
static void Main()
{

[Link]("Main Method");
}
}
Output:
Main Method

5. Return Type: The Main Method can also have integer return type. Returning
an integer value from Main() method cause the program to obtain a status
information. The value which is returned from Main() method is treated as the
exit code for the process. Example:
using System;

class GFG {
// Main Method with int return type
static int Main()
{
[Link]("Main Method");

// for successful execution of code


return 0;
}
}
Output:
Main Method
3.8 RECURSION
 A function that calls itself is known as a recursive function. And, this way
is known as recursion.
 A physical world example would be to place two parallel mirrors facing
each other. Any object in between them would be reflected recursively.

.NET PROGRAMMING Page 164


UNIT III

How Recursion Works

Working of C# Recursion
In the above example, we have called the recurse() method from inside the
Main method (normal method call). And, inside the recurse() method, we are
again calling the same recurse() method. This is a recursive call.
To stop the recursive call, we need to provide some conditions inside the method.
Otherwise, the method will be called infinitely.

Example: Factorial of a Number Using Recursion


The factorial of a positive number n is given by:
factorial of n (n!) = 1 * 2 * 3 * 4.........n
In C#, we can use recursion to find the factorial of a number. For example,
using System;
class Program
{
public static void Main()
{
int fact, num;
[Link]("Enter a number:
");
// take input from user
num = Convert.ToInt32([Link]());
Program obj = new Program();
// calling recursive function
fact = [Link](num);
.NET PROGRAMMING Page 165
UNIT III

[Link]("Factorial of {0} is {1}", num, fact);


}
// recursive function
public int factorial(int num)
{
// termination condition
if (num == 0)
return 1;
else
// recursive call
return num * factorial(num - 1);
}
}
Output
Enter a number: 4
Factorial of 4 is 24
In the above example, we have a method named factorial(). We have passed a
variable num as an argument in factorial().
The factorial() is called from the Main() method. Inside factorial(), notice the
statement:
return num * factorial(num - 1);
Here, the factorial() method is calling itself. Initially, the value
of num inside factorial() is 4. During the next recursive call, 3 is passed to
the factorial() method. This process continues until num is equal to 0.
When num is equal to 0, the if statement returns true hence 1 is returned.
Finally, the accumulated result is passed to the Main() method.
Working of Factorial Program
The image below will give you a better idea of how the factorial program is
executed using recursion.

.NET PROGRAMMING Page 166


UNIT III

Advantages and Disadvantages of Recursion


Advantage - Using recursion, our code looks clean and more readable.
Disadvantages - When a recursive call is made, new storage locations for
variables are allocated on the stack. As each recursive call returns, the old
variables and parameters are removed from the stack. Hence, recursion
generally uses more memory and is generally slow.
3.9 STATIC CLASSES
 In C#, static means something which cannot be instantiated. You cannot
create an object of a static class and cannot access static members using
an object.
 C# classes, variables, methods, properties, operators, events, and
constructors can be defined as static using the static modifier keyword.
Static Class
Apply the static modifier before the class name and after the access modifier to
make a class static. The following defines a static class with static fields and
methods.
Example: C# Static Class
public static class Calculator
{

.NET PROGRAMMING Page 167


UNIT III

private static int _resultStorage = 0;

public static string Type = "Arithmetic";

public static int Sum(int num1, int num2)


{
return num1 + num2;
}

public static void Store(int result)


{
_resultStorage = result;
}
}
Above, the Calculator class is a static. All the members of it are also static.
You cannot create an object of the static class; therefore the members of the
static class can be accessed directly using a class name
like [Link], as shown below.
Example: Accessing Static Members
class Program
{
static void Main(string[] args)
{
var result = [Link](10, 25); // calling static method
[Link](result);

var calcType = [Link]; // accessing static variable


[Link] = "Scientific"; // assign value to static variable
}
}
Rules for Static Class
1. Static classes cannot be instantiated.
2. All the members of a static class must be static; otherwise the compiler
will give an error.
3. A static class can contain static variables, static methods, static
properties, static operators, static events, and static constructors.
4. A static class cannot contain instance members and constructors.

.NET PROGRAMMING Page 168


UNIT III

5. Indexers and destructors cannot be static


6. var cannot be used to define static members. You must specify a type of
member explicitly after the static keyword.
7. Static classes are sealed class and therefore, cannot be inherited.
8. A static class cannot inherit from other classes.
9. Static class members can be accessed using [Link].
10.A static class remains in memory for the lifetime of the application
domain in which your program resides.

DELEGATES,EVENTS AND LAMBDA EXPRESSIONS


3.10 DELEGATES
In C#, delegates are a type-safe function pointer that allow methods to be passed as
parameters, stored, and invoked dynamically. They are essential for events,
callbacks, and designing flexible and extensible applications.
Here's an overview of how delegates work in C#:
What is a Delegate?
A delegate is a reference type that holds a reference to a method with a particular
parameter list and return type. You can think of a delegate as a type- safe
function pointer, which means it can refer only to methods that match its
signature.
Syntax:
To declare a delegate, you define its signature (method signature without the
body). Here's a simple example:
// Declare a delegate type
public delegate void MyDelegate(string message);

This delegate type can point to any method that takes a string parameter and
returns void.
Using a Delegate:
1. Define a method that matches the delegate signature:
public void PrintMessage(string message)

.NET PROGRAMMING Page 169


UNIT III

{
[Link](message);
}
2. Create an instance of the delegate: You can then create a delegate
instance and point it to the method.
MyDelegate del = new MyDelegate(PrintMessage);
3. Invoke the method through the delegate: You can invoke the method
through the delegate like this:
del("Hello, Delegates!");
Example Code:
Here's a full example demonstrating the use of delegates:
using System;

class Program
{
// Declare a delegate type
public delegate void MyDelegate(string message);

static void Main()


{
// Create an instance of the delegate and bind it to the method
MyDelegate del = new MyDelegate(PrintMessage);

// Invoke the method through the delegate


del("Hello, Delegates!");

// You can also call it directly using shorthand


[Link]("This is a shortcut way to call a delegate.");
}

// A method that matches the delegate signature


static void PrintMessage(string message)
{
[Link](message);
}
}
Output:
vbnet

.NET PROGRAMMING Page 170


UNIT III

Copy code
Hello, Delegates!
This is a shortcut way to call a delegate.
Multicast Delegates
A delegate in C# can also point to more than one method, which is known as
multicast delegates. When you invoke the delegate, it calls all the methods that
are in its invocation list.
Example of multicast delegates:
public delegate void MyDelegate(string message);

static void Main()


{
MyDelegate del = PrintMessage;
del += AnotherMethod;

// This will invoke both PrintMessage and AnotherMethod


del("Hello, Multicast Delegates!");
}

static void PrintMessage(string message)


{
[Link]("PrintMessage: " + message);
}

static void AnotherMethod(string message)


{
[Link]("AnotherMethod: " + message);
}
Output:
makefile
Copy code
PrintMessage: Hello, Multicast Delegates!
AnotherMethod: Hello, Multicast Delegates!

Anonymous Methods and Lambda Expressions


In C#, you can also use anonymous methods or lambda expressions with
delegates, which provide a more concise syntax.
Using an Anonymous Method:

.NET PROGRAMMING Page 171


UNIT III

MyDelegate del = delegate(string message)


{
[Link]("Anonymous: " + message);
};
del("Hello from anonymous method!");

Using a Lambda Expression:

MyDelegate del = (message) => [Link]("Lambda: " + message);


del("Hello from lambda!");

Delegates and Events


Delegates are commonly used with events. For example, when you subscribe to
an event, you're essentially creating a delegate invocation list. Here's an
example:
public class Button
{
public event MyDelegate Clicked;

public void OnClick(string message)


{
// Trigger the event (invoke the delegate)
Clicked?.Invoke(message);
}
}

class Program
{
static void Main()
{
Button button = new Button();

// Subscribe to the event


[Link] += (message) => [Link]("Button clicked: " +
message);

.NET PROGRAMMING Page 172


UNIT III

// Trigger the event


[Link]("Hello!");
}
}

3.11 EVENTS
Events are something that occurs in a program. Events allow a class or object to
notify other classes or objects when something occurs.
 The class that raises (or sends) the event is called the publisher.
 The classes that receive (or handle) the event are called subscribers. And
the method of the classes that handle the event is often called event
handlers.
This pattern is known as publisher/subscriber. In this pattern, the publisher
determines when to raise the event and the subscribers decide how to handle the
event.
Technically, an event has an encapsulated delegate. In fact, an event is like a
simpler delegate. Let’s take an example of using events.
Suppose you have a class called Order with a method Create() that creates a
new order:
class Order
{
public void Create()
{
[Link]("Order created");
}
}Code language: C# (cs)

And two other classes that send an email and SMS:


class Email
{
public static void Send()
{
[Link]("Send an email");
}
}

.NET PROGRAMMING Page 173


UNIT III

class SMS
{
public static void Send()
{
[Link]("Send an SMS");
}
}Code language: C# (cs)
When an order is created, you want to send an email and SMS to the customer.
To do it, you may come up with the following code:
class Order
{
public void Create()
{
[Link]("Order was
created"); [Link]();
[Link]();
}
}Code language: C# (cs)
Later if you want to do other tasks when an order is created, you have to modify
the Create() method. Also, the Order class depends on the Email and SMS
classes which is not a good design.
To resolve this, you can use the publisher/subscriber pattern:
 The Order class is the publisher.
 The Email and SMS classes are the subscribers.
When an order is created, the Order object will notify
the Email and SMS classes to send an email and SMS.
Declaring an event
The following declares the OnCreated event when an order is created:
delegate void OrderEventHandler();

class Order
{
public event OrderEventHandler OnCreated;

public void Create()


{

.NET PROGRAMMING Page 174


UNIT III

[Link]("Order created");
}
}Code language: C# (cs)

How it works.
First, define a delegate type for the event:
delegate void OrderEventHandler();Code language: C# (cs)
Second, declare an event associated with the delegate type:
public event OrderEventHandler OnCreated;Code language: C# (cs)
Since an event is a member of a class, you need to declare it inside the class. In
this example, the event is public so that other classes can register event handlers
with it. Also, the event handlers must match the delegate type associated with
the event.
Raising an event
Raising an event is the same as invoking a method. An event that doesn’t have
any event handlers is null. Therefore, before raising an event, you need to
compare it to null.
The following raises the OnCreated event inside the Create() method:
class Order
{
public event OrderEventHandler OnCreated;

public void Create()


{
[Link]("Order created");

if(OnCreated != null)
{
OnCreated();
}
}
}Code language: C# (cs)

Subscribing to an event
.NET PROGRAMMING Page 175
UNIT III

Subscribing to an event means adding event handlers to an event. The event


handlers must have the same return type and signature as the event’s delegate.
To add an event handler to an event, you use the += operator. The event handler
can be an instance method, a static method, an anonymous method, or a lambda
expression.
The following shows how to subscribe OnCreated event:
class Program
{
static void Main(string[] args)
{
var order = new Order();

[Link] += [Link];
[Link] += [Link];

[Link]();
}
}Code language: C# (cs)
Output:
Order created
Send an email
Send an SMSCode language: C# (cs)

How it works.
First, create a new Order object:
var order = new Order();Code language: C# (cs)
Second, add event handlers to the OnCreated event:
[Link] += [Link];
[Link] += [Link];Code language: C#
(cs) Third, call the Create() method of the Order
object: [Link]();Code language: C# (cs)
The Create() method raises the OnCreated event. Since
the Email and SMS classes are subscribed to the OnCreated event,
the Send() methods of these classes are automatically called.

.NET PROGRAMMING Page 176


UNIT III

Put it all together:


delegate void OrderEventHandler();

class Order
{
public event OrderEventHandler OnCreated;

public void Create()


{
[Link]("Order created");

if(OnCreated != null)
{
OnCreated();
}
}
}

class Email
{
public static void Send()
{
[Link]($"Send an email");
}
}

class SMS
{
public static void Send()
{
[Link]($"Send an SMS");
}
}

class Program
{
static void Main(string[] args)
{

.NET PROGRAMMING Page 177


UNIT III

var order = new Order();

[Link] += [Link];
[Link] += [Link];

[Link]();
}
}Code language: C# (cs)

EventHandler

C# provides you with the standard EventHandler delegate type so that you don’t
need to define a new delegate type when you use events.
The following shows the declaration of the EventHandler delegate type:
public delegate void EventHandler(object sender, EventArgs e);Code language:
C# (cs)
In this delegate type:
 The sender holds a reference to the object that raised the event.
 The EventArgs object holds the state information which can be whatever
that is applicable to the application.
It’s important to understand that the EventArgs is designed for event handlers
that do not need to pass data from the publisher to subscribers. If you want to
pass the data, you need to define a class derived from the EventArgs class.
The following program shows how to use the EventHandler for the order
created event:
class Order
{
public event EventHandler OnCreated;

public void Create()


{
[Link]("Order created");

if(OnCreated != null)
{

.NET PROGRAMMING Page 178


UNIT III

OnCreated(this, [Link]);
}
}
}

class Email
{
public static void Send(object sender, EventArgs e)
{
[Link]($"Send an email");
}
}

class SMS
{
public static void Send(object sender, EventArgs e)
{
[Link]($"Send an SMS");
}
}

class Program
{
static void Main(string[] args)
{
var order = new Order();

[Link] +=
[Link]; [Link]
+= [Link];

[Link]();
}
}Code language: C# (cs)
How it works.
First, use the EventHandler instead of the OrderEventHandler delegate type:
public event EventHandler OnCreated;Code language: C# (cs)

.NET PROGRAMMING Page 179


UNIT III

Second, raise the OnCreated event by passing the Order object (this)
and [Link]:
OnCreated(this, [Link]);Code language: C# (cs)
Note that the [Link] provides a value to use with an event that does
not have event data.
Third, modify the signature of the Send() method of the Email and SMS classes
to match with the EventHandler delegate type:
public static void Send(object sender, EventArgs e)Code language: C# (cs)

3.12 LAMBDA EXPRESSIONS


C# Lambda Expression is a short block of code that accepts parameters and
returns a value. It is defined as an anonymous function (function without a
name). For example,
num => num * 7
Here, num is an input parameter and num * 7 is a return value. The lambda
expression does not execute on its own. Instead, we use it inside other methods
or variables.
How to Define a Lambda Expression
We can define lambda expression in C#
as, (parameterList) => lambda body
Here,
 parameterList - list of input parameters
 => - a lambda operator
 lambda body - can be an expression or statement
Based on lambda body, the C# lambda expression is divided into two types.
Types of Lambda Expression
The two types of lambda expressions are:
1. Expression Lambda
2. Statement Lambda

.NET PROGRAMMING Page 180


UNIT III

1. Expression Lambda: Expression lambda contains a single expression in the


lambda body. For example,
(int num) => num * 5;

The above expression lambda contains a single expression num * 5 in the


lambda body. It takes an int input, multiplies it by 5, and returns the output.
2. Statement Lambda: Statement lambda encloses one or more statements in
the lambda body. We use curly braces {} to wrap the statements. For example,
(int a, int b) =>
{
var sum = a + b;
return sum;
};

The above expression is a statement lambda which contains two statements in the
lambda body. This takes two int inputs and returns its sum.
Example: C# Expression Lambda
using System;
class Program
{
static void Main()
{
// expression lambda that returns the square of a number
var square = (int num) => num * num;

// passing input to the expression lambda


[Link]("Square of number: " + square(5));
}
}
Output
Square of number: 25

In the above example, the expression lambda is


(int num) => num * num;

.NET PROGRAMMING Page 181


UNIT III

Here, the expression lambda returns the square of num. We have then assigned
the expression lambda to the square variable.
So, when we pass 5 as an input in square, we get 25 as an output.

Example: C# Statement Lambda


using System;
class Program
{
static void Main()
{
// statement lambda that takes two int inputs and returns the sum
var resultingSum = (int a, int b) =>
{
int calculatedSum = a + b;
return calculatedSum;
};

// find the sum of 5 and 6


[Link]("Total sum: " + resultingSum(5, 6));
}
}
Output
Total sum: 11

In the above example, we have used the statement lambda as,


(int a, int b) =>
{
int calculatedSum = a + b;
return calculatedSum;
}
Here, the statement lambda takes two integer parameters - a and b. On the right
side of the lambda operator => we have enclosed two statements that:
 calculate the sum of a and b
 return the sum

.NET PROGRAMMING Page 182


UNIT III

Note: Before C# 9.0, explicitly defining the delegate type was necessary when
using var with lambda expressions. C# 9.0 introduced the ability to assign
lambda expressions to var without specifying the delegate type.

Lambda Expression with Delegate


In C#, we can assign lambda expressions to the delegate types like Func. For
example,
using System;
class Program
{
static void Main()
{
// using lambda expression with delegate type
// take an int input, multiply it with 3 and return the result
Func<int, int> multiply = num => num * 3;

// calls multiply() by passing 5 as an input


[Link](multiply(5));
}
}
Output
15

In the above example, we have assigned lambda expression num => num * 3; to the
Func delegate multiply.
Here, the lambda expression takes an int type input num, multiplies it
with 3 and returns the result to multiply().
Hence, when we pass 5 in multiply(), it returns 15.
Note: The Func<> delegate type takes 0 or more input values and returns an output
value. For example, Func<int,int,string> takes two int inputs and returns a string
output. To learn more about delegates, visit C# delegates.
Use of Lambda Expression
Some of the uses of the lambda expression are:
1. Writing Easy and Simple Delegate Code

.NET PROGRAMMING Page 183


UNIT III

Using lambda expressions, we can write much easier and simpler code. Let's see
programs with and without using a lambda expression in a delegate.
Program Without Using Lambda Expression
using System;
class Program
{
static void Main()
{
// method that returns square of a number
int Square(int num)
{
return num * num;
}

// delegate that points the Square() method


Func<int, int> square = Square;

// calling square() delegate


[Link](square(7));
}
}
Output
49
In the above program, we have defined a delegate square of Func type that
points to the Square() method.
Program With Using Lambda Expression
using System;
class Program
{
static void Main()
{
// delegate using lambda expression
Func<int, int> square = num => num * num;

// calling square() delegate


[Link](square(7));
}
}
Output

.NET PROGRAMMING Page 184


UNIT III

49
Here, we don't need to define a separate method. We have replaced the pointer
to the square() method with the lambda expression.
2. Passing Parameter in Method
We can pass a lambda expression as a parameter in a method call.
Let's take a built-in Count() method of C# array and pass a lambda expression
as its parameter.
using System;
class Program
{
static void Main()
{
// array containing integer values
int[] numbers = { 2, 13, 1, 4, 13, 5 };

// lambda expression as method parameter


// returns the total count of 13 in the numbers array
int totalCount = [Link](x => x == 13);

[Link]("Total number of 13: " + totalCount);


}
}
Output
Total number of 13: 2
In the above example, we have passed the lambda expression x => x == 13 as a
method parameter.
The Count() method checks each element of the numbers array and counts the
total number of 13 in the array.
3.13 LINQ
LINQ is known as Language Integrated Query, and it is presented in .NET 3.5
and Visual Studio 2008.
The excellence of LINQ is it gives the capacity to .NET languages(like C#,
[Link], and so forth) to create inquiries to recover information from the
information source.

.NET PROGRAMMING Page 185


UNIT III

For instance, a program might get data from the understudy records or get to
worker records, and so on.
To beat such kinds of issues, Microsoft created LINQ. It connects one more
capacity to the C# or .NET dialects to create a question for any LINQ viable
information source. What's more, the best part is the sentence structure used to
make a question is similar regardless of which kind of information source is
utilized means the grammar of making an inquiry about information in a social
data set is the same as that used to make question information put away in a
cluster there is compelling reason need to utilize SQL or some other [Link]
language component. You can likewise utilize LINQ with SQL, with XML
records, with [Link], with web administrations, and with some other
information base.
In C#, LINQ is available in System. Linq namespace. It gives different sort of
classes and techniques which upholds LINQ questions. In this namespace:
1. The Enumerable class holds a standard query operator that works on an
object which executes IEnumerable<T>.
2. The queryable class holds standard inquiry administrators that work on an
object which executes IQueryable<T>.
For Example: SQL is a structured query Language that is used to save and
recuperate data from the database. Likewise, LINQ is an Organized Query
Sentence structure. LINQ is the basic C#. It is utilized to recover information
from various kinds of sources, for example, XML, docs, collections, [Link]
DataSet, Web Service, MS SQL Server, and different database servers.

Uses of LINQ
1. The primary reason behind making LINQ is, before C# 3.0, we used for
loop, for each loop, or delegates to traverse a collection to track down a
particular object, yet the detriment of involving these strategies for
finding an object is you really want to compose an enormous amount of

.NET PROGRAMMING Page 186


UNIT III

code to find an object which is additional tedious and make your program
less lucid. So to defeat these issues, LINQ is presented, which plays out
similar activity in a couple of quantities of lines and makes your code
clear; furthermore, you can involve similar code in different projects.
2. It additionally gives full sort checking at the compile time. It assists us
with distinguishing the error at the runtime, so we can undoubtedly
eliminate them.
3. LINQ is it is straightforward, very much arranged, and significant level
language than SQL
4. You can likewise utilize LINQ with C# array and collections. It provides
you with another guidance to take care of the old issues in a powerful
way.
5. With the assistance of LINQ, you can undoubtedly work with a data
source like XML, SQL, Entities, objects, and so forth. A single query can
work with the database, compelling reason need to learn various sorts of
languages.
6. LINQ upholds query expression, Anonymous types, Implicitly typed
variables, Lambda expressions, Object and collection initializers, and
Extension methods.
We can use LINQ queries in two ways
LINQ query Syntax structure is comprised of query keywords which are
characterized into the .NET System rendition 3.5 or Higher. This allows the
software engineer or developers to compose the directions very much like SQL
design in the code(C# or [Link]) without the utilization of rates. It is in like
manner known in light of the fact that the Question Articulation Grammar. In
LINQ, you can compose the inquiry to IEnumerable series or IQueryable
information sources utilizing the ensuing strategies:
1. Query Syntax:
The LINQ query language syntax starts with from keyword and finishes with the
Select or GroupBy keyword. After from keyword, you can utilize various sorts
of Standard Query operations like grouping, filtering, and so on, as indicated by
your need. In LINQ, 50 unique kinds of Standard Question Administrators are
accessible.
Steps for writing the Query syntax:
Step-1: In the first step, we have to add the [Link] namespace in the code.
.NET PROGRAMMING Page 187
UNIT III

1. i.e., using [Link];


Step-2: In a second step, we have to create the data source on which we have to
perform the operations
Ex: List list = new List()
{
" Hii ",
" Welcome to JavaTpoint
", " The topic is LINQ."
" Any Queries "
};
Step-3: In the third step, we have to create the query for the data source using a
keyword like select, from, etc.
Ex: var r = from l in list
where [Link](" Hii ")
select l;
Here r is the query variable that stores the result of the query articulation. The
form clause is utilized to determine the information source, i.e., list, where
condition applies to the channel, i.e., [Link](" Hii ") and select statement
gives the kind of the brought things back. Furthermore, l is the reach variable.
Step-4: The final step is to execute the query using the for each loop.
EX: foreach(var i in r)
{
[Link](i);
}
Example program on Query syntax:
// program to create LINQ query using Query Syntax
// step-1: Adding the [Link] namespace in the code.
using System;
using [Link];
using [Link];
class HelloWorld
{
// Main Method
static public void Main()
{
// Step-
2: creating the data source on which we have to perform the operations
List<string> list = new List<string>()
.NET PROGRAMMING Page 188
UNIT III

{
" Hii JavaTpoint",
" Welcome to JavaTpoint ",
" The topic is LINQ ",
" Any Queries "
};
// step-
3: Creating the LINQ query for the data source using a keyword like select, f
rom, etc.
var r = from l in list
where [Link](" JavaTpoint")
select l;

// In this will print only the sentence which contains JavaTpoint word
// step-4: Executing LINQ Query using the for each loop
foreach(var i in r)
{
[Link](i);
}
}
}
Output:

2. Method Syntax
In LINQ, Method Syntax is utilized to call the expansion method for the
Enumerable or Queryable static classes. It is also called Method Extension
Syntax or Fluent. Notwithstanding, the compiler generally changes over the
query syntax in method syntax structure at compile time. It can summon the
standard Query operator like Where, Join, Max, Min, Avg, GroupBy Select, and
so forth. You are permitted to call them straightforwardly without utilizing
Query syntax.
Step-1: In the first step, we have to add the [Link] namespace in the code.
1. i.e., using [Link];

.NET PROGRAMMING Page 189


UNIT III

Step-2: In a second step, we have to create the data source on which we have to
perform the operations
Ex: List list = new List()
{
" Hii ",
" Welcome to JavaTpoint
", " The topic is LINQ "
" Any Queries "
};
Step-3: Now create the query using the methods provided by the Enumerable or
Queryable static classes
1. Ex: var r = [Link](a=> [Link](" JavaTpoint "));
Here r is the query variable that stores the result of the query articulation. The
form clause is utilized to determine the information source, i.e., list, where
condition applies to the channel, i.e., [Link](" Hii ") and select statement
gives the kind of the brought things back. Furthermore, l is the reach variable.
Step-4: The final step is to execute the query using the for each
loop. Advertisement
EX: foreach(var i in r)
{
[Link](i);
}
Example program on Method syntax:
// program to create LINQ query using Method syntax
// step-1: Adding the [Link] namespace in the code.
using System;
using [Link];
using [Link];
class HelloWorld
{
// Main Method
static public void Main()
{
// Step-
2: creating the data source on which we have to perform the operations
List<string> list = new List<string>()

.NET PROGRAMMING Page 190


UNIT III

{
" Hii JavaTpoint",
" Welcome to JavaTpoint ",
" The topic is LINQ ",
" Any Queries "
};
//step-
3 creating the query using the methods provided by the Enumerable or Query
able static classes
var r = [Link](a=> [Link](" JavaTpoint "));
// In this will print only the sentence which contains JavaTpoint word
// Executing LINQ Query using the for each loop
foreach(var i in r)
{
[Link](i);
}
}
}
Output:

Advantages of LINQ
1. The client doesn't have to learn new query languages for an alternate type
of data format or data source.
2. It increments the clarity of the code.
3. The query can be reused.
4. It gives type checking of the object at assemble time.
5. It gives IntelliSense to conventional collections.
6. It tends to be utilized with collections or arrays.
7. LINQ upholds ordering, grouping, filtering, and sorting.
8. It makes debugging simple since it is coordinated with the C# language.
9. It gives straightforward change suggesting you can without a doubt
change more than one data type into another data type like changing SQL
data into XML data.
.NET PROGRAMMING Page 191
UNIT IV

UNIT IV
DEVELOPING [Link]
APPLICATIONS VISUAL STUDIO
 Visual Studio is an Integrated Development Environment(IDE)
developed by Microsoft to develop Desktop applications, GUI(Graphical
User Interface), console, web applications, mobile applications, cloud,
and web services, etc.
 With the help of this IDE, you can create managed code as well as native
code. It uses the various platforms of Microsoft software development
software like Windows store, Microsoft Silverlight, and Windows API,
etc.
 It is not a language-specific IDE as you can use this to write code in C#,
C++, VB(Visual Basic), Python, JavaScript, and many more languages. It
provides support for 36 different programming languages.
 It is available for Windows as well as for macOS.
EVOLUTION OF VISUAL STUDIO
The first version of VS(Visual Studio) was released in 1997, named as Visual
Studio 97 having version number 5.0. The latest version of Visual Studio is 15.0
which was released on March 7, 2017. It is also termed as Visual Studio 2017.
The supported .Net Framework Versions in latest Visual Studio is 3.5 to 4.7.
Java was supported in old versions of Visual Studio but in the latest version
doesn’t provide any support for Java language.
Visual Studio Editions
There are 3 editions of Microsoft Visual Studio as follows:
1. Community
It is a free version which is announced in 2014. All other editions are paid. This
contains the features similar to Professional edition. Using this edition, any
individual developer can develop their own free or paid apps like .Net
applications, Web applications and many more. In an enterprise organization,
this edition has some limitations. For example, if your organization have more
than 250 PCs and having annual revenue greater than $1 Million(US Dollars)
then you are not permitted to use this edition. In a non-enterprise organization,
up to five users can use this edition. Its main purpose is to provide the
Ecosystem(Access to thousands of extensions) and Languages(You can code in
C#, VB, F#, C++, HTML, JavaScript, Python, etc.) support.

.NET PROGRAMMING Page 192


UNIT IV

2. Professional
It is the commercial edition of Visual Studio. It comes in Visual Studio 2010
and later versions. It provides the support for XML and XSLT editing and
includes the tool like Server Explorer and integration with Microsoft SQL
Server. Microsoft provides a free trial of this edition and after the trial period,
the user has to pay to continue using it. Its main purpose is to provide
Flexibility(Professional developer tools for building any application type),
Productivity(Powerful features such as CodeLens improve your team’s
productivity), Collaboration(Agile project planning tools, charts, etc.) and
Subscriber benefits like Microsoft software, plus Azure, Pluralsight, etc.
3. Enterprise
It is an integrated, end to end solution for teams of any size with the demanding
quality and scale needs. Microsoft provides a 90-days free trial of this edition
and after the trial period, the user has to pay to continue using it. The main
benefit of this edition is that it is highly scalable and deliver high-quality
software.
Getting Started with Visual Studio 2017
 First, you have to download and install the Visual Studio. For that, you
can refer to Downloading and Installing Visual Studio 2017. Don’t forget
to select the .NET core workload during the installation of VS 2017. If
you forget then you have to modify the installation.
 You can see a number of tool windows when you will open the Visual
Studio and start writing your first program as follows:

.NET PROGRAMMING Page 193


UNIT IV

1. Code Editor: Where the user will write code.


2. Output Window: Here the Visual Studio shows the outputs,
compiler warnings, error messages and debugging information.
3. Solution Explorer: It shows the files on which the user is currently
working.
4. Properties: It will give additional information and context about the
selected parts of the current project.
 A user can also add windows as per requirement by choosing them
from View menu. In Visual Studio the tool windows are customizable as
a user can add more windows, remove the existing open one or can move
windows around to best suit.
 Various Menus in Visual Studio: A user can find a lot of menus on the
top screen of Visual Studio as shown below

1. Create, Open and save projects commands are contained


by File menu.
2. Searching, Modifying, Refactoring code commands are contained
by the Edit menu.
3. View Menu is used to open the additional tool windows in Visual
Studio.
4. Project menu is used to add some files and dependencies in the
project.
5. To change the settings, add functionality to Visual Studio via
extensions, and access various Visual Studio tools can be used by
using Tools menu.
 The below menu is known as the toolbar which provide the quick access
to the most frequently used commands. You can add and remove the
commands by going to View → Customize

Advantages of using Visual Studio IDE

.NET PROGRAMMING Page 194


UNIT IV

 A full-featured programming platform for several operating systems, the


web, and the cloud, Visual Studio IDE is available. Users can easily
browse the UI so they can write their code quickly and precisely.
 To help developers quickly identify potential errors in the code, Visual
Studio offers a robust debugging tool.
 Developers can host their application on the server with confidence
because they have eliminated anything that could lead to performance
issues.
 No matter what programming language developers are using, users of
Visual Studio can get live coding support. For faster development, the
Platform offers an autocomplete option. The built-in intelligent system
offers descriptions and tips for APIs.
 Through Visual Studio IDE you can easily collab with your teammates in
a same project. This IDE helps the developers to share, push and pull
their code with their teammates.
 Every user of Visual Studio has the ability to customize it. They have the
option to add features based on their needs. For example, they can
download add-ons and install extensions in their IDE. Even programmers
can submit their own extensions.
4.1 CREATING WEBSITES
First, you create an [Link] Core project. The project type comes with
all the template files you need to build a fully functional website.
1. On the start window, select Create a new project.

.NET PROGRAMMING Page 195


UNIT IV

2. In the Create a new project window, select C# from the Language list.
Next, select Windows from the All platforms list, and Web from the All
project types list.
After you apply the language, platform, and project type filters, select
the [Link] Core Web App (Razor Pages) template, and then select Next.

3. In the Configure your new project window, enter MyCoreApp in


the Project name field. Then, select Next.

4. In the Additional information window, verify that .NET 8.0 appears in


the Target Framework field.

.NET PROGRAMMING Page 196


UNIT IV

From this window, you can enable container support and add
authentication support. The drop-down menu for Authentication Type has the
following four options:
 None: No authentication.
 Individual accounts: These authentications are stored in a local or
Azure-based database.
 Microsoft identity platform: This option uses Microsoft Entra ID
or Microsoft 365 for authentication.
 Windows: Suitable for intranet applications.
Leave the Enable container support box unchecked, and
select None for Authentication Type.

Select Create.
Visual Studio opens your new project.
TOUR YOUR SOLUTION
1. The project template creates a solution with a single [Link] Core
project named MyCoreApp. Select the Solution Explorer tab to view its
contents.

.NET PROGRAMMING Page 197


UNIT IV

2. Expand the Pages folder.

3. Select the [Link] file, and view in the code editor.

4. Each .cshtml file has an associated code file. To open the code file in the
editor, expand the [Link] node in Solution Explorer, and select
the [Link] file.

.NET PROGRAMMING Page 198


UNIT IV

5. View the [Link] file in the code editor.

6. The project contains a wwwroot folder, which is the root for your
website. Expand the folder to view its contents.

You can put static site content such as CSS, images, and JavaScript
libraries directly in the paths where you want them.

.NET PROGRAMMING Page 199


UNIT IV

7. The project also contains configuration files that manage the web app at
run time. The default application configuration is stored
in [Link]. However, you can override these settings by
using [Link]. Expand the [Link] file
to view the [Link] file.

Run, debug, and make changes


1. In the toolbar, select the https button to build and run the app in debug
mode. Alternatively, press F5, or go to Debug > Start Debugging from
the menu bar.

.NET PROGRAMMING Page 200


UNIT IV

2. Visual Studio launches a browser window. You should then


see Home and Privacy pages in the menu bar.
3. Select Privacy from the menu bar. The Privacy page in the browser
renders the text that's set in the [Link] file.

4. Return to Visual Studio, and then press Shift+F5 to stop debugging. This
action closes the project in the browser window.
5. In Visual Studio, open [Link] for editing. Next, delete the
sentence, Use this page to detail your site's privacy policy and replace it
with This page is under construction as of @ViewData["TimeStamp"].

6. Now, let's make a code change. Select [Link]. Then, clean up


the using directives at the top of the file by selecting the following
shortcut:
Mouseover or select a greyed out using directive. A Quick Actions light
bulb appears below the caret or in the left margin. Select the light bulb, and then
select the expand arrow next to Remove unnecessary usings.

.NET PROGRAMMING Page 201


UNIT IV

Now select Preview changes to see what changes.

.NET PROGRAMMING Page 202


UNIT IV

Select Apply. Visual Studio deletes the unnecessary using directives from
the file.
7. Next, create a string for the current date that's formatted for your culture
or region by using the [Link] method.
 The first argument for the method specifies how the date should be
displayed. This example uses the format specifier (d) which
indicates the short date format.
 The second argument is the CultureInfo object that specifies the
culture or region for the date. The second argument determines,
among other things, the language of any words in the date, and the
type of separators used.
Change the body of the OnGet() method in [Link] to the
following code:
public void OnGet()
{
string dateTime = [Link]("d", new CultureInfo("en-
US"));
ViewData["TimeStamp"] = dateTime;
}
Notice that the following using directive automatically gets added to the top of
the file:
using [Link];
[Link] contains the CultureInfo class.
Press F5 to open your project in the web browser.
At the top of the web site, select Privacy to view your changes.

Close the web browser, press Shift+F5 to stop debugging.

.NET PROGRAMMING Page 203


UNIT IV

Change your Home page


1. In the Solution Explorer, expand the Pages folder, and then
select [Link].

The [Link] file corresponds with your Home page in the web app,
which runs in a web browser.

In the code editor, you see HTML code for the text that appears on
the Home page.

.NET PROGRAMMING Page 204


UNIT IV

2. Replace the Welcome text with Hello World!

3. Select https or press Ctrl+F5 to run the app and open it in a web
browser.

4. In the web browser, you see your new changes on the Home page.

5. Close the web browser, press Shift+F5 to stop debugging, and save your
project. You can now close Visual Studio.

4.2 THE ANATOMY OF A WEB FORM


In [Link], a Web Form is a page that provides an interface to interact with a
user in a web application. It serves as a container for both UI (User Interface)
components like text boxes, buttons, and labels, and the logic required to handle
events and user input. Web Forms are the foundation of [Link] web
applications and allow developers to build dynamic, data-driven websites.
Key Components of a Web Form in [Link]
A Web Form consists of several key components, such as the page's structure,
the controls, and the code-behind logic. Let’s break down each of these
elements.

.NET PROGRAMMING Page 205


UNIT IV

1. The Page Directive


At the top of every [Link] Web Form is a Page directive. It provides
essential information about the page, such as its language, the master page, or
the class associated with it. The @Page directive is written in the form of a
comment at the very beginning of the .aspx file.
Example of Page Directive:
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="[Link]" Inherits="[Link]" %>
Explanation of attributes:
 Language: Specifies the programming language used for the code-behind
file (usually C# or [Link]).
 AutoEventWireup: Indicates whether events are automatically wired up
between the controls and their event handlers (set to true by default).
 CodeBehind: Points to the file containing the C# code for the page's logic
(e.g., [Link]).
 Inherits: Specifies the fully qualified name of the class that the page is
derived from.

2. The HTML Structure


A Web Form, like any web page, includes an HTML structure that contains tags
such as <html>, <head>, <body>, and others. This is where the UI components
(controls, images, etc.) are defined.
Example of HTML Structure in an ASPX page:
<!DOCTYPE html>
<html>
<head>
<title>My Web Form</title>
</head>
<body>
<form id="form1" runat="server">
<!-- Controls and Content go here -->
</form>
</body>
</html>
The <form> tag is special in Web Forms. It has a runat="server" attribute,
which allows [Link] to manage and process the form on the server side.
3. The Form Tag (<form>)
The <form> tag in a Web Form serves as the container for all the controls (like
textboxes, buttons, etc.). It is important to note that it has the runat="server"
attribute, which enables [Link] to process the form on the server side.
Example:
<form id="form1" runat="server">
<!-- Web Controls go here -->
.NET PROGRAMMING Page 206
UNIT IV

</form>
The runat="server" attribute makes this form a server-side control. When the
page is loaded, [Link] processes this form and converts it into HTML that
the client browser can understand.

4. Web Controls
Web controls in [Link] are the building blocks of the user interface. They
include elements like buttons, textboxes, labels, grids, dropdowns, etc. These
controls can automatically generate HTML elements in the browser, and their
behavior is governed by event handlers defined in the code-behind.
Examples of Common Web Controls:
TextBox: For user input.
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
Button: To trigger an action.
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click" />
Label: For displaying messages.
<asp:Label ID="lblMessage" runat="server" Text="Enter your
name"></asp:Label>
DropDownList: For displaying a list of options.
<asp:DropDownList ID="ddlCountry" runat="server">
<asp:ListItem Text="Select Country" Value="0"></asp:ListItem>
<asp:ListItem Text="USA" Value="1"></asp:ListItem>
<asp:ListItem Text="Canada" Value="2"></asp:ListItem>
</asp:DropDownList>
Each control has a runat="server" attribute that makes it a server-side control,
which means it will be processed on the server and can interact with the code-
behind logic.

5. Code-Behind (C# or [Link])


In [Link] Web Forms, the code-behind is the server-side logic written in C#
or [Link] that responds to events triggered by user actions on the page (e.g.,
button clicks, page load). The code-behind file has the same name as the ASPX
page, with a .cs (C#) or .vb ([Link]) extension.
Example of Code-Behind File ([Link]):
using System;
using [Link];

namespace MyApp
{
public partial class Default : Page
{

.NET PROGRAMMING Page 207


UNIT IV

protected void Page_Load(object sender, EventArgs e)


{
if (!IsPostBack)
{
[Link] = "Enter your name";
}
}

protected void btnSubmit_Click(object sender, EventArgs e)


{
string userName = [Link];
[Link] = "Hello, " + userName;
}
}
}
Key elements in the code-behind:
 Page_Load: Handles the page load event. The Page_Load method is
called when the page is first loaded or refreshed.
 Event Handlers: In the example above, the btnSubmit_Click method
handles the Click event of the button control.
 Accessing Controls: In the code-behind, you can access controls (like
txtName, btnSubmit, etc.) directly to get user input or change the UI.

6. The Page Life Cycle


[Link] Web Forms have a well-defined page life cycle, which outlines the
sequence of events that occur when a page is requested, processed, and
rendered. Understanding this lifecycle is important for developers because
certain actions need to be done at specific stages.
Basic Stages of the Page Life Cycle:
1. Page Request: The page request is initiated when the user navigates to a
URL.
2. Page Initialization: During this stage, each control on the page is
initialized, i.e., assigned a unique ID.
3. Page Load: This is where you can write code to populate controls or set
properties based on the state of the page (e.g., Page_Load method).
4. Postback Event Handling: If the page is a postback (i.e., the user has
interacted with it), events like button clicks are handled.
5. Rendering: The controls are rendered to HTML, which is sent to the
client's browser.
6. Unload: Resources are released, and the page is cleaned up.

7. Master Pages (Optional)

.NET PROGRAMMING Page 208


UNIT IV

In larger applications, [Link] provides Master Pages to enable a consistent


layout across multiple pages. A master page defines a common structure (e.g.,
header, footer, and navigation) that can be reused across pages. Individual pages
then inherit this layout.
 Master Page ([Link]): Contains the common layout.
 Content Page ([Link]): Contains the content specific to each
page.
Example of Master Page:
<%@ Master Language="C#" CodeBehind="[Link]"
Inherits="[Link]" %>
<html>
<body>
<header>
<h1>Welcome to My Web Application</h1>
</header>
<div>
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>
</div>
</body>
</html>
Example of Content Page using Master Page:
<%@ Page Title="Home Page" Language="C#"
MasterPageFile="~/[Link]" CodeBehind="[Link]"
Inherits="[Link]" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent"
runat="server">
<h2>Home Page</h2>
<p>Welcome to the home page of our application!</p>
</asp:Content>

The anatomy of an [Link] Web Form includes several key components:


1. Page Directive: Defines important settings for the page.
2. HTML Structure: Contains the standard HTML tags (<html>, <body>,
etc.).
3. Form Tag: A special server-side form used to contain controls.
4. Web Controls: UI elements like textboxes, buttons, and labels that
interact with the user.
5. Code-Behind: Server-side logic that handles user events (like button
clicks).
6. Page Life Cycle: The sequence of events that happen when the page is
processed by [Link].

.NET PROGRAMMING Page 209


UNIT IV

7. Master Pages (optional): Used to provide a consistent layout across


multiple pages.
Together, these components make up a Web Form in [Link], enabling

WEB FORM FUNDAMENTALS

Web forms in [Link] are a key part of the framework, enabling developers to
create dynamic, interactive websites. [Link] Web Forms allows for a rich
user interface and the ability to manage state in a stateless environment. Here's a
detailed breakdown of the fundamentals of Web Forms in [Link]:
1. [Link] Web Forms Overview
 What are Web Forms? Web Forms is a part of the [Link] framework
that simplifies web application development by providing an event-driven
model. It uses a set of controls, like buttons and text boxes, to handle user
interaction.
 Page-based Model: Web Forms are page-centric, meaning each page (or
form) in an [Link] application corresponds to a file (typically with a
.aspx extension), which contains both HTML and server-side code.
 Server-Side Controls: Web Forms provide a range of built-in controls
(like text boxes, grids, buttons, and labels) that render as HTML elements
on the client side but execute on the server.
2. Basic Structure of a Web Form
A basic Web Form consists of:
 Page Directive: Defines settings like the language of the page, the type
of code-behind file, etc.
 HTML Markup: Defines the structure of the page, including forms,
tables, etc.
 Server-Side Controls: Controls that are rendered as HTML but have
server-side functionality. These controls are enclosed within <asp:...>
tags.
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="[Link]" Inherits="[Link]" %>
<html>
<body>
<form id="form1" runat="server">
.NET PROGRAMMING Page 210
UNIT IV

<h2>Welcome to [Link] Web Forms</h2>


<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click" />
</form>
</body>
</html>
 Code-behind (C# or [Link]): Handles the logic of the page. The file is
typically named with the .[Link] or .[Link] extension. In this file, you
handle events such as button clicks or form submissions.
public partial class Default : [Link]
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Load initial data, only on the first load
}
}

protected void btnSubmit_Click(object sender, EventArgs e)


{
// Handle button click logic
[Link]("Button clicked!");
}
}
3. Web Forms Life Cycle
The Web Forms page lifecycle consists of a series of events that occur from the
time the page is requested until the response is sent to the client. These stages
include:
 Page Request: The request for the page is made.
 Start: Initializes the page, where properties like Request, Response, and
Session are available.
 Initialization: Web controls are initialized but not yet rendered.
 Load: Controls are loaded with data.
 Postback Handling: If the page is a result of a postback (i.e., a user
action like a button click), this step handles it.
 Rendering: The page content is generated and sent to the client.
.NET PROGRAMMING Page 211
UNIT IV

 Unload: Cleanup code is executed after the response is sent.


4. State Management in Web Forms
Web Forms provide mechanisms to handle state, as the HTTP protocol is
inherently stateless. Here are the common state management techniques:
 ViewState: Stores values between requests for a page. It’s automatically
handled by [Link].
 Session: Stores user-specific data across pages in a session.
 Cookies: Stores small pieces of data on the client’s machine.
 QueryString: Passes data between pages via the URL.
 Hidden Fields: Allows data to persist across postbacks within the same
form.
Example of ViewState:
<asp:TextBox ID="txtName" runat="server" />
The value of txtName can be preserved using ViewState automatically, even after
a postback.
5. [Link] Web Forms Controls
Web Forms provides a rich set of controls that abstract complex HTML
functionality into easily usable components. Some common controls include:
 TextBox: For user input.
 Button: Triggers an event (e.g., a server-side method).
 DropDownList: A selection list.
 GridView: Displays data in a tabular format.
 Label: Displays text.
Example:
<asp:TextBox ID="txtName" runat="server" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click" />
<asp:Label ID="lblMessage" runat="server" />
6. Event Handling in Web Forms

.NET PROGRAMMING Page 212


UNIT IV

Event-driven programming is a hallmark of Web Forms. Events such as button


clicks, page load, and form submission trigger server-side code to execute.
 Button Click Event Example:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string name = [Link];
[Link] = "Hello, " + name;
}
7. Validation Controls
[Link] provides built-in controls for validating user input before processing
it:
 RequiredFieldValidator: Ensures a field is not empty.
 RangeValidator: Ensures the input falls within a specified range.
 RegularExpressionValidator: Ensures the input matches a regular
expression pattern.
 CompareValidator: Compares values between controls.
 CustomValidator: Allows custom validation logic.
Example of validation:
<asp:TextBox ID="txtEmail" runat="server" />
<asp:RegularExpressionValidator
ID="revEmail" runat="server"
ControlToValidate="txtEmail"
ValidationExpression="^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$"
ErrorMessage="Invalid Email Address" />
8. Master Pages and Themes
 Master Pages: Allows for consistent layout across multiple pages. A
master page contains common elements like headers, footers, and
navigation menus, which are shared across multiple content pages.
 Themes: Provides a way to define reusable styling for controls and pages.
Example of Master Page:
<%@ Master Language="C#" MasterPageFile="~/[Link]"
Inherits="[Link]" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

.NET PROGRAMMING Page 213


UNIT IV

<title>My Page</title>
</asp:Content>
9. Web Forms vs. MVC
 Web Forms is event-driven and page-based, ideal for developers who are
more familiar with desktop applications.
 MVC (Model-View-Controller): [Link] MVC is a more modern
approach focused on separating concerns with clear boundaries between
models, views, and controllers.
10. Deployment of Web Forms
Deploying an [Link] Web Forms application is similar to any web
application:
 The compiled assemblies (.dll files) and other resources (e.g., images,
scripts) are placed on a server.
 The .aspx pages and associated files are served through IIS (Internet
Information Services).
4.3 CONVERTING HTML PAGE TO AN [Link] PAGE
Converting an HTML page to an [Link] Web Forms page involves
integrating dynamic server-side functionality and [Link]-specific features
like server-side controls, event handling, and state management. Here's a step-
by-step guide on how to convert an HTML page to an [Link] Web Forms
page.
Step-by-Step Conversion Process
1. Create a New [Link] Web Forms Page
First, you need to create a new .aspx page in your [Link] project:
 In Visual Studio, right-click your project and select Add > New Item.
 Choose Web Form from the list, provide a name (e.g., [Link]),
and click Add.
This generates the basic structure of a Web Form page.
2. Convert HTML Tags to [Link] Server Controls
HTML tags that require server-side functionality need to be replaced with
[Link] server controls. These controls are enclosed within the <asp:...> tag.

.NET PROGRAMMING Page 214


UNIT IV

 TextBox: Replace an HTML <input> tag with an <asp:TextBox> control.


 Button: Replace <button> with <asp:Button>.
 Label: Replace plain text with an <asp:Label> control.
Example:
Original HTML:
<html>
<body>
<h1>Welcome to My Web Page</h1>
<input type="text" id="txtName" placeholder="Enter your name" />
<button onclick="alert('Hello!')">Submit</button>
</body>
</html>
Converted [Link]:
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="[Link]" Inherits="[Link]" %>
<html>
<body>
<h1>Welcome to My Web Page</h1>
<form id="form1" runat="server">
<!-- TextBox Control -->
<asp:TextBox ID="txtName" runat="server" placeholder="Enter your
name" />
<!-- Button Control -->
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click" />
</form>
</body>
</html>
3. Create a Code-behind File
Each [Link] Web Form has a corresponding code-behind file (with a
.[Link] or .[Link] extension). This file contains the server-side logic for
handling events, such as button clicks or form submissions.
 In your [Link] page, the button click (OnClick) event is referenced
in the OnClick="btnSubmit_Click" attribute.
 In the code-behind file ([Link]), you define the logic for the
button click event handler.

.NET PROGRAMMING Page 215


UNIT IV

Code-behind file ([Link]):


using System;
using [Link];

namespace MyApp
{
public partial class MyPage : Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Handle page load logic here
}

protected void btnSubmit_Click(object sender, EventArgs e)


{
string name = [Link];
[Link]("Hello, " + name);
}
}
}
4. Handling Form Submission and State Management
Unlike static HTML pages, [Link] Web Forms allows you to handle form
submissions on the server. The values from controls like TextBox,
DropDownList, etc., can be accessed in the code-behind file.
 Form Handling: The Button control in [Link] triggers an event on
the server when clicked. Use the OnClick attribute of the button to bind
the event handler.
 State Management: [Link] Web Forms has features like ViewState,
Session, and Cookies for managing data across postbacks. This allows
you to maintain data between page loads or after form submissions.
5. Add Validation Controls
If your HTML page uses JavaScript for validation, you can replace it with
[Link] validation controls like RequiredFieldValidator, RangeValidator, etc.
HTML-based validation:
<input type="text" id="txtEmail" placeholder="Enter your email" />
<button onclick="validateEmail()">Submit</button>
<script>

.NET PROGRAMMING Page 216


UNIT IV

function validateEmail() {
var email = [Link]("txtEmail").value;
if (!email) {
alert("Email is required!");
}
}
</script>
Converted [Link] with validation:
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="[Link]" Inherits="[Link]" %>
<html>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="txtEmail" runat="server" placeholder="Enter your
email" />
<asp:RequiredFieldValidator
ID="rfvEmail"
runat="server"
ControlToValidate="txtEmail"
ErrorMessage="Email is required!"
ForeColor="Red" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click" />
</form>
</body>
</html>
6. Replace JavaScript with Server-Side Logic (If Needed)
Any JavaScript logic, such as form submission or alerts, can be replaced with
server-side logic in the [Link] page. For example:
 Instead of using JavaScript alert() for showing messages, use a Label
control to display the result on the page.
 Complex form processing or validations can be handled on the server side
in the code-behind file, where you have access to the [Link]
framework.

7. Integrate Master Pages (Optional)

.NET PROGRAMMING Page 217


UNIT IV

If your original HTML page has common layout elements (e.g., headers,
footers, navigation bars), you can use Master Pages in [Link]. A master
page allows you to define common layout, which can be reused across multiple
pages.
Example:
<!-- [Link] -->
<%@ Master Language="C#" Inherits="[Link]" %>
<html>
<head><title><asp:ContentPlaceHolder ID="title" runat="server"
/></title></head>
<body>
<div id="header">Welcome to My Site</div>
<asp:ContentPlaceHolder ID="mainContent" runat="server" />
</body>
</html>

<!-- [Link] -->


<%@ Page Language="C#" MasterPageFile="~/[Link]"
Inherits="[Link]" %>
<asp:Content ID="title" ContentPlaceHolderID="title" runat="server">
My Web Page
</asp:Content>
<asp:Content ID="mainContent" ContentPlaceHolderID="mainContent"
runat="server">
<h1>Welcome to My Web Page</h1>
<!-- Page content goes here -->
</asp:Content>
8. Add CSS and JavaScript (Optional)
If your HTML page includes CSS or JavaScript files, you can continue to use
them in your [Link] page.
 Add CSS files inside <head> section using <link> tags.
 Add JavaScript files using <script> tags, either inline or linking external
.js files.
Final Result
The converted page might look like this:
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="[Link]" Inherits="[Link]" %>
<html>
.NET PROGRAMMING Page 218
UNIT IV

<body>
<form id="form1" runat="server">
<h1>Welcome to My Web Page</h1>
<asp:TextBox ID="txtName" runat="server" placeholder="Enter your
name" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click" />
<asp:Label ID="lblMessage" runat="server" />
</form>
</body>
</html>
And in the code-behind ([Link]):
using System;
using [Link];

namespace MyApp
{
public partial class MyPage : Page
{
protected void btnSubmit_Click(object sender, EventArgs
e)
{
string name = [Link];
[Link] = "Hello, " + name;
}
}
}
4.4 PAGE CLASS
In [Link] Web Forms, the Page class is a fundamental class that represents a
web page within the application. It serves as the base class for all Web Forms
pages and provides properties, methods, and events that are essential for
handling the page lifecycle, managing controls, handling user input, and
interacting with the server.
Key Features of the Page Class
The Page class is a part of the [Link] namespace and is used for
creating dynamic web pages. It provides several critical functions, such as
rendering content, managing server-side controls, and providing lifecycle events
to handle page requests.
.NET PROGRAMMING Page 219
UNIT IV

Here’s an overview of its key components:


1. Page Life Cycle Events
The Page class provides a series of events that occur during the lifecycle of a
page. These events allow you to execute specific code at various points in the
page's lifecycle. The common events in the Page lifecycle are:
 Page_Load: This event is fired when the page is loaded into memory. It
is often used for setting up initial data or performing tasks that should be
done once when the page is loaded.
 Page_Init: This event occurs when the page is first initialized, and the
controls are created. This is where controls are initialized.
 Page_PreRender: This event occurs just before the page is rendered to
the client. It is useful for making any final changes to controls, such as
modifying values before rendering.
 Page_Unload: This event is triggered after the page has been fully
rendered and the response is sent to the client. It is typically used for
clean-up tasks.
Example of Page Events:
public partial class MyPage : [Link]
{
// This is called when the page is initialized.
protected void Page_Init(object sender, EventArgs
e)
{
// Initialization code
}

// This is called when the page is loaded.


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Code to run only on the first request
}
}

// This is called just before the page is rendered.


protected void Page_PreRender(object sender, EventArgs e)
.NET PROGRAMMING Page 220
UNIT IV

{
// Final modifications before rendering
}

// This is called after the page is rendered.


protected void Page_Unload(object sender, EventArgs e)
{
// Clean-up code
}
}
2. Properties of the Page Class
The Page class exposes several properties that help manage the page and control
its behavior:
 Request: Provides access to the HTTP request sent by the client. You can
use this to read query strings, form data, cookies, and more.
 Response: Provides access to the HTTP response sent to the client. It is
used to write output, set HTTP headers, and handle redirects.
 Session: Provides access to the session state, allowing data to persist
across different requests from the same user.
 Application: Provides access to the global application state, which is
shared across all users.
 IsPostBack: A boolean property that indicates whether the page is being
loaded due to a postback (i.e., a re-submission of the page due to user
actions) or is being loaded for the first time.
 Controls: A collection of controls that are part of the page, including
standard HTML controls and [Link] server controls.
 Title: Gets or sets the title of the page, which is displayed in the
browser’s title bar or tab.
Example of using some page properties:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Initialize the page only on the first request.
Title = "Welcome to My [Link] Page"; // Set the page title

.NET PROGRAMMING Page 221


UNIT IV

[Link]("Hello, welcome to my website!"); // Output to the


browser
}
}
3. Handling Postbacks
In Web Forms, when a user submits a form, the page is sent back to the server
(known as a postback). The Page class provides the IsPostBack property to
check whether the current request is a postback or the first time the page is
being loaded.
 IsPostBack is used to determine whether the page is being loaded as a
result of a user action (e.g., clicking a button) or whether it is being
loaded for the first time.
Example:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Code to run only on the first page load (e.g., initializing data)
}
else
{
// Code to run on postback (e.g., handling user input)
}
}
4. Control Management
The Page class is responsible for managing the controls on the page. These
controls can be [Link] server controls (like Button, TextBox, etc.) or
standard HTML controls.
 Finding Controls: You can find controls dynamically on the page using
methods like FindControl().
Example of finding a control:
TextBox txtName =
(TextBox)FindControl("txtName"); string userName =
[Link];
 Control Hierarchy: The Controls collection property of the Page class
contains all the controls, including nested controls like those inside a

.NET PROGRAMMING Page 222


UNIT IV
Panel or Form.

.NET PROGRAMMING Page 223


UNIT IV

5. State Management in the Page Class


The Page class supports several ways to manage the state of controls and data
across page requests:
 ViewState: A mechanism that allows page-level state to be preserved
across postbacks. The Page class automatically handles ViewState for
controls.
 Session State: Data that is maintained across requests from the same user.
 QueryString: You can pass data in the URL via query parameters.
 Cookies: Small pieces of data stored on the client's browser.
Example of using ViewState:
// Store data in ViewState
ViewState["UserName"] = "JohnDoe";

// Retrieve data from ViewState


string userName = (string)ViewState["UserName"];
6. Response and Redirects
The Page class provides several methods to control the flow of the page and how it
interacts with the client, such as:
 [Link](): Writes data directly to the page's output stream.
 [Link](): Redirects the user to another page.
 [Link](): Transfers the current page processing to another page
on the server without making a round-trip to the client.
Example of redirecting:
protected void btnRedirect_Click(object sender, EventArgs e)
{
[Link]("[Link]");
}
7. Handling Errors
The Page class provides error handling mechanisms, such as:

.NET PROGRAMMING Page 224


UNIT IV

 Page_Error: An event that is triggered when an unhandled exception


occurs on the page. It allows you to handle errors gracefully.
Example of error handling:
protected void Page_Error(object sender, EventArgs e)
{
Exception ex = [Link]();
// Handle error (log it, show custom error message, etc.)
[Link]("[Link]");
}
Example of Using the Page Class
Here is an example of an [Link] Web Forms page that uses the Page class,
events, and properties:
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="[Link]" Inherits="[Link]" %>

<html>
<head>
<title>Welcome Page</title>
</head>
<body>
<form id="form1" runat="server">
<h2>Welcome to [Link] Web Forms</h2>
<asp:TextBox ID="txtName" runat="server" placeholder="Enter your
name" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click" />
<asp:Label ID="lblMessage" runat="server" />
</form>
</body>
</html>
Code-behind ([Link]):
using System;
using [Link];

namespace WebApplication1
{
public partial class Default : Page
{
protected void Page_Load(object sender, EventArgs e)

.NET PROGRAMMING Page 225


UNIT IV

{
// This is a good place to initialize data or controls.
if (!IsPostBack)
{
[Link] = "Please enter your name.";
}
}

protected void btnSubmit_Click(object sender, EventArgs e)


{
// Handle button click event and show message
[Link] = "Hello, " + [Link];
}
}
}

4.5 WEB CONTROLS


Web controls in [Link] Web Forms provide an abstraction for common
HTML elements, allowing developers to interact with them on the server side.
These controls are the building blocks for web forms and are used to create
dynamic, interactive web pages. Web controls are server-side controls that
generate HTML on the client side. They provide built-in support for handling
events, data binding, validation, and user interactions.
Types of Web Controls in [Link]
1. HTML Controls
o These are standard HTML elements such as <input>, <button>,
<select>, etc., but in [Link] Web Forms, they can be treated as
server controls, which means they can interact with the server-side
code and can have event handling.
Example:
html
<input type="text" id="txtName" runat="server" />
<button id="btnSubmit" runat="server"
onclick="btnSubmit_Click">Submit</button>
2. Web Server Controls
o These are [Link]-specific controls, like TextBox, Button, Label,
DropDownList, etc., that provide richer functionality than standard
.NET PROGRAMMING Page 226
UNIT IV

HTML controls. They are designed to be used with the server-side code.
Common Web Controls in [Link]
1. TextBox
The TextBox control is used to accept user input as a single-line text field.
Example:
<asp:TextBox ID="txtName" runat="server" placeholder="Enter your name" />
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
[Link] = "John Doe"; // Set initial value.
}
}
2. Button
The Button control is used to create a clickable button that can trigger events.
Example:
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click" />
Code-behind:
protected void btnSubmit_Click(object sender, EventArgs e)
{
[Link]("Button Clicked!");
}
3. Label
The Label control is used to display static text or dynamic content.
Example:
<asp:Label ID="lblMessage" runat="server" Text="Hello, World!" />
Code-behind:
[Link] = "This is a dynamic message";

.NET PROGRAMMING Page 227


UNIT IV

4. DropDownList
The DropDownList control is used to create a dropdown list that allows the user
to select a value from a list of options.
Example:
<asp:DropDownList ID="ddlCountries" runat="server">
<asp:ListItem Text="Select a Country" Value="" />
<asp:ListItem Text="USA" Value="USA" />
<asp:ListItem Text="India" Value="IND" />
</asp:DropDownList>

Code-behind:
string selectedCountry = [Link];
5. CheckBox
The CheckBox control is used to allow users to select or deselect an option.
Example:
<asp:CheckBox ID="chkAccept" runat="server" Text="I accept the terms and
conditions" />
Code-behind:
bool isChecked = [Link];

6. RadioButton
The RadioButton control is used when you want users to select one option from
a set of mutually exclusive options.
Example:
<asp:RadioButton ID="rdMale" runat="server" GroupName="Gender"
Text="Male" />
<asp:RadioButton ID="rdFemale" runat="server" GroupName="Gender"
Text="Female" />

Code-behind:
string gender = [Link] ? "Male" : "Female";
7. GridView
The GridView control is used to display data in a tabular format. It supports
data binding, pagination, sorting, and editing.

.NET PROGRAMMING Page 228


UNIT IV

Example:
<asp:GridView ID="gvUsers" runat="server"
AutoGenerateColumns="False"
OnRowCommand="gvUsers_RowCommand">
<asp:BoundField DataField="Name" HeaderText="Name"
SortExpression="Name" />
<asp:BoundField DataField="Email" HeaderText="Email"
SortExpression="Email" />
</Columns>
</asp:GridView>

Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Example data binding
[Link] = GetUsers();
[Link]();
}
}

private List<User> GetUsers()


{
// Return sample data
return new List<User>
{
new User { Name = "John", Email = "john@[Link]" },
new User { Name = "Jane", Email = "jane@[Link]" }
};
}

8. Repeater
The Repeater control is used to display repeated data items from a data source
in a customizable way. It is ideal for scenarios where you need full control over
the layout of each item.
Example:
<asp:Repeater ID="rptProducts" runat="server">
.NET PROGRAMMING Page 229
UNIT IV

<ItemTemplate>
<p><%# Eval("ProductName") %></p>
</ItemTemplate>
</asp:Repeater>

Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
[Link] = GetProducts();
[Link]();
}
}

private List<Product> GetProducts()


{
// Sample data
return new List<Product>
{
new Product { ProductName = "Laptop" },
new Product { ProductName = "Phone" }
};
}
9. FileUpload
The FileUpload control is used to allow users to upload files to the server.
Example:
<asp:FileUpload ID="fileUpload" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
OnClick="btnUpload_Click" />
Code-behind:
protected void btnUpload_Click(object sender, EventArgs e)
{
if ([Link])
{
string filename = [Link];
[Link]([Link]("~/Uploads/") + filename);

.NET PROGRAMMING Page 230


UNIT IV

}
}

Handling Events with Web Controls


Web controls in [Link] Web Forms support events, which allow the server-
side code to respond to user actions. For instance:
 Button Click Event: Triggered when the user clicks a button.
 TextChanged Event: Triggered when the text in a TextBox control
changes.
These events are handled in the code-behind by defining event handler methods.
Example of Handling Events:
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click" />
<asp:TextBox ID="txtName" runat="server"
TextChanged="txtName_TextChanged" AutoPostBack="true" />

Code-behind:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string name = [Link];
[Link] = "Hello, " + name;
}

protected void txtName_TextChanged(object sender, EventArgs e)


{
[Link] = "Text changed: " + [Link];
}

1. Button Controls
[Link] provides three types of button control:
 Button : It displays text within a rectangular area.
 Link Button : It displays text that looks like a hyperlink.
.NET PROGRAMMING Page 231
UNIT IV

 Image Button : It displays an image.


When a user clicks a button, two events are raised: Click and Command.
Basic syntax of button control:
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Click" / >
Common properties of the button control:

Property Description

The text displayed on the button. This is


Text
for button and link button controls only.

For image button control only. The


ImageUrl
image to be displayed for the button.

For image button control only. The text to


AlternateText be displayed if the browser cannot
display the image.

Determines whether page validation occurs


CausesValidation when a user clicks the button. The
default is true.

A string value that is passed to the


CommandName command event when a user clicks the
button.

A string value that is passed to the


CommandArgument command event when a user clicks the
button.

The URL of the page that is requested


PostBackUrl
when the user clicks the button.

2. Text Boxes and Labels

.NET PROGRAMMING Page 232


UNIT IV

Text box controls are typically used to accept input from the user. A text box
control can accept one or more lines of text depending upon the settings of the
TextMode attribute.
Label controls provide an easy way to display text which can be changed from
one execution of a page to the next. If you want to display text that does not
change, you use the literal text.
Basic syntax of text control:
<asp:TextBox ID="txtstate" runat="server" ></asp:TextBox>
Common Properties of the Text Box and Labels:

Property Description

Specifies the type of text box. SingleLine


creates a standard text box, MultiLIne
creates a text box that accepts more than
TextMode
one line of text and the Password causes
the characters that are entered to be
masked. The default is SingleLine.

Text The text content of the text box.

The maximum number of characters that


MaxLength
can be entered into the text box.

It determines whether or not text wraps


Wrap automatically for multi-line text box;
default is true.

Determines whether the user can change


ReadOnly the text in the box; default is false, i.e., the
user can not change the text.

The width of the text box in characters.


Columns The actual width is determined based on
the font that is used for the text entry.

Rows The height of a multi-line text box in lines.

.NET PROGRAMMING Page 233


UNIT IV

The default value is 0, means a single line


text box.

The mostly used attribute for a label control is 'Text', which implies the text
displayed on the label.
3. Check Boxes and Radio Buttons
A check box displays a single option that the user can either check or uncheck
and radio buttons present a group of options from which the user can select just
one option.
To create a group of radio buttons, you specify the same name for the
GroupName attribute of each radio button in the group. If more than one group
is required in a single form, then specify a different group name for each group.
If you want check box or radio button to be selected when the form is initially
displayed, set its Checked attribute to true. If the Checked attribute is set to true
for multiple radio buttons in a group, then only the last one is considered as
true.
Basic syntax of check box:
<asp:CheckBox ID= "chkoption" runat= "Server">
</asp:CheckBox>
Basic syntax of radio button:
<asp:RadioButton ID= "rdboption" runat= "Server">
</asp: RadioButton>
Common properties of check boxes and radio buttons:

Property Description

The text displayed next to the check box or


Text
radio button.

Specifies whether it is selected or not,


Checked
default is false.

GroupName Name of the group the control belongs to.

.NET PROGRAMMING Page 234


UNIT IV

4. List Controls
[Link] provides the following controls
 Drop-down list,
 List box,
 Radio button list,
 Check box list,
 Bulleted list.
These control let a user choose from one or more items from the list. List boxes
and drop-down lists contain one or more list items. These lists can be loaded
either by code or by the ListItemCollection editor.
Basic syntax of list box control:
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
</asp:ListBox>
Basic syntax of drop-down list control:
<asp:DropDownList ID="DropDownList1" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
Common properties of list box and drop-down Lists:

Property Description

The collection of ListItem objects that


represents the items in the control. This
Items
property returns an object of type
ListItemCollection.

Specifies the number of items displayed in


Rows the box. If actual list contains more rows
than displayed then a scroll bar is added.

SelectedIndex The index of the currently selected item. If

.NET PROGRAMMING Page 235


UNIT IV

more than one item is selected, then the


index of the first selected item. If no item
is selected, the value of this property is -1.

The value of the currently selected item. If


more than one item is selected, then the
SelectedValue value of the first selected item. If no item
is selected, the value of this property is an
empty string ("").

Indicates whether a list box allows single


SelectionMode
selections or multiple selections.

Common properties of each list item objects:

Property Description

Text The text displayed for the item.

Selected Indicates whether the item is selected.

Value A string value associated with the item.

It is important to notes that:


 To work with the items in a drop-down list or list box, you use the Items
property of the control. This property returns a ListItemCollection object
which contains all the items of the list.
 The SelectedIndexChanged event is raised when the user selects a
different item from a drop-down list or list box.

5. The List Item Collection


The ListItemCollection object is a collection of ListItem objects. Each ListItem
object represents one item in the list. Items in a ListItemCollection are
numbered from 0.
When the items into a list box are loaded using strings like:
[Link]("Blue"), then both the Text and Value properties of the list

.NET PROGRAMMING Page 236


UNIT IV

item are set to the string value you specify. To set it differently you must create
a list item object and then add that item to the collection.
The ListItemCollection Editor is used to add item to a drop-down list or list
box. This is used to create a static list of items. To display the collection editor,
select edit item from the smart tag menu, or select the control and then click the
ellipsis button from the Item property in the properties window.
Common properties of ListItemCollection:

Property Description

A ListItem object that represents the item


Item(integer)
at the specified index.

Count The number of items in the collection.

Common methods of ListItemCollection:

Methods Description

Adds a new item at the end of the


collection and assigns the string
Add(string)
parameter to the Text property of the
item.

Adds a new item at the end of the


Add(ListItem)
collection.

Inserts an item at the specified index


location in the collection, and
Insert(integer, string)
assigns string parameter to the text
property of the item.

Inserts the item at the specified


Insert(integer, ListItem)
index location in the collection.

Removes the item with the text


Remove(string)
value same as the string.

.NET PROGRAMMING Page 237


UNIT IV

Remove(ListItem) Removes the specified item.

Removes the item at the specified


RemoveAt(integer)
index as the integer.

Removes all the items of the


Clear
collection.

Returns the item whose value is


FindByValue(string)
same as the string.

Returns the item whose text is same


FindByValue(Text)
as the string.

6. Radio Button list and Check Box list


A radio button list presents a list of mutually exclusive options. A check box list
presents a list of independent options. These controls contain a collection of
ListItem objects that could be referred to through the Items property of the
control.
Basic syntax of radio button list:
<asp:RadioButtonList ID="RadioButtonList1" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
</asp:RadioButtonList>
Basic syntax of check box list:
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged">
</asp:CheckBoxList>
Common properties of check box and radio button lists:

Property Description

.NET PROGRAMMING Page 238


UNIT IV

This attribute specifies whether the table


tags or the normal html flow to use while
RepeatLayout
formatting the list when it is rendered. The
default is Table.

It specifies the direction in which the


controls to be repeated. The values
RepeatDirection
available are Horizontal and Vertical.
Default is Vertical.

It specifies the number of columns to use


RepeatColumns
when repeating the controls; default is 0.

7. Bulleted lists and Numbered lists


The bulleted list control creates bulleted lists or numbered lists. These controls
contain a collection of ListItem objects that could be referred to through the
Items property of the control.
Basic syntax of a bulleted list:
<asp:BulletedList ID="BulletedList1" runat="server">
</asp:BulletedList>
Common properties of the bulleted list:

Property Description

This property specifies the style and looks


BulletStyle
of the bullets, or numbers.

It specifies the direction in which the


controls to be repeated. The values
RepeatDirection
available are Horizontal and Vertical.
Default is Vertical.

It specifies the number of columns to use


RepeatColumns
when repeating the controls; default is 0.

.NET PROGRAMMING Page 239


UNIT IV

8. HyperLink Control
The HyperLink control is like the HTML <a> element.
Basic syntax for a hyperlink control:
<asp:HyperLink ID="HyperLink1" runat="server">
HyperLink
</asp:HyperLink>
It has the following important properties:

Property Description

Path of the image to be displayed by the


ImageUrl
control.

NavigateUrl Target link URL.

Text The text to be displayed as the link.

The window or frame which loads the


Target
linked page.

9. Image Control
The image control is used for displaying images on the web page, or some
alternative text, if the image is not available.
Basic syntax for an image control:
<asp:Image ID="Image1" runat="server">
It has the following important properties:

Property Description

Alternate text to be displayed in absence of


AlternateText
the image.

ImageAlign Alignment options for the control.

.NET PROGRAMMING Page 240


UNIT IV

Path of the image to be displayed by the


ImageUrl
control.

STATE MANAGEMENT
State Management in [Link] is a crucial concept because HTTP is a
stateless protocol, meaning that each request to the server is independent, and
the server does not remember previous requests or data associated with a
particular client. This stateless nature can be problematic when developing
dynamic, interactive applications that need to preserve data between requests
(such as user preferences, login credentials, form values, etc.).
[Link] provides several techniques for state management, which can be
broadly divided into two categories:
1. Client-Side State Management: Where the state is stored on the client
(e.g., in the browser).
2. Server-Side State Management: Where the state is stored on the
server. Let's explore each type of state management in more detail:
1. Client-Side State Management
Client-side state management stores the state on the client’s browser or device,
which reduces the load on the server. Common methods include:
1.1 Cookies
Cookies are small pieces of data stored on the client's browser. They can be
used to store simple information (like user preferences or session identifiers)
and persist data across requests and sessions.
Creating and Storing Cookies:
HttpCookie cookie = new HttpCookie("UserName");
[Link] = "JohnDoe";
[Link] = [Link](1); // Set expiration date
[Link](cookie);
Reading Cookies:
HttpCookie cookie = [Link]["UserName"];
if (cookie != null)
{
string userName = [Link];

.NET PROGRAMMING Page 241


UNIT IV

}
 Advantages:
o Persistent across sessions if expiration date is set.

o Can store small amounts of data.


 Disadvantages:
o Limited in size (typically 4 KB).
o Can be disabled by users in the browser settings.
o Not secure for sensitive data.
1.2 Query Strings
Query strings are a way to pass data between pages in the URL. You can append
data to the URL in the form of name/value pairs.
 Example:
Redirecting with query string: [Link]("[Link]?
UserName=JohnDoe&Age=30"); Retrieving data from query string:
string userName = [Link]["UserName"];
string age = [Link]["Age"];

 Advantages:
o Simple to implement.
o Visible in the URL (can be bookmarked or shared).
 Disadvantages:
o Visible to the user, so not suitable for sensitive data.
o Limited length (depending on the browser).
1.3 Hidden Fields
Hidden fields are HTML elements (<input type="hidden" />) that store data on
the client side. They are not visible to the user but can be accessed by the server.
Example:
<input type="hidden" id="hiddenField" value="SomeValue" runat="server"
/>
.NET PROGRAMMING Page 242
UNIT IV

string hiddenValue = [Link];


 Advantages:
o Data is not visible to the user.
o Suitable for storing small amounts of data.
 Disadvantages:
o The data can still be tampered with by the user (e.g., through
browser developer tools).

1.4 ViewState
ViewState is a mechanism that allows the storage of the state of a page's
controls between requests. The state is stored in a hidden field on the page and
is automatically managed by [Link].
 Example:
Enabling ViewState (by default it is enabled):
<asp:TextBox ID="txtName" runat="server" />
Retrieving ViewState in code-behind:
string userName = [Link];
 Advantages:
o Simple to use, automatically managed by [Link].
o Useful for preserving data between postbacks.
 Disadvantages:
o Can increase the page size, affecting performance (especially for
large pages).
o Visible to the user in the form of a hidden field, so not suitable for
sensitive data.

2. Server-Side State Management


Server-side state management stores data on the server, which is more secure
but can consume server resources. Common methods include:

.NET PROGRAMMING Page 243


UNIT IV

2.1 Session State


Session state stores data for a specific user session on the server. The data is
available across requests during the same session (until the session expires or
the user closes the browser).
 Example:
Storing data in session:
Session["UserName"] = "JohnDoe";
Retrieving data from session:
string userName = Session["UserName"] as string;
 Advantages:
o Data is stored on the server, making it more secure.
o Can store complex objects (not just strings).
o Automatically cleared when the session expires.
 Disadvantages:
o Consumes server resources.
o The session may expire after a certain period of inactivity.
 Session State Modes:
o In-Process: Stores session data in the server’s memory.
o StateServer: Stores session data in a separate process (out-of-
process).
o SQLServer: Stores session data in a database.

2.2 Application State


Application state is used to store data that is shared across all users and sessions
for the lifetime of the application. This is ideal for storing global application-
wide data.
 Example:
Storing data in application state:

.NET PROGRAMMING Page 244


UNIT IV

Application["AppName"] = "My [Link] Application";


Retrieving data from application state:
string appName = Application["AppName"] as string;
 Advantages:
o Data is shared among all users of the application.
o Suitable for storing global information (e.g., configuration settings,
application-wide constants).
 Disadvantages:
o Shared data can lead to concurrency issues if multiple users try to
modify the same data.
o Consumes server resources.
2.3 Cache
The cache is used to store data that is frequently accessed or computationally
expensive to generate. Data stored in the cache can be retrieved quickly without
having to recompute it or fetch it from a data source (e.g., database).
 Example:
Storing data in cache:
Cache["Data"] = "This is cached data";
Retrieving data from cache:
string cachedData = Cache["Data"] as string;
 Advantages:
o Provides faster access to data by reducing the need to access
databases or other slow sources.
o Can be used to store both data and objects.
 Disadvantages:
o Cache data can expire, so it may not always be available.
o Consumes server memory.
3. Comparison of State Management Methods

.NET PROGRAMMING Page 245


UNIT IV

Client- Server-
Method Advantages Disadvantages
Side Side
Simple to implement,
Limited size, security
Cookies Yes No persistent across
concerns
sessions
Simple to implement,
Query Limited length, visible to
Yes No visible in URL,
String user
shareable

Hidden Data is not visible to Data can be tampered


Yes No
Fields user, easy to use with
Automatically managed,
ViewState Yes No persists
Increases page size
across postbacks

Consumes server
Stores complex data,
Session State No Yes resources, session
secure on server
timeout
Consumes server
Application Shared across users,
No Yes resources, concurrency
State global access
issues
Fast data retrieval,
May expire, consumes
Cache No Yes
reduces database hits server memory

.NET PROGRAMMING Page 246


UNIT V

UNIT V
5.1 VALIDATION CONTROLS
[Link] validation controls validate the user input data to ensure that useless,
unauthenticated, or contradictory data don't get stored.
[Link] provides the following validation controls:
 RequiredFieldValidator
 RangeValidator
 CompareValidator
 RegularExpressionValidator
 CustomValidator
 ValidationSummary
Base Validator Class
The validation control classes are inherited from the BaseValidator class hence
they inherit its properties and methods. Therefore, it would help to take a look at
the properties and the methods of this base class, which are common for all the
validation controls:

Members Description

ControlToValidate Indicates the input control to validate.

Indicates how the error message is


Display
shown.

Indicates whether client side validation


EnableClientScript
will take.

Enabled Enables or disables the validator.

ErrorMessage Indicates error string.

Text Error text to be shown if validation fails.

IsValid Indicates whether the value of the control

.NET PROGRAMMING Page 247


UNIT V

is valid.

It indicates whether in case of an invalid


SetFocusOnError control, the focus should switch to the
related input control.

The logical group of multiple validators,


ValidationGroup
where this control belongs.

This method revalidates the control and


Validate()
updates the IsValid property.

1. Required Field Validator Control


The RequiredFieldValidator control ensures that the required field is not empty.
It is generally tied to a text box to force input into the text box.
The syntax of the control is as given:
<asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate"
ErrorMessage="Please choose a candidate"
InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>

2. RangeValidator Control
The RangeValidator control verifies that the input value falls within a
predetermined range.
It has three specific properties:

Properties Description

It defines the type of the data. The


Type available values are: Currency, Date,
Double, Integer, and String.

It specifies the minimum value of the


MinimumValue
range.

.NET PROGRAMMING Page 248


UNIT V

It specifies the maximum value of the


MaximumValue
range.

The syntax of the control is as given:


<asp:RangeValidator ID="rvclass" runat="server" ControlToValidate="txtclass"
ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"
MinimumValue="6" Type="Integer">

</asp:RangeValidator>

3. CompareValidator Control
The CompareValidator control compares a value in one control with a fixed
value or a value in another control.
It has the following specific properties:

Properties Description

Type It specifies the data type.

It specifies the value of the input control


ControlToCompare
to compare with.

It specifies the constant value to compare


ValueToCompare
with.

It specifies the comparison operator, the


available values are: Equal, NotEqual,
Operator GreaterThan, GreaterThanEqual,
LessThan, LessThanEqual, and
DataTypeCheck.

The basic syntax of the control is as follows:


<asp:CompareValidator ID="CompareValidator1" runat="server"
ErrorMessage="CompareValidator">

.NET PROGRAMMING Page 249


UNIT V

</asp:CompareValidator>

4. Regular Expression Validator


The RegularExpressionValidator allows validating the input text by matching
against a pattern of a regular expression. The regular expression is set in the
ValidationExpression property.
The following table summarizes the commonly used syntax constructs for
regular expressions:

Character
Description
Escapes

\b Matches a backspace.

\t Matches a tab.

\r Matches a carriage return.

\v Matches a vertical tab.

\f Matches a form feed.

\n Matches a new line.

\ Escape character.

Apart from single character match, a class of characters could be specified that
can be matched, called the metacharacters.

Metacharacters Description

. Matches any character except \n.

[abcd] Matches any character in the set.

[^abcd] Excludes any character in the set.

.NET PROGRAMMING Page 250


UNIT V

Matches any character specified in the


[2-7a-mA-M]
range.

Matches any alphanumeric character and


\w
underscore.

\W Matches any non-word character.

Matches whitespace characters like, space,


\s
tab, new line etc.

\S Matches any non-whitespace character.

\d Matches any decimal character.

\D Matches any non-decimal character.

Quantifiers could be added to specify number of times a character could appear.

Quantifier Description

* Zero or more matches.

+ One or more matches.

? Zero or one matches.

{N} N matches.

{N,} N or more matches.

{N,M} Between N and M matches.

The syntax of the control is as given:


<asp:RegularExpressionValidator ID="string" runat="server"
ErrorMessage="string"
ValidationExpression="string" ValidationGroup="string">

.NET PROGRAMMING Page 251


UNIT V

</asp:RegularExpressionValidator>

5. Custom Validator
The CustomValidator control allows writing application specific custom
validation routines for both the client side and the server side validation.
The client side validation is accomplished through the ClientValidationFunction
property. The client side validation routine should be written in a scripting
language, such as JavaScript or VBScript, which the browser can understand.
The server side validation routine must be called from the control's
ServerValidate event handler. The server side validation routine should be
written in any .Net language, like C# or [Link].
The basic syntax for the control is as given:
<asp:CustomValidator ID="CustomValidator1" runat="server"
ClientValidationFunction=.cvf_func. ErrorMessage="CustomValidator">

</asp:CustomValidator>

6. ValidationSummary
The ValidationSummary control does not perform any validation but shows a
summary of all errors in the page. The summary displays the values of the
ErrorMessage property of all validation controls that failed validation.
The following two mutually inclusive properties list out the error message:
 ShowSummary : shows the error messages in specified format.
 ShowMessageBox : shows the error messages in a separate
window. The syntax for the control is as given:
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
DisplayMode = "BulletList" ShowSummary = "true" HeaderText="Errors:"
/>
Validation Groups
Complex pages have different groups of information provided in different
panels. In such situation, a need might arise for performing validation separately
for separate group. This kind of situation is handled using validation groups.

.NET PROGRAMMING Page 252


UNIT V

To create a validation group, you should put the input controls and the
validation controls into the same logical group by setting
their ValidationGroup property.
Example
The following example describes a form to be filled up by all the students of a
school, divided into four houses, for electing the school president. Here, we use
the validation controls to validate the user input.
This is the form in design view:

The content file code is as given:


<form id="form1" runat="server">

<table style="width: 66%;">

<tr>
<td class="style1" colspan="3" align="center">
<asp:Label ID="lblmsg"
Text="President Election Form : Choose your president"
runat="server" />
</td>
</tr>

<tr>
<td class="style3">
Candidate:
</td>

.NET PROGRAMMING Page 253


UNIT V

<td class="style2">
<asp:DropDownList ID="ddlcandidate" runat="server"
style="width:239px">
<asp:ListItem>Please Choose a Candidate</asp:ListItem>
<asp:ListItem>M H Kabir</asp:ListItem>
<asp:ListItem>Steve Taylor</asp:ListItem>
<asp:ListItem>John Abraham</asp:ListItem>
<asp:ListItem>Venus Williams</asp:ListItem>
</asp:DropDownList>
</td>

<td>
<asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate"
ErrorMessage="Please choose a candidate"
InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>
</td>
</tr>

<tr>
<td
class="style3">
House:
</td>

<td class="style2">
<asp:RadioButtonList ID="rblhouse" runat="server"
RepeatLayout="Flow">
<asp:ListItem>Red</asp:ListItem>
<asp:ListItem>Blue</asp:ListItem>
<asp:ListItem>Yellow</asp:ListItem>
<asp:ListItem>Green</asp:ListItem>
</asp:RadioButtonList>
</td>

<td>
<asp:RequiredFieldValidator ID="rfvhouse" runat="server"
ControlToValidate="rblhouse" ErrorMessage="Enter your house
name" >

.NET PROGRAMMING Page 254


UNIT V
</asp:RequiredFieldValidator>

.NET PROGRAMMING Page 255


UNIT V

<br />
</td>
</tr>

<tr>
<td
class="style3">
Class:
</td>

<td class="style2">
<asp:TextBox ID="txtclass" runat="server"></asp:TextBox>
</td>

<td>
<asp:RangeValidator ID="rvclass"
runat="server" ControlToValidate="txtclass"
ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"
MinimumValue="6" Type="Integer">
</asp:RangeValidator>
</td>
</tr>

<tr>
<td
class="style3">
Email:
</td>

<td class="style2">
<asp:TextBox ID="txtemail" runat="server" style="width:250px">
</asp:TextBox>
</td>

<td>
<asp:RegularExpressionValidator ID="remail" runat="server"
ControlToValidate="txtemail" ErrorMessage="Enter your email"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-
.]\w+)*">
</asp:RegularExpressionValidator>

.NET PROGRAMMING Page 256


UNIT V
</td>
</tr>

.NET PROGRAMMING Page 257


UNIT V

<tr>
<td class="style3" align="center" colspan="3">
<asp:Button ID="btnsubmit" runat="server" onclick="btnsubmit_Click"
style="text-align: center" Text="Submit" style="width:140px" />
</td>
</tr>
</table>
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
DisplayMode ="BulletList" ShowSummary ="true" HeaderText="Errors:"
/>
</form>
The code behind the submit button:
protected void btnsubmit_Click(object sender, EventArgs e)
{
if ([Link])
{
[Link] = "Thank You";
}
else
{
[Link] = "Fill up all the fields";
}
}

5.2 ADROTATOR CONTROL


The AdRotator control in [Link] is used to display advertisements (or
banners) on a web page. It is a highly flexible and powerful control that can
display rotating ads, which means it can show a different ad every time the page
is refreshed or after a certain interval. The AdRotator control can pull data from
an XML file or a database to display a variety of ads based on the configuration.
Features of the AdRotator Control
 Displays advertisements: Can show images, text, or both as
advertisements.
 Rotating Ads: Can rotate through a series of ads automatically, providing
variety.

.NET PROGRAMMING Page 258


UNIT V

 Supports multiple sources: Ads can be loaded from XML files or a


database.
 Click Tracking: Tracks the number of times an ad is clicked, allowing
for performance analysis.
 Targeting: Supports displaying ads based on certain conditions, like user
behavior or location.
Basic Usage of the AdRotator Control
To use the AdRotator control, you need to configure it either through an XML file
or programmatically with a data source (like a database). Below is an example
of using the AdRotator with an XML file as the data source.
1. AdRotator Using an XML File
The AdRotator control can read ad details from an XML file that contains
information about the ads, including the ad image, the URL the ad should link
to, and the number of impressions (or weight) each ad should receive.
Step 1: Create the XML file
The XML file stores the ads and their associated data. Here's an example of an
XML file (e.g., [Link]):
<ads>
<ad>
<imageUrl>~/Images/[Link]</imageUrl>
<navigateUrl>[Link]
<altText>Ad 1</altText>
<impressions>1</impressions>
</ad>
<ad>
<imageUrl>~/Images/[Link]</imageUrl>
<navigateUrl>[Link]
<altText>Ad 2</altText>
<impressions>2</impressions>
</ad>
<ad>
<imageUrl>~/Images/[Link]</imageUrl>
<navigateUrl>[Link]
<altText>Ad 3</altText>
<impressions>3</impressions>
</ad>
.NET PROGRAMMING Page 259
UNIT V

</ads>
 imageUrl: The path to the advertisement image.
 navigateUrl: The URL where the user will be directed when the ad is
clicked.
 altText: The alternate text for the image.
 impressions: A weight value indicating the number of times the ad is
likely to be shown (higher values mean the ad is more likely to appear).
Step 2: Add the AdRotator Control in the [Link] Page
Once the XML file is created, you can add the AdRotator control in your
[Link] page (e.g., [Link]):
<asp:AdRotator ID="adRotator1" runat="server"
DataFile="~/[Link]"
Width="300px"
Height="250px" />
 DataFile: Points to the XML file that contains the ad data.
 Width: Defines the width of the ad display.

 Height: Defines the height of the ad display.


Step 3: Display the Ads
After adding the AdRotator control to the page, each time the page is loaded or
refreshed, it will randomly display an ad from the list in the [Link] file. The
AdRotator will automatically rotate through the available ads, and clicking on
any ad will take the user to the URL specified in the navigateUrl element.

2. AdRotator Using a Database


If you need to store ad details in a database instead of an XML file, you can
bind the AdRotator control to a data source (like a SqlDataSource or custom
database query).
Step 1: Define the Database Table
For this example, let's assume you have a table called Advertisements in your
database with the following structure:
CREATE TABLE Advertisements (
AdID INT PRIMARY KEY,
ImageUrl VARCHAR(255),

.NET PROGRAMMING Page 260


UNIT V

NavigateUrl VARCHAR(255),
AltText VARCHAR(255),
Impressions INT
);
Step 2: Bind the AdRotator to the Database
To bind the AdRotator to a SQL database, you'll use the SqlDataSource control
to fetch the ad data. Here's an example:
<asp:SqlDataSource ID="adsDataSource" runat="server"
ConnectionString="YourConnectionString"
SelectCommand="SELECT ImageUrl, NavigateUrl, AltText, Impressions
FROM Advertisements">
</asp:SqlDataSource>

<asp:AdRotator ID="adRotator1" runat="server"


DataSourceID="adsDataSource"
ItemStyle-Width="300px"
ItemStyle-Height="250px" />
 DataSourceID: Points to the SqlDataSource control that retrieves the ad
data.
 SelectCommand: The SQL query to fetch the ad data from the database.
Step 3: Bind the Data
The AdRotator will automatically bind the data from the SqlDataSource and
display the advertisements from the database. Each time the page is loaded, it
will randomly select an ad to display based on the data from the database.
3. Customizing the AdRotator
The AdRotator control has several properties that allow for customization:
 AdType: Specifies the type of content to display. It can be set to Image
(default), Text, or Both.
o AdType="Text": Displays text-based ads.
o AdType="Both": Displays both text and images.
 DataFile: The path to the XML file containing the ad data.
 DataSourceID: The ID of the data source control (e.g., SqlDataSource)
that provides the ad data.
 Width and Height: The dimensions of the ad.

.NET PROGRAMMING Page 261


UNIT V

 ItemStyle: Controls the appearance of the ad, such as its width and
height.
 Target: Specifies how the ad link should be opened. It can be set to
_blank (new tab/window) or _self (same window).

Example: AdRotator with Text and Image Ads


<asp:AdRotator ID="adRotator1" runat="server"
DataFile="~/[Link]"
AdType="Both"
Width="300px"
Height="250px"
ItemStyle-Width="300px"
ItemStyle-Height="250px" />
 This example displays both image and text ads, with the same
dimensions.

4. AdRotator Event Handling


You can handle various events with the AdRotator, such as when an ad is
clicked. Here's an example of handling the AdClicked event:
Step 1: Add the Event in the ASPX Page
<asp:AdRotator ID="adRotator1" runat="server"
DataFile="~/[Link]"
AdType="Both"
Width="300px"
Height="250px"
OnAdClicked="adRotator1_AdClicked" />
Step 2: Define the Event Handler in Code-Behind
protected void adRotator1_AdClicked(object sender, AdClickedEventArgs e)
{
string clickedAdUrl = [Link];
// You can log the clicked ad URL or perform other actions here
[Link]("Ad clicked: " + clickedAdUrl);
}

.NET PROGRAMMING Page 262


UNIT V

 AdClickedEventArgs provides access to the NavigateUrl of the clicked


ad.

WORKING WITH DATA


5.3 [Link] FUNDAMENTALS
[Link] (Active Data Objects for .NET) is a set of classes in the .NET
Framework used to interact with databases and other data sources, enabling
developers to work with data in a consistent way. It allows for querying,
updating, and managing data within relational databases like SQL Server,
Oracle, and MySQL. [Link] provides both in-memory data storage and
direct data access capabilities for database-driven applications.
Key Components of [Link]
1. Connection
The Connection object is responsible for establishing a connection to a
data source, such as a SQL Server database. It handles the connection
string and manages the actual communication with the database server.
o Common Connection Classes:
 SqlConnection for SQL Server.
 OleDbConnection for OLE DB providers (Access, Oracle).
 OracleConnection for Oracle databases.
 SqlCeConnection for SQL Server Compact Edition.
2. Command
The Command object is used to execute SQL statements or stored
procedures. It represents the SQL query that is sent to the database server.
o Common Command Classes:
 SqlCommand for SQL Server.
 OleDbCommand for OLE DB.
 OracleCommand for
Oracle. Commands can be used to:
o Execute SQL queries to retrieve data (SELECT).

.NET PROGRAMMING Page 263


UNIT V

o Execute non-query SQL commands (INSERT, UPDATE,


DELETE).
o Call stored procedures.
3. DataReader
The DataReader is used for forward-only, read-only access to the data
retrieved by a query. It is the most efficient way to read large sets of data
as it does not load all data into memory at once.
o Common DataReader Classes:
 SqlDataReader for SQL Server.
 OleDbDataReader for OLE DB.
 OracleDataReader for Oracle.
The DataReader is used with a SqlCommand to fetch data from the database.
4. DataAdapter
The DataAdapter acts as a bridge between the DataSet (an in-memory
representation of data) and the database. It allows you to retrieve data
from the database into a DataSet or DataTable and update the database.
o Common DataAdapter Classes:
 SqlDataAdapter for SQL Server.
 OleDbDataAdapter for OLE DB.
 OracleDataAdapter for Oracle.
5. DataSet
The DataSet is a disconnected, in-memory representation of data. It can hold
multiple DataTable objects, each representing a database table. DataSet is
useful when you need to work with data offline or with data that comes
from multiple tables.
o DataSet vs DataReader:
 DataSet: Disconnected, in-memory storage of data, allows
editing and working with multiple tables.
 DataReader: Connected, forward-only access to data from a
single table.
6. Transaction
A transaction ensures that a series of operations are executed in a way

.NET PROGRAMMING Page 264


UNIT V

that guarantees data consistency. If any operation fails, the entire


transaction is rolled back, preventing partial updates to the database.
o A transaction starts with BeginTransaction() and is committed with
Commit(). If an error occurs, Rollback() is called to revert the
changes.
Basic Workflow in [Link]
1. Establish a Connection
The first step in using [Link] is to establish a connection to the database.
This is done using the SqlConnection (or a similar class for other database
types).
string connectionString =
"Server=myServerAddress;Database=myDataBase;User
Id=myUsername;Password=myPassword;";
SqlConnection connection = new SqlConnection(connectionString);
[Link](); // Opens the connection to the database
2. Execute Commands
Once the connection is established, you can execute SQL commands using
SqlCommand. For example, you can retrieve data or modify data using
ExecuteReader or ExecuteNonQuery.
 Reading Data (ExecuteReader)
string query = "SELECT FirstName, LastName FROM Employees";
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader = [Link]();

while ([Link]())
{
[Link]($"{reader["FirstName"]} {reader["LastName"]}");
}
[Link]();
 Non-query Command (ExecuteNonQuery)

.NET PROGRAMMING Page 265


UNIT V

string insertQuery = "INSERT INTO Employees (FirstName, LastName,


DepartmentId) VALUES ('John', 'Doe', 1)";
SqlCommand command = new SqlCommand(insertQuery, connection);
int rowsAffected = [Link]();
[Link]($"{rowsAffected} rows inserted.");
 Query with Parameters
string query = "SELECT FirstName, LastName FROM Employees WHERE
DepartmentId = @DeptId";
SqlCommand command = new SqlCommand(query, connection);
[Link]("@DeptId", 1);
SqlDataReader reader = [Link]();

while ([Link]())
{
[Link]($"{reader["FirstName"]} {reader["LastName"]}");
}
[Link]();

3. Using DataAdapter and DataSet


A DataAdapter can be used to fill a DataSet or DataTable and allows you to
retrieve data into memory. This is useful when you need to manipulate or work
with the data offline.
string query = "SELECT * FROM Employees";
SqlDataAdapter dataAdapter = new SqlDataAdapter(query, connection);
DataSet dataSet = new DataSet();
[Link](dataSet, "Employees"); // Fill the DataSet with the Employees
table

foreach (DataRow row in [Link]["Employees"].Rows)


{
[Link]($"{row["FirstName"]} {row["LastName"]}");
}

.NET PROGRAMMING Page 266


UNIT V

4. Working with Transactions


Transactions ensure that a group of operations are executed as a single unit. If
any operation fails, the transaction can be rolled back to maintain data integrity.
SqlTransaction transaction = [Link]();
try
{
SqlCommand command1 = new SqlCommand("UPDATE Employees SET
DepartmentId = 2 WHERE DepartmentId = 1", connection, transaction);
[Link]();

SqlCommand command2 = new SqlCommand("INSERT INTO Employees


(FirstName, LastName, DepartmentId) VALUES ('Jane', 'Smith', 2)",
connection, transaction);
[Link]();

// Commit the transaction


[Link]();
[Link]("Transaction completed successfully.");
}
catch (Exception)
{
// Rollback the transaction if any error occurs
[Link]();
[Link]("Transaction rolled back due to an error.");
}
5. Closing the Connection
Once the operations are complete, you should close the database connection.
[Link]();
Working with Different Data Sources
[Link] can interact with various types of data sources, such as:
 SQL Server: Use SqlConnection, SqlCommand, SqlDataAdapter, etc.
 Oracle: Use OracleConnection, OracleCommand, OracleDataAdapter.
 OLE DB: Use OleDbConnection, OleDbCommand, OleDbDataAdapter
for older data sources like Microsoft Access.

.NET PROGRAMMING Page 267


UNIT V

Error Handling in [Link]


To ensure robustness, you should handle exceptions that may arise when working
with the database, such as connection errors, query errors, or transaction errors.
Use try-catch blocks to catch SqlException and other relevant exceptions.
try
{
// Database operations
}
catch (SqlException ex)
{
[Link]($"SQL Error: {[Link]}");
}
catch (Exception ex)
{
[Link]($"General Error: {[Link]}");
}
Summary of Key [Link] Classes and Methods
Class Purpose Methods
Connects to a SQL Server
SqlConnection Open(), Close()
database.
Executes SQL commands ExecuteReader(),
or
SqlCommand
stored procedures. ExecuteNonQuery()
Reads data from a database in a
SqlDataReader Read(), Close()
forward-only, read-only manner.
Acts as a bridge between a
SqlDataAdapter Fill(), Update()
database and a DataSet.
In-memory data storage for
DataSet Tables, Rows
multiple tables.
BeginTransaction(),
SqlTransaction Manages database transactions.
Commit(), Rollback()

.NET PROGRAMMING Page 268


UNIT V

5.4 DIRECT DATA ACCESS


Direct Data Access in [Link]
In [Link], direct data access refers to the method of interacting with a
database using a connected model. This model involves working directly with
the database by establishing a live, open connection between the application and
the database. This approach allows real-time interaction with the database to
retrieve, manipulate, and update data as needed.
The direct data access model in [Link] is typically achieved using the
following core classes:
 SqlConnection (for SQL Server)
 SqlCommand
 SqlDataReader
 ExecuteNonQuery
 ExecuteReader
 ExecuteScalar
Steps for Direct Data Access in [Link]
The following sections detail the steps required for direct data access in
[Link], including establishing a connection, executing SQL commands,
retrieving data, and handling errors.

1. Establish a Connection with the Database


To access data directly, we first need to establish a connection to the database.
This is done using the SqlConnection object, which connects to SQL Server (or
other database types can be connected using similar connection classes like
OleDbConnection or OracleConnection).
Example:
// Define the connection string
string connectionString =
"Server=myServerAddress;Database=myDatabase;User
Id=myUsername;Password=myPassword;";

// Create a SqlConnection object

.NET PROGRAMMING Page 269


UNIT V

SqlConnection connection = new SqlConnection(connectionString);

try
{
// Open the connection
[Link]();
[Link]("Connection Opened Successfully");
}
catch (Exception ex)
{
[Link]($"Error: {[Link]}");
}
finally
{
// Close the connection
[Link]();
}
 The connectionString contains the database details, such as the server
name, database name, and credentials.
 Open(): Opens the connection to the database.

 Close(): Closes the connection when done.

2. Execute SQL Commands


Once a connection is open, you can execute SQL commands using
SqlCommand. There are several types of operations you can perform:
 Data retrieval using ExecuteReader()
 Data manipulation (Insert, Update, Delete) using ExecuteNonQuery()
 Scalar queries using ExecuteScalar()
Example: Execute a Simple Query Using ExecuteReader
ExecuteReader() is used to retrieve data from the database (e.g., a SELECT
query). It returns a SqlDataReader object, which allows reading the result row
by row.
string query = "SELECT FirstName, LastName FROM Employees WHERE
DepartmentId = 1";

.NET PROGRAMMING Page 270


UNIT V

SqlCommand command = new SqlCommand(query, connection);


[Link](); // Open the connection

using (SqlDataReader reader = [Link]()) // ExecuteReader


retrieves data
{
while ([Link]()) // Read data row by row
{
[Link]($"First Name: {reader["FirstName"]}, Last Name:
{reader["LastName"]}");
}
}

[Link](); // Close the connection after operation


 ExecuteReader(): Executes the SQL query and returns a SqlDataReader
for accessing the result set.
Example: Execute an Update Command Using ExecuteNonQuery
ExecuteNonQuery() is used for SQL commands that do not return a result set,
such as INSERT, UPDATE, or DELETE statements. It returns the number of
rows affected.
string updateQuery = "UPDATE Employees SET DepartmentId = 2 WHERE
DepartmentId = 1";

SqlCommand command = new SqlCommand(updateQuery, connection);


[Link](); // Open the connection

int rowsAffected = [Link](); // Execute non-query SQL


command
[Link]($"{rowsAffected} rows updated.");

[Link](); // Close the connection after operation


 ExecuteNonQuery(): Executes the SQL command and returns the
number of rows affected.

Example: Execute a Scalar Query Using ExecuteScalar


ExecuteScalar() is used when you need a single value returned from the
database, such as the result of a COUNT, SUM, MAX, or even a simple column
value. It returns the first column of the first row in the result set.

.NET PROGRAMMING Page 271


UNIT V

string countQuery = "SELECT COUNT(*) FROM Employees WHERE


DepartmentId = 1";

SqlCommand command = new SqlCommand(countQuery, connection);


[Link](); // Open the connection

int count = (int)[Link](); // Execute scalar query to get a


single value
[Link]($"Number of employees in department 1: {count}");

[Link](); // Close the connection after operation


 ExecuteScalar(): Returns the first column of the first row in the result
set, or null if the result set is empty.

3. Handling Transactions in Direct Data Access


In [Link], you can also manage database transactions using
SqlTransaction. A transaction is useful when you want to execute a series of
SQL commands as a single unit of work, ensuring that either all commands are
committed, or none are.
Example: Using a Transaction
SqlTransaction transaction = null;

try
{
[Link](); // Open the connection
transaction = [Link](); // Begin the transaction

SqlCommand command1 = new SqlCommand("UPDATE Employees SET


DepartmentId = 3 WHERE DepartmentId = 1", connection, transaction);
[Link](); // Execute first command

.NET PROGRAMMING Page 272


UNIT V

SqlCommand command2 = new SqlCommand("INSERT INTO Employees


(FirstName, LastName, DepartmentId) VALUES ('Alice', 'Johnson', 3)",
connection, transaction);
[Link](); // Execute second command

// Commit the transaction if both commands succeed


[Link]();
[Link]("Transaction successful!");
}
catch (Exception ex)
{
// Rollback the transaction if any command fails
transaction?.Rollback();
[Link]($"Transaction failed:
{[Link]}");
}
finally
{
[Link](); // Close the connection after transaction
}
 BeginTransaction(): Starts a new transaction.
 Commit(): Commits the transaction, making all changes permanent.

 Rollback(): Rolls back the transaction, undoing any changes made during
the transaction.
4. Handling Errors in Direct Data Access
When performing database operations, it's important to handle exceptions
properly to ensure that your application can recover from errors such as network
failures, SQL errors, or connection issues.
Example: Basic Error Handling
try
{
SqlCommand command = new SqlCommand("SELECT * FROM
Employees", connection);
[Link]();
SqlDataReader reader = [Link]();

while ([Link]())
{
.NET PROGRAMMING Page 273
UNIT V

[Link]($"{reader["FirstName"]} {reader["LastName"]}");
}
}
catch (SqlException ex)
{
[Link]($"SQL Error: {[Link]}");
}
catch (Exception ex)
{
[Link]($"General Error: {[Link]}");
}
finally
{
[Link]();
}
 SqlException: Catches errors specific to SQL Server (like connection
issues or query syntax errors).
 Exception: Catches any general exceptions (such as network errors or
other unexpected issues).
Summary of Key [Link] Classes for Direct Data Access

Class Description

SqlConnection Represents the connection to the database.


Represents a SQL command or stored procedure to
SqlCommand
execute against the database.
Provides a forward-only, read-only cursor to retrieve data
SqlDataReader
from the database.
Manages database transactions, ensuring atomic
SqlTransaction
operations.
Executes a SQL command that returns rows (used with
ExecuteReader()
SqlDataReader).
Executes a SQL command that does not return rows (used
ExecuteNonQuery()
for INSERT, UPDATE, DELETE).

ExecuteScalar() Executes a SQL command that returns a single value

.NET PROGRAMMING Page 274


UNIT V

Class Description
(used for aggregate functions).

5.5 DISCONNECTED DATA ACCESS


Disconnected Data Access in [Link]
In [Link], disconnected data access refers to the approach where the
application retrieves data from the database, works with it in memory (offline),
and then updates the database if needed. Unlike the connected model, where a
live connection is maintained during the entire interaction with the database,
disconnected data access allows you to work with data in a more flexible and
efficient manner, especially when dealing with scenarios like working with data
in web applications.
The key component used for disconnected data access in [Link] is the DataSet
(and DataTable). These objects allow data to be retrieved from a database and
manipulated in-memory without maintaining an open connection to the
database.
Key Components of Disconnected Data Access in [Link]
1. DataSet
o A DataSet is an in-memory cache of data. It can hold multiple
DataTable objects, which can represent tables of data from a
database.
o It is disconnected because once the data is retrieved from the
database, the DataSet can be manipulated offline, without
maintaining a persistent connection.
2. DataTable
o A DataTable is a single table of data within a DataSet. It can
represent data from a specific database table.
o It holds rows and columns of data that can be accessed, modified,
and queried in memory.
3. DataAdapter

.NET PROGRAMMING Page 275


UNIT V

o The DataAdapter is used to fill a DataSet or DataTable with data


from the database and to push changes made to the DataSet back to
the database.
o It acts as a bridge between the in-memory data (the DataSet) and
the database.
4. Command
o The SqlCommand object (or other command objects like
OleDbCommand, OracleCommand) is used to perform database
operations like SELECT, INSERT, UPDATE, and DELETE.
Commands are often executed by the DataAdapter.

Steps for Disconnected Data Access in [Link]


1. Establish a Connection
You need to connect to the database, but only temporarily, just to retrieve
data into memory or update it.
2. Use Data Adapter to Retrieve Data
A DataAdapter is used to fill a DataSet or DataTable with data from the
database.
3. Manipulate Data Locally
Once the data is in the DataSet, it can be manipulated locally (offline)
without keeping the connection open.
4. Update the Database
After making any changes to the data in the DataSet, the changes can be
pushed back to the database using the DataAdapter.

Example of Disconnected Data Access in [Link]


Step 1: Establishing a Connection
First, establish a connection to the database using the SqlConnection object.
However, this connection will only be used temporarily to fetch data.
string connectionString =
"Server=myServerAddress;Database=myDatabase;User
Id=myUsername;Password=myPassword;";
SqlConnection connection = new SqlConnection(connectionString);

.NET PROGRAMMING Page 276


UNIT V

Step 2: Using DataAdapter to Retrieve Data


You use the SqlDataAdapter to retrieve data from the database and load it into a
DataSet. This object performs the task of populating the DataSet and filling it
with rows of data.
string query = "SELECT EmployeeID, FirstName, LastName, Department
FROM Employees";
SqlDataAdapter dataAdapter = new SqlDataAdapter(query, connection);

// Create a DataSet to hold the retrieved data


DataSet dataSet = new DataSet();

// Fill the DataSet with data from the database


[Link](dataSet, "Employees");
Here, the DataSet now contains a table called "Employees" that holds the data
returned by the SELECT query.
Step 3: Manipulating Data Locally
Once the data is in the DataSet, you can manipulate it offline, such as adding,
updating, or deleting rows. These changes will be tracked within the DataSet.
// Access the "Employees" table in the DataSet
DataTable employeesTable = [Link]["Employees"];

// Display the data in the DataTable


foreach (DataRow row in [Link])
{
[Link]($"{row["EmployeeID"]} - {row["FirstName"]}
{row["LastName"]} - {row["Department"]}");
}

// Modify data (example: change the department of an employee)


[Link][0]["Department"] = "Sales";
Step 4: Updating the Database
After modifying the data in the DataSet, the changes need to be written back to
the database. This can be done using the DataAdapter's Update method.

.NET PROGRAMMING Page 277


UNIT V

// Create the necessary commands for updating the database


SqlCommandBuilder commandBuilder = new
SqlCommandBuilder(dataAdapter);

// Use the DataAdapter's Update method to push changes to the database


[Link](dataSet, "Employees");

[Link]("Changes updated to the database.");


The SqlCommandBuilder automatically generates the necessary SQL
commands (for INSERT, UPDATE, and DELETE) based on the changes in the
DataSet.
Full Example:
using System;
using [Link];
using [Link];

class Program
{
static void Main()
{
// Step 1: Create the connection
string connectionString =
"Server=myServerAddress;Database=myDatabase;User
Id=myUsername;Password=myPassword;";
SqlConnection connection = new SqlConnection(connectionString);

// Step 2: Create the DataAdapter and DataSet


string query = "SELECT EmployeeID, FirstName, LastName, Department
FROM Employees";
SqlDataAdapter dataAdapter = new SqlDataAdapter(query, connection);

DataSet dataSet = new DataSet();

try
{
// Fill the DataSet with data
[Link](dataSet, "Employees");

// Step 3: Manipulate the data locally


DataTable employeesTable = [Link]["Employees"];

.NET PROGRAMMING Page 278


UNIT V

[Link]("Original Data:");
foreach (DataRow row in [Link])
{
[Link]($"{row["EmployeeID"]} - {row["FirstName"]}
{row["LastName"]} - {row["Department"]}");
}

// Modify data (example: change the department of the first employee)


[Link][0]["Department"] = "Sales";

[Link]("\nUpdated Data:");
foreach (DataRow row in [Link])
{
[Link]($"{row["EmployeeID"]} - {row["FirstName"]}
{row["LastName"]} - {row["Department"]}");
}

// Step 4: Update the database


SqlCommandBuilder commandBuilder = new
SqlCommandBuilder(dataAdapter);

// Push changes to the database


[Link](dataSet, "Employees");

[Link]("\nChanges updated to the database.");


}
catch (Exception ex)
{
[Link]($"Error: {[Link]}");
}
finally
{
[Link](); // Close the connection when done
}
}
}

.NET PROGRAMMING Page 279


UNIT V

Advantages of Disconnected Data Access


1. Reduced Database Load:
Since the application does not need to maintain an open connection, the
database server is not burdened with constant connections for every
operation.
2. Offline Data Manipulation:
The DataSet allows you to work with data offline, making it perfect for
scenarios where the user might need to work with data without being
connected to the database (such as in desktop applications or mobile
apps).
3. Improved Scalability:
With fewer open connections to the database, disconnected data access
can help improve the scalability of the system by reducing the number of
simultaneous connections the server needs to handle.
4. Concurrency Control:
Disconnected data access allows for the management of concurrency
issues by using strategies such as optimistic concurrency, where you can
check if data was modified by someone else before applying your
changes.
Common Operations in Disconnected Data Access
 Fill the DataSet:
The [Link]() method is used to retrieve data from the database
and load it into a DataSet or DataTable.
 Update the Database:
The [Link]() method pushes changes from the DataSet back
to the database.
 CommandBuilder:
A SqlCommandBuilder automatically generates INSERT, UPDATE, and
DELETE SQL commands, eliminating the need to manually write these
commands when updating the database.
 DataRowState:
Each row in a DataTable has a RowState property (like Added, Modified,
Deleted, or Unchanged) that helps track the changes made to the data.

.NET PROGRAMMING Page 280


UNIT V

DATA BINDING
5.6 DATA BINDING WITH [Link]
In [Link], data binding refers to the process of linking data from a
data source (such as a database, XML file, or in-memory collection) to user
interface (UI) controls like GridView, DropDownList, or TextBox in an
[Link] application. This allows the data to be displayed in the UI and, in
many cases, updated automatically when the data changes.
Data binding is commonly used to display data from a database in a UI
component, enabling seamless interaction between the data and the UI.
[Link] provides various methods for binding data, especially with
disconnected data access.
Key [Link] Classes for Data Binding
1. DataSet / DataTable
These are in-memory representations of data from the database. DataSet
is a collection of DataTable objects, while a DataTable represents a single
table of data.
2. DataAdapter
The DataAdapter is responsible for filling a DataSet or DataTable with
data from the database and saving changes back to the database.
3. BindingSource
A BindingSource acts as an intermediary between data and UI controls in
Windows Forms. It allows you to bind a DataTable or List<T> to UI
controls and manage their interactions.
4. UI Controls (e.g., GridView, DropDownList, TextBox)
These are the controls used to display and manipulate data on the web
page.
Steps for Data Binding in [Link]
1. Create a Connection to the Database
Establish a connection to the database using SqlConnection or another
connection class.
2. Create a DataAdapter and Retrieve Data
Use the SqlDataAdapter to execute a SELECT query and fill a DataSet or
DataTable with the results.

.NET PROGRAMMING Page 281


UNIT V

3. Bind Data to UI Controls


Bind the DataSet or DataTable to UI controls like GridView (in [Link]
Web Forms) or DataGridView (in Windows Forms).

Example of Data Binding in [Link]


In this example, we'll show how to bind data from a SQL Server database
to a GridView control in an [Link] Web Forms application.
Step 1: Create a SQL Connection and Retrieve Data
You need to retrieve data from a database using SqlDataAdapter and
store it in a DataSet or DataTable.
using System;
using [Link];
using [Link];
using [Link];

public partial class DataBindingExample : Page


{
// Define connection string
private string connectionString =
"Server=myServerAddress;Database=myDatabase;User
Id=myUsername;Password=myPassword;";

protected void Page_Load(object sender, EventArgs e)


{
if (!IsPostBack)
{
BindData();
}
}

// Method to bind data to GridView


private void BindData()
{
string query = "SELECT EmployeeID, FirstName, LastName,
Department FROM Employees";

.NET PROGRAMMING Page 282


UNIT V

using (SqlConnection connection = new


SqlConnection(connectionString))
{
SqlDataAdapter dataAdapter = new SqlDataAdapter(query,
connection);
DataSet dataSet = new DataSet();
[Link](dataSet, "Employees"); // Fill DataSet with data

// Bind DataSet to GridView


[Link] = [Link]["Employees"];
[Link](); // Perform the data binding
}
}
}

Explanation:
 SqlDataAdapter: Retrieves data from the database using a SQL query and
fills the DataSet.
 [Link]: The DataSource property of the GridView is set
to the DataTable inside the DataSet.
 [Link](): Binds the data to the GridView control, which
will display the data in the table format.
Step 2: Create the GridView in the [Link] Web Form
In the ASPX page, create a GridView control where the data will be
displayed:
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="[Link]"
Inherits="[Link]" %>

<!DOCTYPE html>
<html xmlns="[Link]
<head runat="server">
<title>Data Binding Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>

.NET PROGRAMMING Page 283


UNIT V

<h2>Employee List</h2>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="True" />
</div>
</form>
</body>
</html>
Explanation:
 AutoGenerateColumns="True": Automatically generates the columns
based on the data provided in the DataSource. If you want to manually
define columns, you can use the BoundField controls inside the
GridView.
 GridView1: This is the ID of the GridView control where the data will be
displayed.
Example of Data Binding in Windows Forms
In Windows Forms, the process is similar but uses controls like
DataGridView instead of GridView.
Step 1: Retrieve Data and Bind to DataGridView
using System;
using [Link];
using [Link];
using [Link];

public partial class MainForm : Form


{
private string connectionString =
"Server=myServerAddress;Database=myDatabase;User
Id=myUsername;Password=myPassword;";

public MainForm()
{
InitializeComponent();
}

private void MainForm_Load(object sender, EventArgs


e)
{
BindData();
}
.NET PROGRAMMING Page 284
UNIT V

private void BindData()


{
string query = "SELECT EmployeeID, FirstName, LastName,
Department FROM Employees";

using (SqlConnection connection = new


SqlConnection(connectionString))
{
SqlDataAdapter dataAdapter = new SqlDataAdapter(query,
connection);
DataSet dataSet = new DataSet();
[Link](dataSet, "Employees"); // Fill DataSet with data

// Bind DataSet to DataGridView


[Link] = [Link]["Employees"];
}
}
}

Step 2: Design the Form


In the Windows Forms Designer, drag a DataGridView control to the
form, and set the Name property to dataGridView1.
Explanation:
 [Link](): Retrieves the data and fills the DataSet.
 [Link]: The DataSource property binds the
DataTable inside the DataSet to the DataGridView control.
 DataGridView1: The data is displayed inside the DataGridView control.
Data Binding with BindingSource
In Windows Forms, you can use a BindingSource to simplify data
binding. The BindingSource acts as a mediator between the data and the
control, allowing for easier navigation and editing.
Example:
using System;
using [Link];
using [Link];

.NET PROGRAMMING Page 285


UNIT V

using [Link];

public partial class MainForm : Form


{
private string connectionString =
"Server=myServerAddress;Database=myDatabase;User
Id=myUsername;Password=myPassword;";
private BindingSource bindingSource = new BindingSource();

public MainForm()
{
InitializeComponent();
}

private void MainForm_Load(object sender, EventArgs e)


{
BindData();
}

private void BindData()


{
string query = "SELECT EmployeeID, FirstName, LastName,
Department FROM Employees";

using (SqlConnection connection = new


SqlConnection(connectionString))
{
SqlDataAdapter dataAdapter = new SqlDataAdapter(query,
connection);
DataSet dataSet = new DataSet();
[Link](dataSet, "Employees");

// Set the BindingSource DataSource


[Link] = [Link]["Employees"];

// Bind the DataGridView to the BindingSource


[Link] = bindingSource;
}
}
}
.NET PROGRAMMING Page 286
UNIT V

Explanation:
 BindingSource: A BindingSource is used to bind the DataTable to the
DataGridView.
 [Link]: Sets the DataSource of the BindingSource to
the DataTable inside the DataSet.
 [Link]: The DataGridView is bound to the
BindingSource rather than directly to the DataTable, making it easier to
manage complex data-binding scenarios.
5.7 DATA SOURCE CONTROLS
In [Link], Data Source Controls are not directly part of [Link], but
they are related to how data can be bound to web controls in [Link].
[Link] itself is a set of classes for data access and manipulation, such as
SqlConnection, SqlCommand, DataSet, and DataTable. However, in [Link],
Data Source Controls like SqlDataSource, ObjectDataSource,
LinqDataSource, and others provide an easy way to connect to various data
sources (like databases or custom objects) and bind that data to UI controls,
abstracting the underlying [Link] code.
Understanding Data Source Controls in the Context of [Link]
Although [Link] provides a lower-level approach to data access, [Link]
provides specialized data source controls that make it easier to work with data
sources like SQL databases, XML files, and business objects. These data source
controls allow developers to use declarative data binding without writing the
boilerplate [Link] code. In the background, these data source controls are
still leveraging [Link] or similar technologies to interact with databases.
Here are a few key Data Source Controls in [Link] that abstract [Link]
functionality:

1. SqlDataSource Control
 Purpose: The SqlDataSource control is used to connect to a SQL Server
database and execute SQL queries (e.g., SELECT, INSERT, UPDATE,
DELETE).
 Internals: It uses [Link]'s SqlConnection, SqlCommand, and
SqlDataAdapter to interact with the database.

.NET PROGRAMMING Page 287


UNIT V

 Usage: It allows you to define SQL commands directly in the markup,


and it can be bound to [Link] controls like GridView, DropDownList,
ListBox, etc.
Example:
<asp:SqlDataSource
ID="SqlDataSource1"
runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="SELECT EmployeeID, FirstName, LastName FROM
Employees"
UpdateCommand="UPDATE Employees SET FirstName = @FirstName,
LastName = @LastName WHERE EmployeeID = @EmployeeID">
</asp:SqlDataSource>
Explanation:
 ConnectionString: The connection string used to connect to the SQL
Server database (stored in [Link]).
 SelectCommand: The SQL query used to retrieve data from the database.
 UpdateCommand: The SQL query used for updating data in the
database (supports INSERT, UPDATE, and DELETE operations).
The SqlDataSource control internally uses [Link] classes (SqlConnection,
SqlCommand, etc.) to connect to the database, retrieve data, and handle CRUD
operations.
2. ObjectDataSource Control
 Purpose: The ObjectDataSource control allows you to bind data to
methods of custom objects (business objects) or classes that you define.
 Internals: It uses [Link] or any other data access technology
internally, but it abstracts the data source and allows you to work with
objects rather than directly working with database connections or SQL.
 Usage: Ideal for applications that use object-oriented programming to
fetch data (e.g., using a service layer, business logic, etc.).
Example:
<asp:ObjectDataSource
ID="ObjectDataSource1"
runat="server"

.NET PROGRAMMING Page 288


UNIT V

TypeName="[Link]"
SelectMethod="GetEmployees" />

Explanation:
 TypeName: The full name of the class that contains the method you want
to bind to.
 SelectMethod: The name of the method in the specified class that
retrieves data.
In the above example, the ObjectDataSource will call the GetEmployees
method of the EmployeeService class, which might internally use [Link] to
query a database.

3. LinqDataSource Control
 Purpose: The LinqDataSource control binds data to LINQ queries, which
can fetch data from any data source such as databases, collections, or
XML.
 Internals: Internally, it uses LINQ (Language Integrated Query) and can
leverage [Link] for database queries. It simplifies querying and
binding data from databases by using LINQ syntax.
 Usage: Ideal for developers who are using LINQ (such as LINQ to SQL,
LINQ to Entities) to query their data source.
Example:
<asp:LinqDataSource
ID="LinqDataSource1"
runat="server"
ContextTypeName="[Link]"
TableName="Employees" />
Explanation:
 ContextTypeName: The name of the LINQ data context class.
 TableName: The name of the table (entity) to bind to within the LINQ
context.

.NET PROGRAMMING Page 289


UNIT V

The LinqDataSource control simplifies binding a LINQ query to a data-bound


control. The LINQ query can retrieve data from a SQL database, and internally,
it uses [Link] to execute the query against the database.
4. EntityDataSource Control
 Purpose: The EntityDataSource control is designed to work with Entity
Framework (EF) models. It allows you to bind data to Entity Framework
DbSet objects.
 Internals: Uses Entity Framework to interact with databases, which in
turn uses [Link] to perform the actual database operations.
 Usage: Ideal for applications using Entity Framework to interact with the
database.
Example:
<asp:EntityDataSource
ID="EntityDataSource1"
runat="server"
ContextTypeName="[Link]"
EntitySetName="Employees" />

Explanation:
 ContextTypeName: The name of the Entity Framework context class.
 EntitySetName: The name of the EntitySet (a collection of entities) to
bind to.
This control simplifies data binding for applications that use Entity Framework.
Entity Framework handles the ORM (Object-Relational Mapping) and data
access, while the EntityDataSource abstracts much of the underlying logic.
5. XmlDataSource Control
 Purpose: The XmlDataSource control allows you to bind data to an XML
document or XML file.
 Internals: Uses the XmlDocument or XDocument classes in [Link]
to load and query the XML data.
 Usage: Ideal for applications that work with XML data as the data source.

.NET PROGRAMMING Page 290


UNIT V

Example:
<asp:XmlDataSource
ID="XmlDataSource1"
runat="server"
DataFile="~/App_Data/[Link]" />
Explanation:
 DataFile: The path to the XML file that contains the data.
This control is useful for data that is stored in an XML format, allowing easy data
binding to controls like GridView, Repeater, or ListView.
Advantages of Using Data Source Controls
1. Simplified Data Binding: You don't have to write [Link] code to
retrieve data, manage database connections, or handle CRUD operations.
2. Declarative Syntax: You can easily configure data sources using a
declarative syntax in your ASPX pages.
3. Built-in Features: Supports features like paging, sorting, and updating
without writing much code.
4. Reduced Boilerplate Code: Eliminates the need to manually write
database connection management code (like opening and closing
connections, executing queries, etc.).
Disadvantages of Using Data Source Controls
1. Less Flexibility: Data Source Controls may not support complex
scenarios, such as complex joins, advanced queries, or custom SQL.
2. Performance Considerations: For large-scale

5.8 THE DATA CONTROLS


In [Link], the concept of "data controls" typically refers to the way data is
manipulated and presented within an application. However, in [Link], data
controls are the UI controls used to display and manage data, often interacting
with [Link] to retrieve and display information from data sources like
databases, XML, or in-memory data structures.

.NET PROGRAMMING Page 291


UNIT V

Although [Link] itself doesn’t provide direct data controls (like [Link]
does with controls such as GridView, DropDownList, etc.), it provides the data
handling backend that these controls rely on to perform data operations.
[Link] allows developers to fetch, update, and manage data via its classes,
while [Link]’s data-bound controls use [Link] for the data access
layer.
Here’s an overview of some of the important data controls in the context of
[Link] (which use [Link] behind the scenes):
1. GridView Control
 Purpose: The GridView control is a powerful data display control that
presents data in a tabular format. It is used for displaying, editing, and
paging through data retrieved from a data source.
 [Link] Integration: Data can be bound to a GridView using various
data source controls (e.g., SqlDataSource, ObjectDataSource, etc.), which
internally use [Link] to retrieve the data.
Example:
<asp:GridView
ID="GridView1"
runat="server"
AutoGenerateColumns="True"
DataSourceID="SqlDataSource1">
</asp:GridView>
 Important Features:
o Auto Paging, Sorting, and Editing: Built-in features for
pagination, sorting, and editing operations without writing extra
code.
o Custom Bound Fields: You can bind data columns manually using
the BoundField or TemplateField.
o Integration with [Link]: You can bind data from an
[Link] DataSet, DataTable, or a database using a
SqlDataSource.
2. DropDownList Control
 Purpose: The DropDownList control is a dropdown menu that allows
users to select an item from a list. It is commonly used for displaying a
set of predefined options, often sourced from a database.

.NET PROGRAMMING Page 292


UNIT V

 [Link] Integration: Typically bound to a database using [Link]


through SqlDataSource or ObjectDataSource.
Example:
<asp:DropDownList
ID="DropDownList1"
runat="server"
DataSourceID="SqlDataSource1"
DataTextField="FirstName"
DataValueField="EmployeeID">
</asp:DropDownList>
 Important Features:
o Data Binding: It can be populated dynamically from [Link]
data sources.
o DataTextField: Specifies the property or column to display in the
dropdown.
o DataValueField: Specifies the value that gets submitted when an
item is selected.
3. ListBox Control
 Purpose: The ListBox control displays a list of items in a box, where the
user can select one or more items.
 [Link] Integration: Similar to DropDownList, the ListBox can be
bound to data from an [Link] data source like SqlDataSource.
Example:
<asp:ListBox
ID="ListBox1"
runat="server"
DataSourceID="SqlDataSource1"
DataTextField="FirstName"
DataValueField="EmployeeID">
</asp:ListBox>
 Important Features:
o Multiple Selection: Can allow multiple selections by setting the
SelectionMode property.
o Data Binding: Like DropDownList, it can bind to data from
[Link] data sources.

.NET PROGRAMMING Page 293


UNIT V

4. DetailsView Control
 Purpose: The DetailsView control is used to display a single record at a
time in a form-like format. It is typically used for viewing and editing
detailed information for a single entity, such as an employee’s details.
 [Link] Integration: It works with data sources like SqlDataSource
or ObjectDataSource to fetch and update data.
Example:
<asp:DetailsView
ID="DetailsView1"
runat="server"
AutoGenerateRows="True"
DataSourceID="SqlDataSource1">
</asp:DetailsView>
 Important Features:
o Automatic Editing and Insertion: Can automatically generate
fields for data editing or insertion.
o Master-Detail Views: Frequently used in conjunction with a
GridView to create master-detail data views.
5. Repeater Control
 Purpose: The Repeater control is a more lightweight data-bound control
that displays data in a custom template format. It’s used for situations
where you need full control over the layout of data.
 [Link] Integration: You can bind a Repeater control to [Link]
objects like DataTable, DataSet, or a data source control like
SqlDataSource.
Example:
<asp:Repeater
ID="Repeater1"
runat="server"
DataSourceID="SqlDataSource1">
<ItemTemplate>
<div><%# Eval("FirstName") %> <%# Eval("LastName") %></div>
</ItemTemplate>
</asp:Repeater>
 Important Features:

.NET PROGRAMMING Page 294


UNIT V

o Custom Layout: You can define how each record should be


displayed with ItemTemplate, AlternatingItemTemplate, etc.
o Flexible Data Binding: Great for complex layouts or when you
need fine control over how each record is rendered.
6. FormView Control
 Purpose: The FormView control is used to display a single record at a
time, similar to DetailsView, but with more customization and flexibility
for displaying records in custom layouts.
 [Link] Integration: It uses data source controls (like SqlDataSource)
to fetch and display data.
Example:
<asp:FormView
ID="FormView1"
runat="server"
DataSourceID="SqlDataSource1"
ItemTemplate="<div><%# Eval('FirstName') %> <%# Eval('LastName')
%></div>">
</asp:FormView>
 Important Features:
o Custom Layouts: You can create detailed, custom views of each
record.
o Insert, Update, Delete Support: Supports form-based editing for
CRUD operations.

Advantages of Data Controls in [Link]


1. Declarative Data Binding: You can declaratively bind data to controls
without writing repetitive code for opening connections, executing
queries, and handling result sets.
2. Built-in Features: Controls like GridView and DetailsView provide
features such as paging, sorting, and editing, which are often complex to
implement manually.
3. Consistency: Data controls provide consistent patterns for displaying and
editing data, making your UI simpler to design and maintain.

.NET PROGRAMMING Page 295


UNIT V

Disadvantages of Data Controls in [Link]


1. Limited Flexibility: Some data-bound controls (like GridView) may not
provide the flexibility needed for highly customized data presentation.
2. Tight Coupling: These controls are tightly coupled with data access
logic, making it difficult to test business logic or change the data layer
without modifying UI code.
3. Performance: For large datasets, controls like GridView can face
performance issues due to the overhead of data binding and rendering
large numbers of records.

5.9 THE GRID VIEW


The GridView control is one of the most commonly used data controls in
[Link] for displaying data in a tabular format. It is designed to show a
collection of data (such as records from a database) in a structured way and
provides built-in features like paging, sorting, editing, and deleting without the
need for writing a lot of code.
Key Features of GridView
1. Data Binding: You can bind the GridView control to a variety of data
sources, including [Link] objects (like DataSet, DataTable,
DataReader), and data source controls (SqlDataSource,
ObjectDataSource, LinqDataSource).
2. Paging: The GridView control supports paging, which enables the
display of large sets of data across multiple pages. Users can navigate
between pages to view different sets of records.
3. Sorting: You can easily enable sorting of data by columns, and GridView
will automatically handle sorting without requiring custom code.
4. Editing, Inserting, and Deleting: The GridView supports inline editing,
deleting, and inserting of records. It generates UI elements for modifying
data in a tabular form, and developers can define the logic for performing
these operations.
5. Template Support: The GridView allows custom templates for rows,
columns, headers, and footers. You can use templates to create complex
layouts.

.NET PROGRAMMING Page 296


UNIT V

Basic Structure of a GridView Control


A basic GridView control in [Link] consists of the following elements:
 Data Source: The data that the GridView will display (e.g., a
SqlDataSource, ObjectDataSource, or a custom data object).
 Columns: The individual columns inside the GridView to display the
data. These columns can be automatically generated or you can manually
define them.
 Templates: Templates like ItemTemplate, EditItemTemplate, etc., to
define how data should be displayed and edited.
Example of a Basic GridView with SqlDataSource
Here’s a simple example of using the GridView control with a SqlDataSource in an
[Link] page.
WebForm (ASPX Page):
<asp:SqlDataSource
ID="SqlDataSource1"
runat="server"
ConnectionString="<%$ ConnectionStrings:MyDatabaseConnectionString
%>"
SelectCommand="SELECT EmployeeID, FirstName, LastName, JobTitle
FROM Employees">
</asp:SqlDataSource>

<asp:GridView
ID="GridView1"
runat="server"
AutoGenerateColumns="True"
DataSourceID="SqlDataSource1"
AllowPaging="True"
AllowSorting="True"
OnRowEditing="GridView1_RowEditing"
OnRowDeleting="GridView1_RowDeleting"
OnRowUpdating="GridView1_RowUpdating"
OnRowCancelingEdit="GridView1_RowCancelingEdit">
</asp:GridView>

.NET PROGRAMMING Page 297


UNIT V

Explanation of the Example:


1. SqlDataSource:
o The SqlDataSource control is used to connect to a SQL database
and retrieve data. It uses a SelectCommand to specify the SQL
query (SELECT EmployeeID, FirstName, LastName, JobTitle
FROM Employees) and a ConnectionString to connect to the
database.
2. GridView:
o AutoGenerateColumns="True": This property automatically
generates the columns for the GridView based on the fields
returned by the SqlDataSource.
o DataSourceID="SqlDataSource1": The GridView is bound to
the SqlDataSource1 control to fetch data.
o AllowPaging="True": Enables paging for the grid (for large
datasets).
o AllowSorting="True": Allows the user to sort the grid data by
clicking the column headers.
o Event Handlers: The GridView provides various events such as
RowEditing, RowDeleting, RowUpdating, and RowCancelingEdit
to handle operations like editing, deleting, and updating data in the
grid.
Customizing Columns in GridView
You can customize the GridView columns by manually defining them using the
BoundField, TemplateField, and other field types.
Example: Custom Column Definitions
<asp:GridView
ID="GridView1"
runat="server"
AllowPaging="True"
AllowSorting="True"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="EmployeeID" HeaderText="Employee ID"
SortExpression="EmployeeID" />

.NET PROGRAMMING Page 298


UNIT V

<asp:BoundField DataField="FirstName" HeaderText="First Name"


SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="Last Name"
SortExpression="LastName" />
<asp:BoundField DataField="JobTitle" HeaderText="Job Title"
SortExpression="JobTitle" />
<asp:CommandField ShowEditButton="True" ShowDeleteButton="True"
/>
</Columns>
</asp:GridView>
Explanation:
 BoundField: Each BoundField specifies a data field from the data source
to display in the column (e.g., EmployeeID, FirstName, etc.).
 CommandField: Provides buttons for editing and deleting records in the
grid. ShowEditButton="True" shows the "Edit" button, and
ShowDeleteButton="True" shows the "Delete" button.
Enabling Paging in GridView
Paging is one of the core features of the GridView control that allows you to
break large datasets into manageable pages. This is useful for improving
performance and user experience when displaying large amounts of data.
To enable paging, set AllowPaging="True" and specify the PageSize property,
which controls the number of records per page.
Example:
<asp:GridView
ID="GridView1"
runat="server"
DataSourceID="SqlDataSource1"
AllowPaging="True"
PageSize="10" />
This example displays 10 records per page, and the GridView will automatically
generate pagination controls.

Sorting Data in GridView


Sorting allows users to reorder the displayed data based on column headers.

.NET PROGRAMMING Page 299


UNIT V

To enable sorting, set the AllowSorting="True" property on the GridView. You


also need to handle the Sorting event to re-query the data based on the sort
order.
Example:
<asp:GridView
ID="GridView1"
runat="server"
AllowSorting="True"
DataSourceID="SqlDataSource1"
OnSorting="GridView1_Sorting">
</asp:GridView>
Code Behind (C#):
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
[Link] = [Link];
[Link] = "SELECT EmployeeID, FirstName,
LastName, JobTitle FROM Employees ORDER BY " + [Link];
[Link]();
}
This example uses the Sorting event to capture the column clicked by the user
and sort the data based on that column.

Editing, Updating, and Deleting Records


The GridView control provides built-in features to edit, update, and delete
records from the data source. To enable these features, you can use command
buttons like "Edit", "Update", and "Delete" that are automatically displayed in
the grid when CommandField is added.
Example: Editing and Updating
<asp:GridView
ID="GridView1"
runat="server"
DataSourceID="SqlDataSource1"
AllowPaging="True"
AllowSorting="True"
AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="EmployeeID" HeaderText="Employee ID"
SortExpression="EmployeeID" />
.NET PROGRAMMING Page 300
UNIT V

<asp:BoundField DataField="FirstName" HeaderText="First Name"


SortExpression="FirstName" />
<asp:CommandField ShowEditButton="True" ShowDeleteButton="True"
/>
</Columns>
</asp:GridView>
Code Behind (C#):
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs
e)
{
[Link] = [Link];
BindGrid(); // Rebind the data to reflect the edited row
}

protected void GridView1_RowUpdating(object sender,


GridViewUpdateEventArgs e)
{
int employeeID =
Convert.ToInt32([Link][[Link]].Value);
string firstName =
((TextBox)[Link][[Link]].FindControl("txtFirstName")).Text;
string lastName =
((TextBox)[Link][[Link]].FindControl("txtLastName")).Text;

// Update the database with new values (using [Link])

[Link] = -1;
BindGrid();
}

protected void GridView1_RowDeleting(object sender,


GridViewDeleteEventArgs e)
{
int employeeID = [Link]
32([Link][[Link]].Value);
// Delete record from database (using [Link])

BindGrid();
}

.NET PROGRAMMING Page 301


UNIT V

private void BindGrid() { [Link] = "SELECT


EmployeeID, FirstName, LastName, JobTitle FROM Employees";
[Link](); }

In this example, the `RowEditing`, `RowUpdating`, and `RowDeleting` events


handle editing, updating, and deleting operations, respectively. After each
operation, the grid is rebound to reflect the changes.
5.10 GENERATING CRYSTAL REPORTS
Crystal Reports is a powerful tool that enables developers to create detailed
reports based on data from a variety of data sources. In [Link], you can
integrate Crystal Reports into your web applications to generate, view, export,
and print reports. Below are the steps to generate Crystal Reports and display
them in an [Link] application.
Steps for Generating Crystal Reports in [Link]
1. Install Crystal Reports for Visual Studio
To generate and work with Crystal Reports in Visual Studio, you need to install
SAP Crystal Reports for Visual Studio. Follow these steps:
 Download and install SAP Crystal Reports for Visual Studio from the
SAP website: SAP Crystal Reports.
 After installation, you should see Crystal Reports options in Visual
Studio's Toolbox.
2. Create a Crystal Report
1. Add a Crystal Report to Your [Link] Project:
o In Visual Studio, right-click your project in Solution Explorer and
select Add > New Item.
o Choose Crystal Report from the list of templates and name it
(e.g., [Link]).
o Click Add to create a new Crystal Report file.
2. Design the Report:
o Open the Crystal Report Designer in Visual Studio.
o Use the Database Expert to connect to your data source (such as
SQL Server, Oracle, or any other supported database).

.NET PROGRAMMING Page 302


UNIT V

o Drag and drop the fields you want to display on the report.
o Optionally, you can apply grouping, sorting, filtering, and
formatting rules to the report.
o Save the report (.rpt file).
3. Fetch Data Using [Link]
You will fetch data from your database using [Link]. In this example, we'll use
a SqlDataAdapter to fetch data and bind it to a Crystal Report.
Here’s an example of how to fetch data from a SQL Server database and bind it
to a Crystal Report in the code-behind.
using System;
using [Link];
using [Link];
using [Link];

public partial class ReportViewerPage : [Link]


{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GenerateCrystalReport();
}
}

private void GenerateCrystalReport()


{
// Step 1: Fetch data from the database using [Link]
string connectionString = "your_connection_string_here";
string query = "SELECT SalesID, ProductName, Quantity, TotalAmount
FROM Sales";

using (SqlConnection conn = new SqlConnection(connectionString))


{
SqlDataAdapter adapter = new SqlDataAdapter(query, conn);
DataSet dataSet = new DataSet();
[Link](dataSet, "SalesData");

.NET PROGRAMMING Page 303


UNIT V

// Step 2: Load the Crystal Report


ReportDocument reportDocument = new ReportDocument();
[Link]([Link]("~/Reports/[Link]"));

// Step 3: Set the data source for the report


[Link]([Link]["SalesData"]);

// Step 4: Set the report source to the CrystalReportViewer


[Link] = reportDocument;
[Link]();
}
}
}
Explanation of the Code:
 [Link] Data Fetching: We are using a SqlDataAdapter to execute a
query against the database, fetching data into a DataSet object.
 Crystal Report Binding: A ReportDocument object is used to load the
.rpt file and set the data source to the DataSet.
 Display in CrystalReportViewer: The CrystalReportViewer control is
used to display the report in the web page.
4. Display the Report Using CrystalReportViewer
To display the Crystal Report in your [Link] page, you need to use the
CrystalReportViewer control.
1. Add CrystalReportViewer Control to Your ASPX Page:
o In your ASPX page, add the CrystalReportViewer control, which
will display the report.
o Register the Crystal Decisions assembly if it's not already
registered.
Example of the ASPX page ([Link]):
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="[Link]"
Inherits="[Link]" %>
<%@ Register Assembly="[Link], Version=13.0.2000.0,
Culture=neutral, PublicKeyToken=69f491cfae1e2c87"
Namespace="[Link]" TagPrefix="CR" %>

.NET PROGRAMMING Page 304


UNIT V

<html>
<body>
<form id="form1" runat="server">
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server"
Width="100%" Height="600px"
EnableDatabaseLogonPrompt="False" />
</form>
</body>
</html>
 CrystalReportViewer: This control displays the report. You can
configure it to allow features like printing, exporting, and zooming.
 EnableDatabaseLogonPrompt: Set this to False to disable the login
prompt when connecting to the database.
5. Passing Parameters to Crystal Reports
If your Crystal Report has parameters (e.g., date range or customer ID), you can
pass them dynamically from the [Link] page.
Example of passing parameters to the Crystal Report:
using [Link];
using [Link];

public partial class ReportViewerPage : [Link]


{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GenerateCrystalReport();
}
}

private void GenerateCrystalReport()


{
// Fetch data from the database (same as before)

string connectionString = "your_connection_string_here";


string query = "SELECT SalesID, ProductName, Quantity, TotalAmount
FROM Sales";

.NET PROGRAMMING Page 305


UNIT V

SqlDataAdapter adapter = new SqlDataAdapter(query, new


SqlConnection(connectionString));
DataSet dataSet = new DataSet();
[Link](dataSet, "SalesData");

// Load Crystal Report


ReportDocument reportDocument = new ReportDocument();
[Link]([Link]("~/Reports/[Link]"));

// Pass parameters to the report


ParameterFieldDefinitions parameterFields =
[Link];
ParameterFieldDefinition parameterField = parameterFields["StartDate"];
ParameterValues parameterValues = new ParameterValues();
ParameterDiscreteValue discreteValue = new ParameterDiscreteValue();
[Link] = [Link](-7); // Example parameter
value
[Link](discreteValue);
[Link](parameterValues);

// Set the data source for the report


[Link]([Link]["SalesData"]);

// Display the report in CrystalReportViewer


[Link] =
reportDocument;
[Link]();
}
}
In this example, a parameter StartDate is passed dynamically to the Crystal
Report.
6. Exporting and Printing Reports
The CrystalReportViewer control provides built-in options for exporting and
printing reports. By default, it supports exporting to various formats, including
PDF, Excel, Word, and HTML.
To enable the export and print buttons, set the following properties in the
CrystalReportViewer:
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server"
Width="100%" Height="600px"
.NET PROGRAMMING Page 306
UNIT V

ShowExportButton="True" ShowPrintButton="True" />


Conclusion
To generate Crystal Reports in an [Link] application:
1. Install Crystal Reports for Visual Studio.
2. Create a Crystal Report (.rpt) in Visual Studio, using the Database
Expert to connect to your data.
3. Use [Link] to fetch data from a database and pass it to the Crystal
Report.
4. Display the report using the CrystalReportViewer control in your
ASPX page.
5. Pass parameters to the report dynamically (if required).
6. Enable exporting and printing capabilities in the Crystal Report Viewer.
By following these steps, you can integrate Crystal Reports into your [Link]
application to generate dynamic reports with rich features like filtering,
grouping, and exporting.

.NET PROGRAMMING Page 307

You might also like