100% found this document useful (8 votes)
2K views127 pages

ASP.NET Programming Course Overview

The document outlines the curriculum for a BCA course on ASP.NET Programming, detailing the course structure, units of study, and key topics such as .NET Framework, ASP.NET, ADO.NET, and web application security. It also includes a list of textbooks and reference materials for further reading. Additionally, it provides an overview of the .NET Framework, its components, advantages, and disadvantages, as well as a detailed explanation of the Common Language Runtime (CLR) and the Framework Class Library (FCL).

Uploaded by

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

ASP.NET Programming Course Overview

The document outlines the curriculum for a BCA course on ASP.NET Programming, detailing the course structure, units of study, and key topics such as .NET Framework, ASP.NET, ADO.NET, and web application security. It also includes a list of textbooks and reference materials for further reading. Additionally, it provides an overview of the .NET Framework, its components, advantages, and disadvantages, as well as a detailed explanation of the Common Language Runtime (CLR) and the Framework Class Library (FCL).

Uploaded by

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

By

Mr. M. Pandiaraj, MCA., [Link]., NET.,


Assistant Professor,
PG & Research Department of Computer Science & Applications,
Sri Vidya Mandir Arts & Science College (Autonomous), Katteri

Name : __________________________

Class : __________________________
Programme: BCA

Core – VI Course Code: 23UCA5C06 Course Title: ASP. Net Programming

Semester Hours/Week Total Hours Credits Total Marks


V 5 75 4 100

UNIT – I
Overview of .NET framework: Common Language Runtime (CLR), Framework Class
Library - C# Fundamentals: Primitive types and Variables – Operators - Conditional
statements – Looping statements – Creating and using Objects–Arrays – String
operations.
UNIT – II
Introduction to [Link] – IDE – Languages supported Components – Working with
Web Forms – Web form standard controls: Properties and its events – HTML controls
– List Controls: Properties and its events.
UNIT – III
Rich Controls: Properties and its events – validation controls: Properties and its
events– File Stream classes -File Modes – File Share – Reading and Writing to files –
Creating, Moving, Copying and Deleting files –File uploading.
NIT – IV
[Link] Overview – Database Connections – Commands – Data Reader – Data
Adapter – Data Sets – Data Controls and its Properties – DataBinding.
UNIT – V
Grid View control: Deleting, editing, Sorting and Paging. XML classes – Web form to
manipulate XML files – Website Security – Authentication – Authorization – Creating
a Web application.
Text Books
1. Svetlin Nakov, Veselin Kolev & Co, Fundamentals of Computer Programming
with C#, Faber publication, 2019.
2. Mathew, MacDonald, The Complete Reference [Link], Tata McGraw-Hill,
2015.
Reference Book
1. Herbert Schildt, The Complete Reference C#.NET, Tata McGraw-Hill, 2017.
2. Kogent Learning Solutions, C# 2012 Programming Covers .NET4.5 BlackBook,
Dreamtechpres, 2013.
3. AnneBoehm, JoelMurach, Murach‘s C# 2015, Mike Murach & Associates Inc.
2016.
4. Denielle Otey, Michael Otey, [Link]: The Complete reference, McGrawHill,
2008.
5. Matthew MacDonald, Beginning ASP.NET4 in C# 2010, APRESS, 2010.
[Link] Programming
UNIT- 1
1.1 .NET FRAMEWORK
It is a virtual machine that provide a common platform to run an application
that was built using the different language such as C#, [Link], Visual Basic, etc.
It is also used to create a form based, console-based, mobile and web-based
application or services that are available in Microsoft environment.
The .NET framework is a pure object oriented, that similar to the Java
language. But it is not a platform independent as the Java. So, its application runs
only to the windows platform.
The main objective of the framework is to develop an application that can run
on the windows platform. The current version of the .Net framework is 4.8. The
.NET Framework is not only a language, but it is also a software and language
neutral platform.

Components of .NET Framework:


There are following components of .NET Framework:
1. CLR (Common Language Runtime)
2. CTS (Common Type System)
3. BCL (Base Class Library)
4. CLS (Common Language Specification)
5. FCL (Framework Class Library)
6. .NET Assemblies
7. XML Web Services
8. Window Services

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 1


[Link] Programming

Characteristics of .NET Framework:


• CLR (Common Language Runtime)
• Namespace - Predefined class and function
• Metadata and Assemblies
• Application domains
• It helps to configure and deploy the .net application
• It provides form and web-based services
• NET and [Link] AJAX
• LINQ
• Security and Portability
• Interoperability
• It provides multiple environments for developing an application
.NET Programming Languages:
The .NET ecosystem supports various programming languages developed by
Microsoft and third-party contributors. Some of the most widely used languages are:
• C# .NET
• [Link]
• F# .NET
• C++ .NET
• J# .NET

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 2


[Link] Programming
• IronRuby, IronPython
• [Link], C Omega, ASML, and more.
Advantages of .NET Framework:
• Multi-Language Support: The .NET Framework supports several
programming languages, including C#, F#, and Visual Basic, allowing
developers to choose the language that best suits their needs while still
benefiting from the same set of libraries and tools.
• Cross-Platform Compatibility (via .NET Core and Mono): Although initially
designed for Windows, the .NET Framework can now run on various
operating systems through .NET Core and Mono, making it a versatile
solution for cross-platform development.
• Large and Active Developer Community: The .NET Framework benefits
from a broad developer base, creating a rich ecosystem of libraries, tools, and
resources. This helps developers solve problems more easily and share
solutions across the community.
• Security Features: The framework includes various security features such as
code access security and digital signatures, helping protect applications from
malicious threats and vulnerabilities.
• Productivity: The set of pre-built libraries and tools offered by .NET
accelerates development time, enabling developers to focus on business logic
rather than reinventing common functionalities.
Disadvantages of .NET Framework:
• Windows Dependency: Though it supports on cross-platform, the .NET
Framework was originally built for Windows, and certain features may still
be optimized primarily for the Windows operating system.
• Large Footprint: The .NET Framework installation is relatively large, which
can be a concern for applications running on devices with limited storage or
bandwidth.
• Licensing Costs: Some versions of the .NET Framework may require a paid
license, adding costs to development and deployment.
• Performance Considerations: Although .NET provides excellent performance
for most applications, it may not be the ideal choice for high-performance

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 3


[Link] Programming
scenarios where low-level hardware interaction or complex algorithms are
required.
• Learning Curve: Although .NET is designed to be easy to use, developers
new to the platform may face a learning curve specially with the object-
oriented programming.
1.2 .NET COMMON LANGUAGE RUNTIME (CLR):
.NET CLR is a run-time environment that manages and executes the code
written in any .NET programming language. It converts code into native code which
further can be executed by the CPU.
.NET CLR Functions:
❖ It converts the program into native code.
❖ Handles Exceptions
❖ Provides type-safety
❖ Memory management
❖ Provides security
❖ Improved performance
❖ Language independent
❖ Platform independent
❖ Garbage collection
❖ Provides language features such as inheritance, interfaces, and
overloading for object-oriented programming.
.NET CLR Versions:
.NET version CLR version Released on Features
1.0 1.0 2002 [Link] and [Link], IPv6, databases
and ODBC
1.1 1.1 2003 [Link] and [Link], IPv6, databases
and ODBC
2.0 2.0 Jan 2006 [Link] like asynchronous database
operations,
XML data types, user-defined types
(UDT), and snapshot isolation.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 4


[Link] Programming
3.0 2.0 Nov 2006 ❖ GUI capabilities
❖ Lambda Expressions
3.5 2.0 2007 ❖ LINQ
❖ NET Ajax-enabled Websites
❖ Latency Mode in Garbage
Collection
❖ TimeZoneInfo
❖ Cryptography Enhancements
❖ Socket Performance Enhancements
❖ Peer-to-peer networking
❖ Web Service Interoperability
4 4 2010 ❖ Parallel computing for distributed
or multi-core systems.
❖ Dynamic Language Runtime
❖ Expanded Base Class
4.5 4 2012 ❖ Programming languages support
such as C#, F# or just create an
windows Applications.
❖ WPF, WCF, WWF
❖ Native support for Zip
compression
4.5.1 4 2013 ❖ Edit & Continue controls (64-bit)
❖ Possibility to handle return values
❖ Improved performance &
reliability
❖ Compact large object heaps
❖ Trace & sample activities
❖ Support for Automatic binding
redirection
❖ Expanded support for Windows
store application development

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 5


[Link] Programming
4.5.2 4 2014 ❖ High DPI Scenarios
❖ Expanded resizing Windows
Forms controls
4.6 4 July 2015 ❖ RyuJIT, 64-bit compiler
❖ Event-tracking enhancement
❖ HTTP/2 support
4.6.1 4 Nov 2015 ❖ Spell checking
❖ Image generator
❖ Indexed members etc.
4.6.2 4 2016 ❖ Exception Filter
❖ Signed Xml support for SHA-2
hashing
❖ Support for persisted-key
symmetric encryption
4.7 4 May 2017 ❖ Object Cache Extensibility
❖ TLS (Transport Layer Security)
❖ Enhanced Cryptography
❖ More features for touch & style in
WPF
4.7.1 4 Oct 2017 ❖ TLS
❖ Enhanced Cryptography
❖ High DPI support
4.7.2 4 2018 ❖ New overloads of [Link] and
[Link]
❖ Ephemeral keys Support
❖ Support for same-site cookies
❖ HttpClientHandler properties
implementation
4.8 4 2019 ❖ JIT improvements, Updated ZLib
❖ Reducing FIPS Impact on
Cryptography

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 6


[Link] Programming
❖ Antimalware Scanning for All
Assemblies
❖ Reducing FIPS Impact on
Cryptography
.NET CLR Structure:

Base Class Library Support:


It is a class library that provides support of classes to the .NET application.
Thread Support:
It manages the parallel execution of the multi-threaded application.
COM Marshaler:
It provides communication between the COM objects and the application.
Type Checker:
It checks types used in the application and verifies that they match to the
standards provided by the CLR.
Code Manager:
It manages code at execution run-time.
Garbage Collector:
It releases the unused memory and allocates it to a new application.
Exception Handler:
It handles the exception at runtime to avoid application failure.
ClassLoader:
It is used to load all classes at run time.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 7


[Link] Programming
1.3 FRAMEWORK CLASS LIBRARY (FCL):
The Framework Class Library or FCL provides the system functionality in
the .NET Framework as it has various classes, data types, interfaces, etc. to perform
multiple functions and build different types of applications such as desktop
applications, web applications, mobile applications, etc.
The Framework Class Library is integrated with the Common Language
Runtime (CLR) of the .NET framework and is used by all the .NET languages such
as C#, F#, Visual Basic .NET, etc.
Key Components of FCL:
• Object type
• Implementation of data structure
• Base data types
• Garbage collection
• Security and database connectivity
• Creating common platform for window and web-based application
Categories in the FCL:

The functionality of the Framework Class Library can be broadly divided


into three categories i.e.
• Utility features written in .NET
• Wrappers around the OS functionality and
• Frameworks

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 8


[Link] Programming
Utility Features:
The utility features in the FCL includes various collection classes such as list,
stack, queue, dictionary, etc. and also classes for more varied manipulations such as
Regex class for regular expressions.
Wrappers Around OS functionality:
Some of the features in the FCL are wrappers around the underlying
Windows OS functionality. These include the classes for using the file system, the
classes to handle the network features, the classes to handle I/O for console
applications, etc.
Frameworks:
There are various frameworks available in the FCL to develop certain
applications. For example, [Link] is used to develop web applications, Windows
Presentation Foundation (WPF) is used to render user interfaces in Windows
applications, and so on.
Namespaces in the Framework Class Library:
Namespaces in the Framework Class Library are a group of related classes
and interfaces that can be used by all the .NET framework languages. Some of the
namespaces in the FCL along with their description is given as follows:
Namespace Description
Accessibility The Accessibility namespace is a part of the managed
wrapper for the COM accessibility interface.
[Link] The [Link] namespace provides support
for Windows Workflow Foundation applications.
[Link] The [Link] namespace has support for
compilation and code generation for the C# source
code.
[Link] The [Link] namespace has support for
compilation and code generation for the JScript source
code.
[Link] The [Link] namespace has support for
compilation and code generation for the VisualBasic

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 9


[Link] Programming
source code.
System The System namespace has base classes for definition
of interfaces, data types, events, event handlers,
attributes, processing exceptions etc.
[Link] The [Link] namespace handles the creation
and working with activities in the Window Workflow
Foundation using various classes.
[Link] The [Link] namespace has multiple
standard, specialized, and generic collection objects
that are defined using various types.
[Link] The [Link] namespace handles
configuration data using various types. This may
include data in machine or application configuration
files.
[Link] The [Link] namespace accesses and manages
data from various sources using different classes.
[Link] The [Link] namespace handles GDI+ basic
graphics functionality. Various child namespaces also
handle vector graphics functionality, advanced
imaging functionality, etc.
[Link] The [Link] namespace handles
language, country, calendars used, format patterns for
dates, etc. using various classes.
[Link] The [Link] namespaces support IO like data
read/write into streams, data compression,
communicate using named pipes etc. using various
types.
[Link] The [Link] namespace supports Language-
Integrated Query (LINQ) using various types.
[Link] The [Link] namespace handles sound files and
accessing the sounds provided by the system using

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 10


[Link] Programming
various classes.
[Link] The [Link] namespace provides an interface for
network protocols, cache policies for web resources,
composing and sending e-mail etc. using various
classes.
[Link] The [Link] namespace gives a managed
view of loaded methods, types, fields, etc. It can also
create and invoke types dynamically.
[Link] The [Link] namespace has the .NET security
system and permissions. Child namespaces provide
authentication, cryptographic services etc.
[Link] The [Link] namespace allows
multithreaded programming using various types.
XamlGeneratedNamespace The XamlGeneratedNamespace has compiler-
generated types that are not used directly from the
code.

1.4 .NET REVOLUTION (.NET FRAMEWORK VERSIONS):


The .Net Framework, a programming model developed by Microsoft
supports building as well as running applications for Windows, Windows Phone,
Windows servers, XML Web services, and Microsoft Azure.
The framework includes a large class library called FCL (Framework Class
Library) as well as CLR (Common Language Interoperability) across various
programming languages like [Link], C++, F#, and C#.
The .Net framework solutions provide the Base Class Library that covers the
broad range of programming needs in a large number of areas using data access,
Interface, Cryptography, data connectivity, numerous algorithms, network
communications, and web application development.
.Net framework is one of the most popular Frameworks used as software
development platform with various .Net Framework versions.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 11


[Link] Programming
Different .Net Framework Versions and Features:
.NET version CLR version Released on Features
1.0 1.0 2002 [Link] and [Link], IPv6, databases
and ODBC
1.1 1.1 2003 [Link] and [Link], IPv6, databases
and ODBC
2.0 2.0 Jan 2006 [Link] like asynchronous database
operations,
XML data types, user-defined types
(UDT), and snapshot isolation.
3.0 2.0 Nov 2006 ❖ GUI capabilities
❖ Lambda Expressions
3.5 2.0 2007 ❖ LINQ
❖ NET Ajax-enabled Websites
❖ Latency Mode in Garbage
Collection
❖ TimeZoneInfo
❖ Cryptography Enhancements
❖ Socket Performance Enhancements
❖ Peer-to-peer networking
❖ Web Service Interoperability
4 4 2010 ❖ Parallel computing for distributed
or multi-core systems.
❖ Dynamic Language Runtime
❖ Expanded Base Class
4.5 4 2012 ❖ Programming languages support
such as C#, F# or just create an
windows Applications.
❖ WPF, WCF, WWF
❖ Native support for Zip
compression

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 12


[Link] Programming
4.5.1 4 2013 ❖ Edit & Continue controls (64-bit)
❖ Possibility to handle return values
❖ Improved performance &
reliability
❖ Compact large object heaps
❖ Trace & sample activities
❖ Support for Automatic binding
redirection
❖ Expanded support for Windows
store application development
4.5.2 4 2014 ❖ High DPI Scenarios
❖ Expanded resizing Windows
Forms controls
4.6 4 July 2015 ❖ RyuJIT, 64 bit compiler
❖ Event-tracking enhancement
❖ HTTP/2 support
4.6.1 4 Nov 2015 ❖ Spell checking
❖ Image generator
❖ Indexed members etc.
4.6.2 4 2016 ❖ Exception Filter
❖ Signed Xml support for SHA-2
hashing
❖ Support for persisted-key
symmetric encryption
4.7 4 May 2017 ❖ Object Cache Extensibility
❖ TLS (Transport Layer Security)
❖ Enhanced Cryptography
❖ More features for touch & style in
WPF
4.7.1 4 Oct 2017 ❖ TLS
❖ Enhanced Cryptography

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 13


[Link] Programming
❖ High DPI support
4.7.2 4 2018 ❖ New overloads of [Link] and
[Link]
❖ Ephemeral keys Support
❖ Support for same-site cookies
❖ HttpClientHandler properties
implementation
4.8 4 2019 ❖ JIT improvements, Updated ZLib
❖ Reducing FIPS Impact on
Cryptography
❖ Antimalware Scanning for All
Assemblies
❖ Reducing FIPS Impact on
Cryptography

1.5 .NET FRAMEWORK ARCHITECTURE:


.Net Framework Architecture is a programming model for the .Net platform
that provides an execution environment and integration with various programming
languages for simple development and deployment of various Windows and
desktop applications. It consists of class libraries and reusable components.

.NET Components:
The architecture of .Net framework is based on the following key
components;
i) Common Language Runtime
ii) Class Library
iii) Languages

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 14


[Link] Programming
Common Language Runtime:
The “Common Language Infrastructure” or CLI is a platform in .Net
architecture on which the .Net programs are executed.
The CLI has the following key features:
Exception Handling - Exceptions are errors which occur when the application is
executed.
Examples of exceptions are:
• If an application tries to open a file on the local machine, but the file is not
present.
• If the application tries to fetch some records from a database, but the
connection to the database is not valid.
Garbage Collection – Garbage collection is the process of removing unwanted
resources when they are no longer required.
Examples of garbage collection are
• A File handles which is no longer required. If the application has finished all
operations on a file, then the file handle may no longer be required.
• The database connection is no longer required. If the application has finished
all operations on a database, then the database connection may no longer be
required.
Working with Various programming languages –
A developer can develop an application in a variety of .Net programming
languages.
1. Language – The first level is the programming language itself, the most
common ones are [Link] and C#.
2. Compiler – There is a compiler which will be separate for each programming
language. So underlying the [Link] language, there will be a separate [Link]
compiler. Similarly, for C#, you will have another compiler.
3. Common Language Interpreter – This is the final layer in .Net which would
be used to run a .net program developed in any programming language. So
the subsequent compiler will send the program to the CLI layer to run the
.Net application.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 15


[Link] Programming

Class Library:
The .NET Framework includes a set of standard class libraries. A class library
is a collection of methods and functions that can be used for the core purpose.
For example, there is a class library with methods to handle all file-level
operations. So there is a method which can be used to read the text from a file.
Similarly, there is a method to write text to a file.
Most of the methods are split into either the System.* or Microsoft.*
namespaces. (The asterisk * just means a reference to all of the methods that fall
under the System or Microsoft namespace)
A namespace is a logical separation of methods. We will learn these
namespaces more in detail in the subsequent chapters.
Languages:
The types of applications that can be built in the .Net framework is classified
broadly into the following categories.
WinForms – This is used for developing Forms-based applications, which would run
on an end user machine. Notepad is an example of a client-based application.
[Link] – This is used for developing web-based applications, which are made to
run on any browser such as Internet Explorer, Chrome or Firefox.
• The Web application would be processed on a server, which would have
Internet Information Services Installed.
• Internet Information Services or IIS is a Microsoft component which is used to
execute an [Link] application.
• The result of the execution is then sent to the client machines, and the output
is shown in the browser.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 16


[Link] Programming
[Link] – This technology is used to develop applications to interact with
Databases such as Oracle or Microsoft SQL Server.
Microsoft always ensures that .Net frameworks are in compliance with all the
supported Windows operating systems.
1.6 C# FUNDAMENTALS:
C# is a modern, general-purpose, object-oriented programming language
developed by Microsoft and approved by European Computer Manufacturers
Association (ECMA) and International Standards Organization (ISO).
C# was developed by Anders Hejlsberg and his team during the development
of .Net Framework.
C# is designed for Common Language Infrastructure (CLI), which consists of
the executable code and runtime environment that allows use of various high-level
languages on different computer platforms and architectures.
The following reasons make C# a widely used professional language −
• It is a modern, general-purpose programming language
• It is object oriented.
• It is component oriented.
• It is easy to learn.
• It is a structured language.
• It produces efficient programs.
• It can be compiled on a variety of computer platforms.
• It is a part of .Net Framework.
Key Characteristics of C#:
C# comes with several key features that make it a powerful and reliable
programming language:
• Object-Oriented: C# follows OOP principles, allowing the use of classes,
inheritance, polymorphism, and encapsulation.
• Type-Safe: C# is a type-safe programming language that ensures secure
coding by preventing unsafe memory operations.
• Cross-Platform: C# is a cross-platform programming language that means C#
works on Windows, Linux, and macOS using .NET Core.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 17


[Link] Programming
• Scalable & Maintainable: C# is well-suited for developing large and complex
applications.
• Rich Library Support: C# come with many built-in libraries for UI, database
handling, and networking.
• High Performance: C# compiles to Intermediate Language (IL) and runs
efficiently on the Common Language Runtime (CLR).
Strong Programming Features of C#:
C# constructs closely follow traditional high-level languages, C and C++ and
being an object-oriented programming language.
It has strong resemblance with Java, it has numerous strong programming
features that make it endearing to a number of programmers worldwide.
Following is the list of few important features of C# −
• Boolean Conditions
• Automatic Garbage Collection
• Standard Library
• Assembly Versioning
• Properties and Events
• Delegates and Events Management
• Easy-to-use Generics
• Indexers
• Conditional Compilation
• Simple Multithreading
• LINQ and Lambda Expressions
• Integration with Windows
Importance of C#:
C# offers a great mix of simplicity, performance, and flexibility, which makes
C# a popular choice for building large and complex applications for the different
industries.
• Easy to Learn: C#'s syntax is similar to C, C++, and Java, which makes it
beginner-friendly.
• Strongly Typed: C# helps prevent errors by enforcing strict type safety.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 18


[Link] Programming
• Versatile: C# is a versatile programming language, which means it can be
used to develop desktop, web, cloud, and gaming applications.
• Large Community Support: There is a large community of strong C#
developers with plenty of resources and documentation; you can take any
support anytime and from anywhere.
• Seamless .NET Integration: C# works smoothly with [Link], Blazor,
Xamarin, and Unity for diverse development needs.
C# vs Other Programming Languages:
The following table compares C#, Java, Python, and C++ based on key
features to help you choose the right language for your needs:
Feature C# Java Python C++
Object-Oriented Yes Yes Yes Yes
Memory Automatic Automatic Automatic Manual
Management (Garbage (Garbage (Garbage
Collection) Collection) Collection)
Performance High Medium Slower Very High
Cross-Platform Yes (.NET Core) Yes Yes Yes
Game Yes (Unity) No No Yes
Development

C# is a great option for building business applications, developing games,


and creating software that works on multiple platforms.
Example:
Open Compiler
using System;
class HelloWorld
{
static void Main()
{
[Link]("Hello, World!");
}
}

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 19


[Link] Programming
Output:
Hello, World!
Uses of C#:
C# is a versatile programming language used across various domains,
making it ideal for,
1. Desktop Applications
2. Web Development
3. Game Development
4. Mobile App Development
5. Cloud & IoT Development
1.7 C# IDENTIFIERS:
In programming languages, identifiers are used for identification purposes.
Or in other words, identifiers are the user-defined name of the program components.
In C#, an identifier can be a class name, method name, variable name, or label.
Rules for Defining Identifiers
There are certain valid rules for defining a valid C# identifier. These rules
should be followed, otherwise, we will get a compile-time error.
Aspect Description
Allowed The only allowed characters for identifiers are all
Characters alphanumeric characters ([A-Z], [a-z], [0-9]), ‘_‘(underscore).
For example, “geek@” is not a valid C# identifier as it contains
‘@’ – special character.
Starting Identifiers should not start with digits ([0-9]).
Character For example, “123geeks” is not valid in the C# identifier.
No Whitespaces Identifiers must not contain whitespace characters.
Keywords Identifiers are not allowed to use as keywords unless they
include @ as a prefix. For example, @as is a valid identifier, but
“as” is not because it is a keyword.
Unicode Support C# identifiers allow Unicode Characters.
Case – C# identifiers are case-sensitive.
Sensitivity

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 20


[Link] Programming
Length C# identifiers cannot contain more than 512 characters.
Restriction
No Double Identifiers do not contain two consecutive underscores in their
Underscores name because such types of identifiers are used for the
implementation.
Example:
• Keywords: using, public, static, void, int.
• Identifiers: Geeks, Main, a, b, c.
1.8 C# DATA TYPES:
C# data types define the type of data a variable can store, such as integers,
floating-point numbers, characters, or Boolean values.
The data types are essential to declare specific variables to store the related
value, memory optimization, performance improvements, and code readability.
In C#, all variables must be declared with the data types before their use, as it
is a strongly typed language.
Syntax for Declaring a Variable with Data Type
<data_type> <variable_name> = <value>;
Example:
Open Compiler
using System;
class Program
{
static void Main()
{
string studentName = "Sudhir Sharma";
int studentAge = 20;
double marksPercentage = 85.5;
char grade = 'A';
bool isEnrolled = true;
[Link]("Student Name: " + studentName);
[Link]("Age: " + studentAge);
[Link]("Marks Percentage: " + marksPercentage + "%");

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 21


[Link] Programming
[Link]("Grade: " + grade);
[Link]("Enrolled: " + isEnrolled);
} }
Output:
Student Name: Sudhir Sharma
Age: 20
Marks Percentage: 85.5%
Grade: A
Enrolled: True
Types of Data in C#:
The variables in C#, are categorized into the following types −
• Value types
• Reference types
• Pointer types
1. Value Types in C#
Value type variables can be assigned a value directly. They are derived from
the class [Link].
The value types directly contain data. Some examples are int, char, and float,
which stores numbers, alphabets, and floating-point numbers, respectively. When
we declare an int type, the system allocates memory to store the value.
Value types store actual values and include:
• Integral types (int, byte, long, etc.)
• Floating-point types (float, double, decimal)
• Character type (char)
• Boolean type (bool)
• Enumerations (enum)
• Structs (struct)
Integral Data Types
Data Type Size Range
byte 1 byte 0 to 255
sbyte 1 byte -128 to 127

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 22


[Link] Programming
short 2 bytes -32,768 to 32,767
ushort 2 bytes 0 to 65,535
int 4 bytes -2,147,483,648 to 2,147,483,647
uint 4 bytes 0 to 4,294,967,295
long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ulong 8 bytes 0 to 18,446,744,073,709,551,615
Floating-Point Data Types
Data Type Size Precision
float 4 bytes 6-7 decimal places
double 8 bytes 15-16 decimal places
decimal 16 bytes 28-29 decimal places
Use float and double for general calculations.
Use decimal for precise financial calculations.
Character and Boolean Data Types
Data Type Size Description
char 2 bytes Stores a single character
bool 1 byte Stores true or false
Enumerations (enum)
An enum is a special data type used for defining named constant values.
Example
Open Compiler
using System;
class Program
{
enum JobLevel { Intern, Junior, Mid, Senior, Manager }
static void Main()
{
JobLevel currentLevel = [Link];
[Link]("Current Job Level: " + currentLevel);
} }
Output:
Current Job Level: Mid

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 23


[Link] Programming
Structs
A struct is a value type used to encapsulate related data.
Example
Open Compiler
using System;
struct Employee
{
public int ID;
public string Name;
public double Salary;
}
class Program
{
static void Main()
{
Employee emp;
[Link] = 101;
[Link] = "Zoya";
[Link] = 60000.50;
[Link]("Employee ID: " + [Link]);
[Link]("Employee Name: " + [Link]);
[Link]("Employee Salary: $" + [Link]);
} }
Output:
Employee ID: 101
Employee Name: Zoya
Employee Salary: $60000.5
2. Reference Types in C#
The reference types do not contain the actual data stored in a variable, but
they contain a reference to the variables. In other words, they refer to a memory
location. Using multiple variables, the reference types can refer to a memory
location.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 24


[Link] Programming
If the data in the memory location is changed by one of the variables, the
other variable automatically reflects this change in value.
Example of built-in reference types are: object, dynamic, string, and array.
Object Type
The Object Type is the ultimate base class for all data types in C# Common
Type System (CTS). Object is an alias for [Link] class.
The object types can be assigned values of any other types, value types,
reference types, predefined or user-defined types. However, before assigning values,
it needs type conversion.
When a value type is converted to object type, it is called boxing and on the
other hand, when an object type is converted to a value type, it is called unboxing.
object obj;
obj = 100; // this is boxing
Dynamic Type
We can store any type of value in the dynamic data type variable. Type
checking for these types of variables takes place at run-time.
Syntax for declaring a dynamic type is −
dynamic <variable_name> = value;
String Type
The String Type allows you to assign any string values to a variable. The
string type is an alias for the [Link] class. It is derived from object type. The
value for a string type can be assigned using string literals in two forms: quoted and
@quoted.
The user-defined reference types are:
class,
interface, or delegate.
Array Type
Arrays store multiple values of the same type in a single variable.
Example
Open Compiler
using System;
class Program

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 25


[Link] Programming
{
static void Main()
{
string[] students = { "Zoya", "Yashna", "Olivia", "Naomi" };
[Link]("Student List:");
foreach (string student in students)
{
[Link](student);
}
} }
Output:
Student List:
Zoya
Yashna
Olivia
Naomi
3. Pointer Type in C#
Pointer type variables store the memory address of another type. Pointers in
C# have the same capabilities as the pointers in C or C++.
Syntax for declaring a pointer type is −
type* identifier;
Type Conversion in C#
Type conversion allows us to convert data from one type to another. In C#,
there are two types of type conversions: implicit and explicit.
1. Implicit Conversion (Safe)
Implicit conversion occurs automatically when there is no risk of data loss. C#
allows implicit conversion for compatible types.
Example
Open Compiler
using System;
class Program
{

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 26


[Link] Programming
static void Main()
{
int studentAge = 18;
double preciseAge = studentAge; // Implicit conversion
[Link]("Student Age (Integer): " + studentAge);
[Link]("Converted to Double: " + preciseAge);
} }
Output:
Student Age (Integer): 18
Converted to Double: 18
2. Explicit Conversion (Casting)
Explicit conversion is required when converting between incompatible types.
This is done using casting.
Example
Open Compiler
using System;
class Program
{
static void Main()
{
double salary = 50000.75;
int roundedSalary = (int)salary; // Explicit casting
[Link]("Original Salary (Double): " + salary);
[Link]("Rounded Salary (Integer): " + roundedSalary);
} }
Output:
Original Salary (Double): 50000.75
Rounded Salary (Integer): 50000
1.9 C# VARIABLES:
C# variables are fundamental building blocks in any C# program and are
used to store data. We can assign, access, and manipulate the data with the help of
variables.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 27


[Link] Programming
C# variables are the containers to store data and help to access and
manipulate the data during the program execution.
A variable must be declared by using a specific data type which can store that
type of value.
Importance of Variables in C#:
• Data Storage: Variables allow storing data like numbers, text, and more.
• Data Manipulation: It can manipulate the data within variables to perform
calculations, transformations, or display results.
• Program Flow Control: Variables help manage and control how data flows
through the program.
Declaring Variables in C#:
In C#, we declare a variable by specifying its data type and a variable name.
Syntax
Here's the basic syntax to declare a variable:
<data_type> <variable_name>;
Example
int age;
string name;
C# Variable Initialization:
After declaring a variable, we can initialize it with a value.
Example
int age = 21;
string name = "Zoya";
bool isActive = true;
We can also assign a value to a variable after declaration:
Example
int age;
age = 25;
Types of Variables in C#
C# supports several types of variables, categorized as follows:
1. Primitive Variables
2. Reference Variables

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 28


[Link] Programming
3. Constants
4. Nullable Variables
1. Primitive Variables
The primitive variables are basic data types like int, float, char, and bool.
Example
int number = 10;
double pi = 3.14;
2. Reference Variables
The reference variables hold references to objects in memory, like arrays and
classes.
Example
string name = "Alice";
int[] numbers = new int[] { 1, 2, 3 };
3. Constants
The constants are variables whose value cannot be changed once assigned.
Example
const double PI = 3.14159;
4. Nullable Variables
The nullable variables can hold a null value.
Example
int? age = null;
1.10 C# OPERATORS:
An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations. C# has rich set of built-in operators and
provides the following type of operators −
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 29


[Link] Programming
Arithmetic Operators:
C# arithmetic operators perform mathematical operations such as addition,
subtraction, multiplication, division, and modulus between numeric data types.
These operators are binary operators, which need two operands to perform the
operations.
Following table shows all the arithmetic operators supported by C#. Assume
variable A holds 10 and variable B holds 20 then −
Operator Description Example
+ Adds two operands A + B = 30
- Subtracts second operand from the first A - B = -10
* Multiplies both operands A * B = 200
/ Divides numerator by de-numerator B/A=2
% Modulus Operator and remainder of after an integer B % A = 0
division
++ Increment operator increases integer value by one A++ = 11
-- Decrement operator decreases integer value by one A-- = 9
Example
Open Compiler
using System;
class Program
{
static void Main()
{
int x = 10, y = 4;
[Link]("Addition: " + (x + y));
[Link]("Multiplication: " + (x * y));
[Link]("Modulo: " + (x % y));
} }
Output:
Addition: 14
Multiplication: 40
Modulo: 2

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 30


[Link] Programming
Relational Operators:
C# relational operators compare two operands and return either true or false.
These operators are useful for decision-making.
Following table shows all the relational operators supported by C#. Assume
variable A holds 10 and variable B holds 20, then −
Operator Description Example
== Checks if the values of two operands are equal or not, if (A == B) is
yes then condition becomes true. not true.
!= Checks if the values of two operands are equal or not, if (A != B) is
values are not equal then condition becomes true. true.
> Checks if the value of left operand is greater than the (A > B) is
value of right operand, if yes then condition becomes true. not true.
< Checks if the value of left operand is less than the value of (A < B) is
right operand, if yes then condition becomes true. true.
>= Checks if the value of left operand is greater than or equal (A >= B) is
to the value of right operand, if yes then condition not true.
becomes true.
<= Checks if the value of left operand is less than or equal to (A <= B) is
the value of right operand, if yes then condition becomes true.
true.
Example
Open Compiler
using System;
class Program
{
static void Main()
{
int a = 20, b = 15;
[Link]("Is a > b? " + (a > b));
[Link]("Is a == b? " + (a == b));
}
}

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 31


[Link] Programming
Output:
Is a > b? True
Is a == b? False
Logical Operators:
C# logical operators combine Boolean expressions. These operators are useful
when the multiple conditions and want to combine and check them. The result of
these operators is either true or false; i.e., these operators return only Boolean values.
Following table shows all the logical operators supported by C#. Assume
variable A holds Boolean value true and variable B holds Boolean value false, then −
Operator Description Example
&& Called Logical AND operator. If both the operands (A && B) is
are non-zero then condition becomes true. false.
|| Called Logical OR Operator. If any of the two (A || B) is
operands is non zero then condition becomes true. true.
! Called Logical NOT Operator. Use to reverses the !(A && B) is
logical state of its operand. If a condition is true then true.
Logical NOT operator will make false.
Example
Open Compiler
using System;
class Program
{
static void Main()
{
bool x = true, y = false;
[Link]("AND (&&) : " + (x && y));
[Link]("OR (||) : " + (x || y));
[Link]("NOT (!) : " + (!x));
}
}
Output:
AND (&&) : False

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 32


[Link] Programming
OR (||) : True
NOT (!) : False
Bitwise Operators:
Bitwise operator works on bits and performs bit by bit operation. The truth
tables for &, |, and ^ are as follows −
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; then in the binary format they are as follows −
A = 0011 1100
B = 0000 1101
-------------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C# are listed in the following table.
Assume variable A holds 60 and variable B holds 13, then −
Operator Description Example
& Binary AND Operator copies a bit to the result (A & B) = 12, which is
if it exists in both operands. 0000 1100
| Binary OR Operator copies a bit if it exists in (A | B) = 61, which is
either operand. 0011 1101
^ Binary XOR Operator copies the bit if it is set (A ^ B) = 49, which is
in one operand but not both. 0011 0001
~ Binary Ones Complement Operator is unary (~A ) = -61, which is
and has the effect of 'flipping' bits. 1100 0011 in 2's
complement due to a
signed binary number.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 33


[Link] Programming
<< Binary Left Shift Operator. The left operands A << 2 = 240, which is
value is moved left by the number of bits 1111 0000
specified by the right operand.
>> Binary Right Shift Operator. The left operands A >> 2 = 15, which is
value is moved right by the number of bits 0000 1111
specified by the right operand.
Example
Open Compiler
using System;
class Program
{
static void Main()
{
int a = 5, b = 3;
[Link]("Bitwise AND: " + (a & b));
[Link]("Bitwise OR: " + (a | b));
}
}
Output:
Bitwise AND: 1
Bitwise OR: 7
Assignment Operators:
C# assignment operators assign values to variables and also perform
arithmetic operations in some of the cases.
There are following assignment operators supported by C# −
Operator Description Example
= Simple assignment operator, Assigns values C = A + B assigns
from right side operands to left side operand value of A + B into C
+= Add AND assignment operator, It adds right C += A is equivalent to
operand to the left operand and assign the C = C + A
result to left operand

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 34


[Link] Programming
-= Subtract AND assignment operator, It subtracts C -= A is equivalent to
right operand from the left operand and assign C = C - A
the result to left operand
*= Multiply AND assignment operator, It C *= A is equivalent to
multiplies right operand with the left operand C = C * A
and assign the result to left operand
/= Divide AND assignment operator, It divides left C /= A is equivalent to
operand with the right operand and assign the C = C / A
result to left operand
%= Modulus AND assignment operator, It takes C %= A is equivalent
modulus using two operands and assign the to C = C % A
result to left operand
<<= Left shift AND assignment operator C <<= 2 is same as C =
C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C =
C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C =
C&2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C =
C^2
|= bitwise inclusive OR and assignment operator C |= 2 is same as C =
C|2
Example
Open Compiler
using System;
class Program
{
static void Main()
{
int num = 10;
num += 5; // Equivalent to num = num + 5
[Link](num);

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 35


[Link] Programming
}}
Output:
15
Ternary Operator:
C# ternary operator requires three operands and performs a conditional
check; it is a shortcut for if-else statements.
Example
Open Compiler
using System;
class Program
{
static void Main()
{
int age = 18;
string result = (age >= 18) ? "Eligible to vote" : "Not eligible";
[Link](result);
}}
Output:
Eligible to vote
Miscellaneous Operators:
C# miscellaneous operators are special operators that don't come under
arithmetic, logical, relational, or bitwise categories. These operators are basically
used for type checking, null handling, and memory referencing. There are few other
important operators including sizeof, typeof and ? : supported by C#.
Operator Description Example
sizeof() Returns the size of a data type. sizeof(int), returns 4.
typeof() Returns the type of a class. typeof(StreamReader);
& Returns the address of an &a; returns actual address of the
variable. variable.
* Pointer to a variable. *a; creates pointer named 'a' to a
variable.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 36


[Link] Programming
?: Conditional Expression If Condition is true ? Then value X :
Otherwise value Y
is Determines whether an object If( Ford is Car) // checks if Ford is an
is of a certain type. object of the Car class.
as Cast without raising an Object obj = new StringReader("Hello");
exception if the cast fails. StringReader r = obj as StringReader;
Example
Open Compiler
using System;
class Program
{
static void Main()
{
// typeof operator
[Link]("Type of int: " + typeof(int));
// sizeof operator
[Link]("Size of int: " + sizeof(int));
// is operator
object obj = "Hello";
[Link]("Is obj a string? " + (obj is string));
// as operator
object number = 42;
string str = number as string;
[Link]("Using 'as' operator: " + (str ?? "Conversion failed"));
// nameof operator
string variableName = nameof(number);
[Link]("Variable name: " + variableName);
}}
Output:
Type of int: System.Int32
Size of int: 4
Is obj a string? True

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 37


[Link] Programming
Using 'as' operator: Conversion failed
Variable name: number
Operator Precedence in C#:
Operator precedence determines the grouping of terms in an expression. This
affects evaluation of an expression. Certain operators have higher precedence than
others; for example, the multiplication operator has higher precedence than the
addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has
higher precedence than +, so the first evaluation takes place for 3*2 and then 7 is
added into it.
Here, operators with the highest precedence appear at the top of the table,
those with the lowest appear at the bottom. Within an expression, higher precedence
operators are evaluated first.
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 38


[Link] Programming
1.11 C# CONDITIONAL STATEMENTS (OR) C# - DECISION MAKING:
Decision making structures requires the programmer to specify one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and optionally,
other statements to be executed if the condition is determined to be false.
Following is the general form of a typical decision-making structure found in
most of the programming languages −

Types of Decision-making Statements:


[Link]. Statement Description

1 if statement An if statement consists of a boolean


expression followed by one or more
statements.
2 if...else statement An if statement can be followed by an
optional else statement, which executes
when the boolean expression is false.
3 nested if statements We can use one if or else if statement
inside another if or else if statement(s).
4 switch statement A switch statement allows a variable to be
tested for equality against a list of values.
5 nested switch statements We can use one switch statement inside
another switch statement(s).

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 39


[Link] Programming
The if Statement:
An if statement consists of a boolean expression followed by one or more
statements.
Example
Open Compiler
using System;
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
// Define a local variable
int temperature = 30;
// Check the condition using an if statement
if (temperature > 25)
{
[Link]("It's a hot day.");
}
[Link]($"Current temperature: {temperature} degree C");
} } }
Output:
It's a hot day.
Current temperature: 30 degree C
The if else Statement:
An if statement can be followed by an optional else statement, which executes
when the boolean expression is false.
Example
Open Compiler
using System;
namespace DecisionMaking
{

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 40


[Link] Programming
class Program
{
static void Main(string[] args)
{
// Define a local variable
int temperature = 21;
// Check the condition using if-else statement
if (temperature > 25)
{
[Link]("It's a hot day.");
}
else
{
[Link]("The weather is pleasant.");
}
[Link]($"Current temperature: {temperature} degree C");
} } }
Output:
The weather is pleasant.
Current temperature: 21 degree C
Nested if Statements:
It is always legal in C# to nest if-else statements, which means we can use one
if or else if statement inside another if or else if statement(s).
Example
Open Compiler
using System;
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 41


[Link] Programming
// Define a local variable
int temperature = 30;
// Check the condition using nested if statements
if (temperature > 0)
{
if (temperature < 15)
{
[Link]("It's a cold day.");
}
else if (temperature <= 15 && temperature >= 25)
{
[Link]("The weather is pleasant.");
}
else
{
[Link]("It's a hot day.");
}
}
else
{
[Link]("It's freezing outside!");
}
[Link]($"Current temperature: {temperature} degree C");
}
} }
Output:
It's a hot day.
Current temperature: 30 degree C
The switch Statement
A switch statement allows a variable to be tested for equality against a list of
values. Each value is called a case, and the variable being switched on is checked for
each switch case.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 42


[Link] Programming
Example
Open Compiler
using System;
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
int day = 3;
switch (day)
{
case 1:
[Link]("Sunday");
break;
case 2:
[Link]("Monday");
break;
case 3:
[Link]("Tuesday");
break;
case 4:
[Link]("Wednesday");
break;
case 5:
[Link]("Thursday");
break;
case 6:
[Link]("Friday");
break;
case 7:
[Link]("Saturday");

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 43


[Link] Programming
break;
default:
[Link]("Invalid day number! Please enter a number
between 1 and 7.");
break;
} } } }
Output:
Tuesday
The ? : Operator
The conditional operator ? : which can be used to replace if...else statements.
It has the following general form −
Exp1 ? Exp2 : Exp3;
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of
the colon.
The value of a ? expression is determined as follows: Exp1 is evaluated. If it is
true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1
is false, then Exp3 is evaluated and its value becomes the value of the expression.
1.12 C# LOOPING STATEMENTS:
A loop statement allows us to execute a statement or a group of statements
multiple times.

Example
In the following example, we define an array and use the loop to display the
elements of the array −
Open Compiler
using System;

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 44


[Link] Programming
class Example {
static void Main(string[] args) {
int[] number = { 1, 2, 3, 5, 6 };

for (int i = 0; i < [Link]; i++) {


[Link](number[i]);
}
}
}
Output
Following is the output −
1
2
3
5
6
Types of C# Looping Statements:
[Link]. Loop Type Description

1 while loop It repeats a statement or a group of statements while a


given condition is true. It tests the condition before
executing the loop body.
2 for loop It executes a sequence of statements multiple times and
abbreviates the code that manages the loop variable.
3 do...while loop It is similar to a while statement, except that it tests the
condition at the end of the loop body
4 nested loops We can use one or more loop inside any another while,
for or do..while loop.

1. The while Loop


The while loop repeats a statement or a group of statements while a given
condition is true. It tests the condition before executing the loop body.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 45


[Link] Programming
Example:
Open Compiler
using System;
namespace LoopExample
{
class Program
{
static void Main(string[] args)
{
// Using a while loop to print numbers from 1 to 5
int i = 1;
while (i <= 5)
{
[Link]("Number: " + i);
i++;
}
}
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
2. The for Loop
The for loop executes a sequence of statements multiple times and abbreviates
the code that manages the loop variable.
Example:
Open Compiler
using System;
namespace LoopExample

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 46


[Link] Programming
{
class Program
{
static void Main(string[] args)
{
// Using a for loop to print numbers from 1 to 5
for (int i = 1; i <= 5; i++)
{
[Link]("Number: " + i);
}
}
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
3. The do while Loop
The do...while loop is similar to a while statement, except that it tests the
condition at the end of the loop body.
Example:
Open Compiler
using System;
namespace LoopExample
{
class Program
{
static void Main(string[] args)
{
// Using a do-while loop to print numbers from 1 to 5

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 47


[Link] Programming
int i = 1;
do
{
[Link]("Number: " + i);
i++;
} while (i <= 5);
}
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Loop Control Statements:
Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope are
destroyed.
C# provides the following control statements.
[Link]. Control Statement Description

1 break statement Terminates the loop or switch statement


and transfers execution to the statement
immediately following the loop or switch.
2 continue statement Causes the loop to skip the remainder of its
body and immediately retest its condition
prior to reiterating.
Example
Open Compiler
using System;
class Example {

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 48


[Link] Programming
static void Main(string[] args) {
int count = 10;

for (int i = 0; i < count; i++) {


if (i == 5) {
break;
}
[Link](i);
}
}
}
Output
0
1
2
3
4
C# Infinite Loop:
A loop becomes infinite loop if a condition never becomes false. The for loop
is traditionally used for this purpose. Since none of the three expressions that form
the for loop are required, we can make an endless loop by leaving the conditional
expression empty.
Example
Open Compiler
using System;
namespace Loops {
class Program {
static void Main(string[] args) {
for (; ; ) {
[Link]("Hey! I am Trapped");
}
}

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 49


[Link] Programming
}
}
When the conditional expression is absent, it is assumed to be true. We may
have an initialization and increment expression, but programmers more commonly
use the for(;;) construct to signify an infinite loop.
1.13 C# CLASS & OBJECTS:
Class and Object are the basic concepts of Object-Oriented Programming
which revolve around real-life entities.
A class is a user-defined blueprint or prototype from which objects are
created. A class combines the fields and methods(member functions which define
actions) into a single unit.
In C#, classes support polymorphism, and inheritance and also provide the
concept of derived classes and base classes.
Declaration of Class in C#:
Generally, A class declaration contains only a keyword class, followed by
an identifier(name) of the class. Class declarations can include these components:
• Modifiers: Used to define accessibility levels by default modifier of the class
is internal.
• Keyword class: A class keyword is used to declare a class.
• Class Identifier: The variable of type class is provided. The identifier(name of
the class) and the initial letter should be capitalized by convention.
• Base class(Optional): If it inherits its parent class(superclass), if any, then
preceded by the : (colon).
• Interfaces(Optional): A comma-separated list of interfaces implemented by
the class, if any, preceded by the : (colon). A class can implement more than
one interface.
• Body: The class body is enclosed by { } (curly braces) and it may contain the
class’s members like properties, methods, constructors events etc.
Example:
// Declaration of class
using System;
// declaring public class

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 50


[Link] Programming
public class Geeks
{
// field variable
public int a, b;
// member function or method
public static void display()
{
[Link]("Class & Objects in C#");
}
public static void Main(String[] args)
{
display();
} }
Output
Class & Objects in C#
Objects in C#:
Object is a basic unit of Object-Oriented Programming and represents real-life
entities. It can also refer to the instance of a class. An object of that class is created.
An object holds data and can access methods and their properties.
In C# an object consists of :
• State: It is represented by attributes of an object, and reflects the properties of
an object.
• Behaviour: It is represented by the methods of an object, and 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 a Dog as an object and see the below diagram for its identity, state,
and behaviour.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 51


[Link] Programming
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):
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.
Initialization of Object:
The new keyword 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:
// Initialization of an object
using System;
// Class Declaration

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 52


[Link] Programming
public class Dog
{
// Instance Variables
String name;
String breed;
int age;
String color;
// Constructor Declaration of Class
// same name as class
public Dog(String name, String breed, int age, String color)
{
[Link] = name;
[Link] = breed;
[Link] = age;
[Link] = color;
}
public String GetName()
{
return name;
}
public String GetBreed()
{
return breed;
}
public int GetAge()
{
return age;
}
public String GetColor()
{
return color;
}

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 53


[Link] Programming
public override String ToString()
{
return "my name is: " + name + "\nmy breed is: " + breed +
"\nmy age is: " + age;
}
public static void Main(String[] args)
{
// Creating object
Dog tuffy = new Dog("tuffy", "papillon", 5, "white");
[Link]([Link]());
} }
Output
my name is: tuffy
my breed is: papillon
my age is: 5
When we create an object of the Dog class and pass the parameters in the
constructor. So it allocates memory for these different objects and their address
points with the class’s object as shown in the image.

1.14 C# - ARRAYS:
An array stores a fixed-size sequential collection of elements of the same type.
An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type stored at contiguous memory
locations.
Instead of declaring individual variables, such as number0, number1, ..., and
number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables. A specific
element in an array is accessed by an index.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 54


[Link] Programming
All arrays consist of contiguous memory locations. The lowest address
corresponds to the first element and the highest address to the last element.

Declaring a C# Array:
We can declare an array in C# by specifying the data type followed by square
brackets and array name.
Syntax
datatype[] arrayName;
Where,
• datatype is used to specify the type of elements in the array.
• [ ] specifies the rank of the array. The rank specifies the size of the array.
• arrayName specifies the name of the array.
For example:
double[] balance;
Initializing an Array:
Declaring an array does not allocate memory for its elements. When the array
variable is initialized, we can assign values to it.
An array is a reference type in C#, so we need to use the new keyword to
allocate memory for its elements.
Syntax
double[] balance = new double[10];
Assigning Values to an Array:
We can assign values to individual array elements using their index number
as,
double[] balance = new double[10];
balance[0] = 4500.0;
We can also assign values to an array at the time of declaration as
double[] balance = { 2340.0, 4523.69, 3421.0 };
We can create and initialize an array using the new keyword as,
int[] marks = new int[5] { 99, 98, 92, 97, 95 };

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 55


[Link] Programming
We may also omit the size of the array when using an initializer list as,
int[] marks = new int[] { 99, 98, 92, 97, 95 };
We can copy an array variable into another target array variable. In this case,
both the target and source will point to the same memory location.
int[] marks = new int[] { 99, 98, 92, 97, 95 };
int[] score = marks;
When we create an array, C# compiler implicitly initializes each array
element to a default value depending on the array type. For example, for an int array
all elements are initialized to 0.
Accessing Array Elements:
We can access array elements using an index within square brackets after the
array name. Array indices start from 0, meaning the first element is at index 0, the
second at 1, and so on.
Example:
double salary = balance[9];
Example (Using for Loop):
Open Compiler
using System;
namespace ArrayApplication {
class MyArray {
static void Main(string[] args) {
int[] n = new int[10]; // n is an array of 10 integers
// Initializing elements of array n
for (int i = 0; i < 10; i++) {
n[i] = i + 100;
}
// Accessing and displaying array elements
for (int j = 0; j < 10; j++) {
[Link]("Element[{0}] = {1}", j, n[j]);
}
[Link]();
} } }

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 56


[Link] Programming
Output:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Example (Using foreach Loop):
Open Compiler
using System;
namespace ArrayApplication {
class MyArray {
static void Main(string[] args) {
int[] n = new int[10]; // n is an array of 10 integers
// Initializing elements of array n
for (int i = 0; i < 10; i++) {
n[i] = i + 100;
}
// Using foreach loop to access array elements
int index = 0;
foreach (int value in n) {
[Link]("Element[{0}] = {1}", index, value);
index++;
}
[Link]();
}
}
}

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 57


[Link] Programming
Output:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Finding the Length of an Array:
We can find the total number of elements in an array using
the Length property. This property returns the total count of elements in an array.
Example:
int[] numbers = { 10, 20, 30, 40, 50 };
int length = [Link];
[Link]("Array Length: " + length);
Example
Open Compiler
using System;
namespace ArrayApplication {
class ArrayLength {
static void Main(string[] args) {
int[] numbers = { 10, 20, 30, 40, 50 };
// Finding length of the array
[Link]("The total number of elements in the array: " +
[Link]);
[Link]();
}
}
}
Output:
The total number of elements in the array: 5

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 58


[Link] Programming
Sorting an Array:
We can sort an array in C# using the [Link]() method, which sorts the
array elements in ascending order.
Example
Open Compiler
using System;
namespace ArrayApplication {
class SortArray {
static void Main(string[] args) {
int[] numbers = { 50, 20, 40, 10, 30 };
// Sorting the array in ascending order
[Link](numbers);
[Link]("Sorted Array:");
foreach (int num in numbers) {
[Link](num + " ");
}
[Link]();
}
}
}
Output:
Sorted Array:
10 20 30 40 50
Sorting Array Elements in Descending Order:
We can sort an array in descending order by using the [Link]() followed
by [Link]().
Syntax
[Link](arrayName);
[Link](arrayName);
Example
Open Compiler
using System;

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 59


[Link] Programming
namespace ArrayApplication {
class SortArray {
static void Main(string[] args) {
int[] numbers = { 50, 20, 40, 10, 30 };
// Sorting the array in descending order
[Link](numbers);
[Link](numbers);
[Link]("Sorted Array in Descending Order:");
foreach (int num in numbers) {
[Link](num + " ");
}
[Link]();
}
} }
Output:
Sorted Array in Descending Order:
50 40 30 20 10
Copying an Array
We can copy an array to another array using
the [Link]() or [Link]() method.
Syntax
[Link](sourceArray, destinationArray, length);
Using Clone() to create a shallow copy:
destinationArray = [Link]() as int[];
Example: Copying an Array
Open Compiler
using System;
namespace ArrayApplication {
class CopyArray {
static void Main(string[] args) {
int[] sourceArray = { 1, 2, 3, 4, 5 };
int[] destinationArray = new int[[Link]];

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 60


[Link] Programming
// Copying array using [Link]()
[Link](sourceArray, destinationArray, [Link]);
[Link]("Copied Array:");
foreach (int num in destinationArray) {
[Link](num + " ");
}
[Link]();
}
}
}
Output:
Copied Array:
12345
Using Clone() to Copy an Array
The Clone() method creates a shallow copy of the array.
Example
Open Compiler
using System;
namespace ArrayApplication {
class CloneArray {
static void Main(string[] args) {
int[] sourceArray = { 10, 20, 30, 40, 50 };
// Cloning the array
int[] clonedArray = (int[])[Link]();
[Link]("Cloned Array:");
foreach (int num in clonedArray) {
[Link](num + " ");
}
[Link]();
}
}
}

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 61


[Link] Programming
Output:
Cloned Array:
10 20 30 40 50
1.15 C# STRINGS:
In C#, we can use strings as array of characters, However, more common
practice is to use the string keyword to declare a string variable. The string keyword
is an alias for the [Link] class.
Creating a String Object:
We can create a string object using one of the following methods −
• By assigning a string literal to a String variable
• By using a String class constructor
• By using the string concatenation operator (+)
• By retrieving a property or calling a method that returns a string
• By calling a formatting method to convert a value or an object to its string
representation
Example to Create a String Object
Open Compiler
using System;
namespace StringApplication {
class Program {
static void Main(string[] args) {
// Creating a string using a string literal and concatenation
string fname, lname;
fname = "Rowan";
lname = "Atkinson";
char[] letters = {'H', 'e', 'l', 'l', 'o'};
string[] sarray = {
"Hello",
"From",
"Tutorials",
"Point"
};

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 62


[Link] Programming
string fullname = fname + " " + lname;
[Link]("Full Name: {0}", fullname);
// Creating a string using a character array
string greetings = new string(letters);
[Link]("Greetings: {0}", greetings);
// Joining an array of strings
string message = [Link](" ", sarray);
[Link]("Message: {0}", message);
// Formatting method to convert a value
DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1);
string chat = [Link]("Message sent at {0:t} on {0:D}", waiting);
[Link]("Message: {0}", chat);
}
}
}
Output:
Full Name: Rowan Atkinson
Greetings: Hello
Message: Hello From Tutorials Point
Message: Message sent at 5:58 PM on Wednesday, October 10, 2012
Creating a String:
We can create a string in C# using string literals or the String class.
Example
Open Compiler
using System;
namespace StringApplication {
class StringProg {
static void Main(string[] args) {
string message = "Hello, C#!";
[Link](message);
}
}

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 63


[Link] Programming
}
Output:
Hello, C#!
Finding String Length:
We can find the length of a string using the Length property.
Example
Open Compiler
using System;
namespace StringApplication {
class StringProg {
static void Main(string[] args) {
string str = "C# Programming";
int length = [Link];
[Link]("Length of the string: " + length);
}
}
}
Output:
Length of the string: 14
Iterate Over String Characters:
We can iterate over each character in a string using a foreach loop.
Example
Open Compiler
using System;
namespace StringApplication {
class StringProg {
static void Main(string[] args) {
string str = "C# by TP";
foreach (char ch in str) {
[Link](ch);
}
}

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 64


[Link] Programming
}
}
Output:
C
#

b
y

T
P
Comparing Strings:
We can compare two strings using the [Link] method or the
equality operator.
Example
Open Compiler
using System;
namespace StringApplication {
class StringProg {
static void Main(string[] args) {
string str1 = "Hello";
string str2 = "World";
if ([Link](str1, str2) == 0) {
[Link]("Strings are equal.");
} else {
[Link]("Strings are not equal.");
}
}
} }
Output:
Strings are not equal.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 65


[Link] Programming
Checking for a Substring:
We can check if a string contains another string using the Contains method.
Example
Open Compiler
using System;
namespace StringApplication {
class StringProg {
static void Main(string[] args) {
string str = "Welcome to C# programming";
if ([Link]("C#")) {
[Link]("The sequence 'C#' was found.");
}
}
}
}
Output:
The sequence 'C#' was found.
Getting a Substring:
We can extract a part of a string using the Substring method.
Example
Open Compiler
using System;
namespace StringApplication {
class StringProg {
static void Main(string[] args) {
string str = "C# Programming Language";
[Link](str);
string substr = [Link](3, 11);
[Link](substr);
}
}
}

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 66


[Link] Programming
Output:
Programming
Joining Strings:
We can join multiple strings using the [Link] method.
Example
Open Compiler
using System;
namespace StringApplication {
class StringProg {
static void Main(string[] args) {
string[] lines = new string[] {
"C# is a modern",
"Object-oriented",
"Programming language"
};
string result = [Link]("\n", lines);
[Link](result);
}
}
}
Output:
C# is a modern
Object-oriented
Programming language
Handling Strings Using StringBuilder:
StringBuilder helps to modify strings because regular strings cannot be
changed directly. We can use StringBuilder to add, insert, or replace text without
creating new string copies.
Example: Using StringBuilder
Open Compiler
using System;
using [Link];

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 67


[Link] Programming
class Program {
static void Main() {
StringBuilder sb = new StringBuilder("Hello");
[Link](" World!");
[Link](6, "C# ");
[Link]("World", "Everyone");
[Link]([Link]());
}
}
Output:
Hello C# Everyone!
Properties of the String Class:
The String class has the following two properties −
[Link]. Property & Description
1 Chars
Gets the Char object at a specified position in the current String object.
2 Length
Gets the number of characters in the current String object.

Methods of the String Class:


The String class has numerous methods that help in working with the string
objects. The following table provides some of the most commonly used methods −
[Link]. Methods & Description
1 Clone()
It returns a reference to this instance of the String.
2 CompareOrdinal()
It compares two strings by evaluating the numeric values of the
corresponding characters in the strings.
3 Compare()
It compares two specified String objects using the specified rules (case
sensitivity, culture-specific, etc.).
4 Concat()
It concatenates two string objects.
5 Contains()
It returns a value indicating whether the specified String object occurs

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 68


[Link] Programming
within this string.
6 CopyTo()
It copies a specified number of characters from this string to a specified
position in a character array.
7 EndsWith()
It determines whether the end of this string instance matches the
specified string.
8 Equals()
It determines whether two specified String objects have the same value.
9 Format()
It replaces format items in a string with the string representation of the
corresponding objects.
10 GetEnumerator()
It retrieves an enumerator that can iterate through the individual
characters in this string.
11 GetHashCode()
It returns the hash code for this string.
12 IndexOfAny()
It finds the index of the first occurrence of any character in a specified
array of characters.
13 IndexOf()
It reports the zero-based index of the first occurrence of a specified
substring within this string.
14 Insert()
It inserts a string at a specified index in the current string.
15 IsNullOrEmpty()
It checks if the string is either null or empty.
16 IsNullOrWhiteSpace()
It checks if the string is null, empty, or consists only of white-space
characters.
17 Join()
It concatenates the string representations of an array of objects, with a
specified separator..
18 LastIndexOf()
It reports the zero-based index of the last occurrence of a specified
substring within the string.
19 PadLeft()
It pads the string on the left with a specified character to achieve a given
total length.
20 PadRight()
It pads the string on the right with a specified character to achieve a

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 69


[Link] Programming
given total length.
21 Remove()
It removes a specified number of characters from the current string,
starting at a given position.
22 Replace()
It replaces all occurrences of a specified substring with another substring.
23 Split()
It splits a string into substrings based on specified delimiters.
24 StartWith()
It determines whether the beginning of this string instance matches the
specified string.
25 Substring()
It retrieves a substring starting at a specified index, continuing to the end
of the string.
26 ToCharArray()
It converts the string to a character array.
27 ToLower()
It converts all characters of the string to lowercase.
28 ToString()
It returns a string representation of the object.
29 ToUpper()
It converts all characters of the string to uppercase.
30 TrimEnd()
It removes all trailing white-space characters from the current string.
31 TrimStart()
It removes all leading white-space characters from the current string.
32 Trim()
It removes all leading and trailing white-space characters from the
current string.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 70


[Link] Programming
UNIT - 2
2.1 INTRODUCTION TO [Link]:
[Link] is an open-source web application framework developed by
Microsoft that allows developers to build dynamic web applications, websites, and
web services. It is part of the .NET ecosystem and provides tools and libraries for
building scalable, high-performance web solutions.

Key Features of [Link]:


Feature Description
Server-side framework Handles business logic and page rendering on the server
before sending to client
Compiled code Offers better performance than interpreted scripts (like
PHP or JavaScript)
Multiple language Primarily C#, [Link], and F#
support
Rich toolbox Integrated with Visual Studio for drag-and-drop controls
and IntelliSense
Built-in security Authentication, authorization, and data protection
mechanisms
Cross-platform Runs on Windows, Linux, and macOS with .NET
([Link] Core) Core/.NET 5+
Modern development Supports MVC, Razor Pages, Web API, Blazor, and
Minimal APIs

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 71


[Link] Programming
[Link] Frameworks and Models:
Model Description
Web Forms Event-driven model, ideal for RAD, but now considered
legacy
MVC (Model-View- Clean separation of concerns, testable, flexible
Controller) architecture
Razor Pages Page-focused model in [Link] Core, simplifies small to
medium web apps
Web API Used to build RESTful services
Blazor C#-based UI development, runs in browser via
WebAssembly or on server

[Link] vs [Link] Core


Aspect [Link] (Full [Link] Core
Framework)
Platform Windows-only Cross-platform (Windows, macOS,
Linux)
Performance Good Excellent (lightweight and high-
performance)
Modular Design Monolithic Modular via NuGet packages
Future Maintenance mode Actively developed and
Development recommended

Use Cases of [Link]


• Business websites and internal portals
• E-commerce platforms
• RESTful APIs and microservices
• Real-time apps (chats, dashboards)
• Interactive front-ends (with Blazor)
Tools and IDEs:
• Visual Studio (most popular IDE for [Link])
• Visual Studio Code (lightweight, cross-platform)
• .NET CLI for command-line development and deployment

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 72


[Link] Programming
[Link] Versions History:
Year Version / Key Features & Milestones
Framework
1996 Classic ASP Introduced with IIS 3.0, VBScript-based, interpreted,
limited separation of logic/UI
2002 [Link] 1.0 Part of .NET Framework 1.0, introduced Web Forms,
code-behind, compiled server-side pages
2003 [Link] 1.1 Improved security and mobile controls support
2005 [Link] 2.0 Master Pages, Membership/Roles, data controls,
Themes/Skins
2007 [Link] 3.5 Integrated LINQ, ListView/DataPager, [Link] AJAX
2010 [Link] 4.0 Enhanced ViewState, URL routing, better HTML output
2012 [Link] 4.5 Async support with async/await, model binding in Web
Forms
2009– [Link] Introduced MVC pattern, clean separation of concerns,
2013 MVC 1–5 testability, Razor syntax
2016 [Link] Modular, cross-platform (Windows, Linux, macOS), high
Core 1.0 performance, unified framework
2017 [Link] Razor Pages, improved identity system, SignalR preview
Core 2.0
2019 [Link] Removed support for Web Forms/MVC 5, introduced
Core 3.0 Blazor and gRPC
2020 [Link] First unified .NET version, improved minimal hosting
Core 5 model
2021 [Link] Minimal APIs, Hot Reload, performance improvements
Core 6 (LTS)
2022 [Link] .NET MAUI integration, better Blazor and SignalR
Core 7 support
2023 [Link] Enhanced Blazor capabilities, native AOT support, AI
Core 8 tools integration
2024 [Link] Focus on cloud-native, AI integration, improved
(Planned) Core 9 performance and tooling (Upcoming)

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 73


[Link] Programming
2.2 [Link] IDE:
[Link] provides an abstraction layer on top of HTTP on which the web
applications are built. It provides high-level entities such as classes and components
within an object-oriented paradigm. The key development tool for building
[Link] applications and front ends is Visual Studio.
Visual Studio is an integrated development environment for writing,
compiling, and debugging the code. It provides a complete set of development tools
for building [Link] web applications, web services, desktop applications, and
mobile applications.
Installation:
Microsoft provides a free version of visual studio which also contains SQL
Server and it can be downloaded from [Link].
Step 1 − Once downloading is complete, run the installer. The following dialog will
be displayed.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 74


[Link] Programming
Step 2 − Click on the Install button and it will start the installation process.

Step 3 − Once the installation process is completed successfully, you will see the
following dialog. Close this dialog and restart your computer if required.

Step 4 − Open Visual Studio from start Menu which will open the following dialog.
It will be a while for the first time for preparation.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 75


[Link] Programming

Step 5 − Once all is done you will see the main window of Visual studio.

Let’s create a new project from File → New → Project

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 76


[Link] Programming

The Visual Studio IDE:


The new project window allows choosing an application template from the
available templates.

When start a new web site, [Link] provides the starting folders and files
for the site, including two files for the first web form of the site.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 77


[Link] Programming
• [Link] contains the HTML and asp code that defines the form
• [Link] (for C# coding) or [Link] (for VB coding)
contains the code in the language we have chosen and this code is
responsible for the actions performed on a form.
The windows in the Visual Studio IDE are
Web Forms Designer window
Toolbox,
Solution Explorer, and
Properties window.
Working with Views and Windows
We can work with windows in the following ways:
• To change the Web Forms Designer from one view to another, click on the
Design or source button.
• To close a window, click on the close button on the upper right corner and
to redisplay, select it from the View menu.
• To hide a window, click on its Auto Hide button. The window then
changes into a tab. To display again, click the Auto Hide button again.
• To change the size of a window, just drag it.

Adding Folders and Files to your Website:


When a new web form is created, Visual Studio automatically generates the
starting HTML for the form and displays it in Source view of the web forms

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 78


[Link] Programming
designer. The Solution Explorer is used to add any other files, folders or any existing
item on the web site.
• To add a standard folder, right-click on the project or folder under which we
are going to add the folder in the Solution Explorer and choose New Folder.
• To add an [Link] folder, right-click on the project in the Solution Explorer
and select the folder from the list.
• To add an existing item to the site, right-click on the project or folder under
which we are going to add the item in the Solution Explorer and select from
the dialog box.
Projects and Solutions:
A typical [Link] application consists of many items:
web content files (.aspx),
source files (.cs files),
assemblies (.dll and .exe files),
data source files (.mdb files),
references,
icons,
user controls and
miscellaneous other files and folders.
All these files that make up the website are contained in a Solution.
When a new website is created. VB2008 automatically creates the solution and
displays it in the solution explorer.
Solutions may contain one or more projects. A project contains
content files,
source files, and
other files like data sources and image files.
The contents of a project are compiled into an assembly as an executable file
(.exe) or a dynamic link library (.dll) file.
The project contains the following content files:
• Page file (.aspx)
• User control (.ascx)
• Web service (.asmx)

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 79


[Link] Programming
• Master page (.master)
• Site map (.sitemap)
• Website configuration file (.config)
Building and Running a Project:
You can execute an application by:
• Selecting Start
• Selecting Start Without Debugging from the Debug menu,
• pressing F5
• Ctrl-F5
The program is built meaning, the .exe or the .dll files are generated by
selecting a command from the Build menu.
2.3 LANGUAGES SUPPORTED & COMPONENTS IN [Link]:
[Link] is a multi-language, multi-component framework.
Languages Supported in [Link]:
[Link] supports all languages that are compliant with the Common
Language Runtime (CLR). Most commonly used languages include:
Language Usage
C# Most popular choice for [Link] development
[Link] Visual Basic .NET, commonly used in legacy projects
F# Functional-first language; less common in [Link], but fully
supported
Other CLR Python (IronPython), Ruby (IronRuby), [Link] (less
Languages common)

Core Components of [Link]:


[Link] consists of multiple components that allow developers to build
dynamic, scalable, and secure web applications.
1. [Link] Web Forms
• UI-centric event-driven framework.
• Uses controls, ViewState, and code-behind.
• Good for RAD (Rapid Application Development).
• Not recommended for new projects (legacy).

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 80


[Link] Programming
2. [Link] MVC (Model-View-Controller)
• Clean separation of concerns.
• Fully supports testability and TDD.
• Razor View Engine for dynamic HTML rendering.
3. [Link] Web API
• Lightweight framework for building RESTful services.
• Often used in SPA (Single Page Applications) and mobile apps.
4. [Link] SignalR
• Real-time communication using WebSockets.
• Ideal for chat apps, live dashboards, gaming, etc.
5. [Link] Razor Pages
• Introduced in [Link] Core.
• Page-focused development model.
• Simpler than MVC for small to medium apps.
6. [Link] Core
• Unified platform for MVC, Web API, SignalR, Razor Pages, and gRPC.
• Cross-platform and high performance.
• Modular and cloud-optimized.
7. Blazor
• Web UI framework using C# instead of JavaScript.
• Two flavors:
• Blazor Server: Server-side rendering with SignalR.
• Blazor WebAssembly: Runs entirely in the browser via WebAssembly.
Supporting Features & Tools:
Feature Description
Entity Framework ORM for database access (EF Core in .NET Core)
Razor Syntax Markup syntax for embedding C# in HTML
Identity Authentication and authorization system
Middleware Pipeline components for handling requests/responses
([Link] Core)
Dependency Built-in service container for managing app services
Injection

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 81


[Link] Programming
2.4 [Link] WEB FORMS:
Web Forms are web pages built on the [Link] Technology. It executes on
the server and generates output to the browser.
It is compatible to any browser to any language supported by .NET common
language runtime. It is flexible and allows us to create and add custom controls.
We can use Visual Studio to create [Link] Web Forms. It is an IDE
(Integrated Development Environment) that allows us to drag and drop server
controls to the web forms.
It also allows us to set properties, events and methods for the controls. To
write business logic, we can choose any .NET language like: Visual Basic or Visual
C#.
Web Forms are made up of two components: the visual portion (the ASPX
file), and the code behind the form, which resides in a separate class file.

The main purpose of Web Forms is to overcome the limitations of ASP and
separate view from the application logic.
[Link] provides various controls like:
Server controls and
HTML controls for the Web Forms.
[Link] Web Forms Server Controls:
[Link] provides web forms controls that are used to create HTML
components. These controls are categories as server and client based.
Control Name Applicable Events Description
Label None It is used to display text on the
HTML page.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 82


[Link] Programming
TextBox TextChanged It is used to create a text input in
the form.
Button Click, Command It is used to create a button.
LinkButton Click, Command It is used to create a button that
looks similar to the hyperlink.
ImageButton Click It is used to create an images
Button. Here, an image works as
a Button.
Hyperlink None It is used to create a hyperlink
control that responds to a click
event.
DropDownList SelectedIndexChanged It is used to create a dropdown
list control.
ListBox SelectedIndexCnhaged It is used to create a ListBox
control like the HTML control.
DataGrid CancelCommand, It used to create a frid that is
EditCommand, used to show data. We can also
DeleteCommand, perform paging, sorting, and
ItemCommand, formatting very easily with this
SelectedIndexChanged, control.
PageIndexChanged,
SortCommand,
UpdateCommand,
ItemCreated, ItemDataBound
DataList CancelCommand, It is used to create datalist that is
EditCommand, non-tabular and used to show
DeleteCommand, data.
ItemCommand,
SelectedIndexChanged,
UpdateCommand,
ItemCreated, ItemDataBound

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 83


[Link] Programming
CheckBox CheckChanged It is used to create checkbox.
CheckBoxList SelectedIndexChanged It is used to create a group of
check boxes that all work
together.
RadioButton CheckChanged It is used to create radio button.
RadioButtonList SelectedIndexChanged It is used to create a group of
radio button controls that all
work together.
Image None It is used to show image within
the page.
Panel None It is used to create a panel that
works as a container.
PlaceHolder None It is used to set placeholder for
the control.
Calendar SelectionChanged, It is used to create a calendar.
VisibleMonthChanged, We can set the default date,
DayRender move forward and backward etc.
AdRotator AdCreated It allows us to specify a list of
ads to display. Each time the
user re-displays the page.
Table None It is used to create table.
XML None It is used to display XML
documents within the HTML.
Literal None It is like a label in that it displays
a literal, but allows us to create
new literals at runtime and place
them into this control.

HTML Controls:
These controls render by the browser. We can also make HTML controls as
server control.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 84


[Link] Programming
Controls Name Description
Button It is used to create HTML button.
Reset Button Resets all other HTML form elements on a form to a default value
Submit Button Automatically POSTs the form data to the specified page listed in
the Action attribute in the FORM tag
Text Field Gives the user an input area on an HTML form
Text Area Used for multi-line input on an HTML form
File Field Places a text field and a Browse button on a form and allows the
user to select a file name from their local machine when the Browse
button is clicked
Password Field An input area on an HTML form, although any characters typed
into this field are displayed as asterisks
CheckBox Gives the user a check box that they can select or clear
Radio Button Used two or more to a form, and allows the user to choose one of
the controls
Table Allows you to present information in a tabular format
Image Displays an image on an HTML form
ListBox Displays a list of items to the user. You can set the size from two or
more to specify how many items you wish show. If there are more
items than will fit within this limit, a scroll bar is automatically
added to this control.
Dropdown Displays a list of items to the user, but only one item at a time will
appear. The user can click a down arrow from the side of this
control and a list of items will be displayed.
Horizontal Rule Displays a horizontal line across the HTML page

2.5 [Link] WEB FORMS PROJECT:


We are using Visual studio 2017 to create web project. It includes the
following steps:
1. Creating a new project
Click on the file menu from the menu bar and select new -> project.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 85


[Link] Programming

Select Project type


It provides couple of choices but we selecting [Link] Web Application.

Select Project Template


After selecting project types, now, it asks for the type of template that we
want to implement in our application.
Here, we are selecting Web Forms as because we are creating a Web Forms
application.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 86


[Link] Programming

After clicking ok, it shows project in solution explorer window that looks like
the below.

This project contains a [Link] file which is a startup file. When we run
the project, this file executes first and display a home page of the site.
We can see its output on the browser by selecting view in browser option as we did
below.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 87


[Link] Programming

Finally, it shows output in the browser like this:

Well, we have created a project successfully and running on the browser.


Create a New Web Form
Here, we are using the project that we created in last topic. To add a new web
form in our existing project, first select project then right click and add new item.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 88


[Link] Programming

Select web forms option in left corner and then select web form and hit add button.

Now click on the add button and this form will add to our project.
After adding form, we can see that this is now in our project as we have shown in
the below image.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 89


[Link] Programming

Double click on this form and this will show some auto generated code like this:

[Link]:
<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”user-
[Link]”
Inherits=”[Link].user_form” %>
<!DOCTYPE html>
<html xmlns=”[Link]
<head runat=”server”>
<title></title>
</head>
<body>

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 90


[Link] Programming
<form id=”form1” runat=”server”>
<div>
</div>
</form>
</body>
</html>
If we run this file on the browser, it does not show any output. So, let’s print
some message by this form.
[Link]:
<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”user-
[Link]”
Inherits=”[Link].user_form” %>
<!DOCTYPE html>
<html xmlns=”[Link]
<head runat=”server”>
<title></title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<h2>Welcome to the Web Forms!</h2>
</div>
</form>
</body>
</html>
After running it on the browser it yields the following output.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 91


[Link] Programming
[Link] WEB FORM CONTROL CLASSES
2.6 WEB FORM STANDARD CONTROLS (OR) HTML CONTROLS:
2.6.1 LABEL:
This control is used to display textual information on the web forms. It is
mainly used to create caption for the other controls like: textbox.
To create label either we can write code or use the drag and drop facility of
visual studio 2017.
This is server-side control, asp provides own tag to create label. The example
is given below.
• < asp:LabelID="Label1" runat="server" Text="Label" ></asp:Label>
Property Description
AccessKey It is used to set keyboard shortcut for the label.
TabIndex The tab order of the control.
BackColor It is used to set background color of the label.
BorderColor It is used to set border color of the label.
BorderWidth It is used to set width of border of the label.
Font It is used to set font for the label text.
ForeColor It is used to set color of the label text.
Text It is used to set text to be shown for the label.
ToolTip It displays the text when mouse is over the label.
Visible To set visibility of control on the form.
Height It is used to set height of the control.
Width It is used to set width of the control.
Example
[Link]
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebCont
[Link]" Inherits="[Link]" %>
<!DOCTYPE html>
<html xmlns="[Link]
<head runat="server">
<title></title>
<style type="text/css">

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 92


[Link] Programming
.auto-style1 {
width: 100%;
}
.auto-style2 {
margin-left: 0px;
}
.auto-style3 {
width: 121px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<h4>Provide the Following Details:</h4>
<table class="auto-style1">
<tr>
<td class="auto-style3">
<asp:Label ID="Label1" runat="server" Text="User Name"></asp:Label></td>
<td>
<asp:TextBox ID="TextBox1" runat="server" CssClass="auto-style2">
</asp:TextBox></td>
</tr>
<tr>
<td class="auto-style3">
<asp:Label ID="Label2" runat="server" Text="Upload a File"></asp:Label>
</td>
<td>
<asp:FileUpload ID="FileUpload1" runat="server" /></td>
</tr>
</table>
</div>

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 93


[Link] Programming
</form>
</body>
</html>
This is a property window of label control.

Output:
Here, we have used label control with two different controls. It produces the
following output.

2.6.2 TEXTBOX:
This is an input control which is used to take user input. To
create TextBox either we can write code or use the drag and drop facility of visual
studio IDE.
This is server-side control, asp provides own tag to create it. The example is
given below.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 94


[Link] Programming
• < asp:TextBoxID=”TextBox1” runat=”server” ></asp:TextBox>
Server renders it as the HTML control and produces the following code to the
browser.
• <input name=”TextBox1” id=”TextBox1” type=”text”>
Property Description
AccessKey It is used to set keyboard shortcut for the control.
TabIndex The tab order of the control.
BackColor It is used to set background color of the control.
BorderColor It is used to set border color of the control.
BorderWidth It is used to set width of border of the control.
Font It is used to set font for the control text.
ForeColor It is used to set color of the control text.
Text It is used to set text to be shown for the control.
ToolTip It displays the text when mouse is over the control.
Visible To set visibility of control on the form.
Height It is used to set height of the control.
Width It is used to set width of the control.
MaxLength It is used to set maximum number of characters that
can be entered.
Readonly It is used to make control readonly.

Example
[Link]
<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”WebCo
[Link]” Inherits=”[Link]” %>
<!DOCTYPE html>
<html xmlns=”[Link]
<head runat=”server”>
<title></title>
</head>
<body>

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 95


[Link] Programming
<form id=”form1” runat=”server”>
<div>
<asp:Label ID=”labelId” runat=”server”>User Name</asp:Label>
<asp:TextBox ID=”UserName” runat=”server” ToolTip=”Enter User Name”>
</asp:TextBox>
</div>
<p>
<asp:Button ID=”SubmitButton” runat=”server” Text=”Submit” OnClick=”S
ubmitButton_Click” />
</p>
<br />
</form>
<asp:Label ID=”userInput” runat=”server”></asp:Label>
</body>
</html>
[Link]
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
namespace WebFormsControlls
{
public partial class WebControls : [Link]
{
protected void SubmitButton_Click(object sender, EventArgs e)
{
[Link] = [Link];
}
}
}

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 96


[Link] Programming
This is a property window of the TextBox control.

Output:
It produces the following output.

It displays user input, when user submits the input to the server. The
following screen shot taking and showing user input.

2.6.3 BUTTON:
This control is used to perform events. It is also used to submit client request
to the server. To create Button either we can write code or use the drag and drop
facility of visual studio IDE.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 97


[Link] Programming
This is a server-side control and asp provide own tag to create it.
• < asp:ButtonID="Button1" runat="server" Text="Submit" BorderStyle="Solid"
ToolTip="Submit"/>
Server renders it as the HTML control and produces the following code to the
browser.
• <input name="Button1" value="Submit" id="Button1" title="Submit" style="b
order-style:Solid;" type="submit">
Property Description
AccessKey It is used to set keyboard shortcut for the control.
TabIndex The tab order of the control.
BackColor It is used to set background color of the control.
BorderColor It is used to set border color of the control.
BorderWidth It is used to set width of border of the control.
Font It is used to set font for the control text.
ForeColor It is used to set color of the control text.
Text It is used to set text to be shown for the control.
ToolTip It displays the text when mouse is over the control.
Visible To set visibility of control on the form.
Height It is used to set height of the control.
Width It is used to set width of the control.
Example
[Link]
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebCont
[Link]" Inherits="[Link]" %>
<!DOCTYPE html>
<html xmlns="[Link]
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 98


[Link] Programming
<div>
<asp:Button ID="Button1" runat="server" Text="Click here" OnClick="Button
1_Click" />
</div>
</form>
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</body>
</html>
[Link]
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
namespace WebFormsControlls
{
public partial class WebControls : [Link]
{
protected void Button1_Click(object sender, EventArgs e)
{
[Link] = "You Clicked the Button.";
}
}
}

Output:
It produces the following output.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 99


[Link] Programming

This button displays a message when clicked, as shown below.

2.6.4 HYPERLINK:
It is a control that is used to create a hyperlink. It responds to a click event.
We can use it to refer any web page on the server.
To create HyperLink either we can write code or use the drag and drop
facility of visual studio IDE. This control is listed in the toolbox.
This is a server-side control and [Link] provides own tag to create it. The
example is given below.
• < asp:HyperLinkID=”HyperLink1” runat=”server” Text=”JavaTpoint” Navig
ateUrl=”[Link]” ></asp:HyperLink>
Server renders it as the HTML control and produces the following code to the
browser.
• <a id=”HyperLink1” href=”[Link]”>JavaTpoint</a>
Property Description
AccessKey It is used to set keyboard shortcut for the control.
TabIndex The tab order of the control.
BackColor It is used to set background color of the control.
BorderColor It is used to set border color of the control.
BorderWidth It is used to set width of border of the control.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 100


[Link] Programming
Font It is used to set font for the control text.
ForeColor It is used to set color of the control text.
Text It is used to set text to be shown for the control.
ToolTip It displays the text when mouse is over the control.
Visible To set visibility of control on the form.
Height It is used to set height of the control.
Width It is used to set width of the control.
NavigateUrl It is used to set navigate URL.
Target Target frame for the navigate url.

Example:
[Link]:
<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”user-
[Link]” Inherits=”[Link].user_form” %>
<!DOCTYPE html>
<html xmlns=”[Link]
<head runat=”server”>
<title></title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:HyperLink ID=”HyperLink1” runat=”server” Text=”JavaTpoint” Navig
ateUrl=”[Link]”></asp:HyperLink>
</div>
</form>
</body>
</html>
This property window shows properties for the HyperLink control.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 101


[Link] Programming

Output:

This link redirects to Javatpoint home page.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 102


[Link] Programming
2.6.5 LINKBUTTON:
It is a server web control that acts as a hyperlink. It is used to display a
hyperlink-style button control on the web page. [Link] provides a tag to create
LinkButton and has following syntax.
[Link] LinkButton Syntax
<asp:LinkButton
AccessKey="string"
ID="string"
OnClick="Click event handler"
OnClientClick="string"
OnCommand="Command event handler"
OnDataBinding="DataBinding event handler"
OnDisposed="Disposed event handler"
OnInit="Init event handler"
OnLoad="Load event handler"
OnPreRender="PreRender event handler"
OnUnload="Unload event handler"
PostBackUrl="uri"
runat="server" />
[Link] LinkButton Example
[Link]
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="[Link]" Inherits="[Link]
kButtonExample" %>
<!DOCTYPE html>
<html xmlns="[Link]
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 103


[Link] Programming
<p>It is a hyperlink style button</p>
</div>
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Cl
ick">javatpoint</asp:LinkButton>
<p>
<asp:Label ID="Label1" runat="server"></asp:Label>
</p>
</form>
</body>
</html>
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
namespace LinkButtonExample
{
public partial class LinkButtonExample : [Link]
{
protected void LinkButton1_Click(object sender, EventArgs e)
{
[Link] = "Welcome to the javatpoint";
}
}
}
Output:

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 104


[Link] Programming
A message is shown when LinkButton is clicked.

2.6.6 COOKIE:
[Link] Cookie is a small bit of text that is used to store user-specific
information. This information can be read by the web application whenever user
visits the site.
When a user requests for a web page, web server sends not just a page, but
also a cookie containing the date and time. This cookie stores in a folder on the user's
hard disk.
When the user requests for the web page again, browser looks on the hard drive
for the cookie associated with the web page. Browser stores separate cookie for each
different sites user visited.
There are two ways to store cookies in [Link] application.
o Cookies collection
o HttpCookie
We can add Cookie either to Cookies collection or by creating instance of
HttpCookie class. both work same except that HttpCookie require Cookie name as
part of the constructor.
HttpCookie Example
In the following example, we are creating and adding cookie with the help of
HttpCookie class.
// [Link]
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="[Link]" Inherits="[Link]
mple" %>
<!DOCTYPE html>
<html xmlns="[Link]

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 105


[Link] Programming
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
// [Link]
using System;
using [Link];
namespace WebFormsControlls
{
public partial class CookieExample : [Link]
{
protected void Page_Load(object sender, EventArgs e)
{
//-------------- Creating Cookie --------------------------//
// Creating HttpCookie instance by specifying name "student"
HttpCookie cokie = new HttpCookie("student");
// Assigning value to the created cookie
[Link] = "Rahul Kumar";
// Adding Cookie to the response instance
[Link](cokie);
//--------------- Fetching Cookie -------------------------//
var co_val = [Link]["student"].Value;
[Link] = co_val;
}
}

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 106


[Link] Programming
}
Cookie Collection Example
In the following example, we are adding cookie directly to the Cookies
collection.
// [Link]
<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeBe
hind="[Link]"
Inherits="CoockieExample._Default" %>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Select Brand Preferences"></asp
:Label>
<br />
<br />
<asp:CheckBox ID="apple" runat="server" Text="Apple" />
<br />
<asp:CheckBox ID="dell" runat="server" Text="Dell" />
<br />
<asp:CheckBox ID="lenevo" runat="server" Text="Lenevo" />
<br />
<asp:CheckBox ID="acer" runat="server" Text="Acer" />
<br />
<asp:CheckBox ID="sony" runat="server" Text="Sony" />
<br />
<asp:CheckBox ID="wipro" runat="server" Text="Wipro" />
<br />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Sub
mit" />
<p>
<asp:Label ID="Label2" runat="server"></asp:Label>
</p>
</form>

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 107


[Link] Programming
// [Link]
using System;
using [Link];
namespace CoockieExample
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Setting expiring date and time of the cookies
[Link]["computer"].Expires = [Link](-1);
}
protected void Button1_Click(object sender, EventArgs e)
{
[Link] = "";
// --------------- Adding Coockies ---------------------//
if ([Link])
[Link]["computer"]["apple"] = "apple";
if ([Link])
[Link]["computer"]["dell"] = "dell";
if ([Link])
[Link]["computer"]["lenevo"] = "lenevo";
if ([Link])
[Link]["computer"]["acer"] = "acer";
if ([Link])
[Link]["computer"]["sony"] = "sony";
if ([Link])
[Link]["computer"]["wipro"] = "wipro";
// --------------- Fetching Cookies -----------------------//
if ([Link]["computer"].[Link]() != null)
{
if ([Link]["computer"]["apple"] != null)

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 108


[Link] Programming
[Link] += [Link]["computer"]["apple"] + " ";
if ([Link]["computer"]["dell"] != null)
[Link] += [Link]["computer"]["dell"] + " ";
if ([Link]["computer"]["lenevo"] != null)
[Link] += [Link]["computer"]["lenevo"] + " ";
if ([Link]["computer"]["acer"] != null)
[Link] += [Link]["computer"]["acer"] + " ";
if ([Link]["computer"]["sony"] != null)
[Link] += [Link]["computer"]["sony"] + " ";
if ([Link]["computer"]["wipro"] != null)
[Link] += [Link]["computer"]["wipro"] + " ";
}else [Link] = "Please select your choice";
[Link]["computer"].Expires = [Link](-1);
}
}
}
Output:
This example will store selected values as cookie.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 109


[Link] Programming
2.6.7 SESSION:
In [Link] session is a state that is used to store and retrieve values of a
user.
It helps to identify requests from the same browser during a time period
(session). It is used to store value for the particular time session. By default,
[Link] session state is enabled for all [Link] applications.
Each created session is stored in SessionStateItemCollection object. We can
get current session value by using Session property of Page object. Let's see an
example, how to create an access session in [Link] application.
[Link] Session Example
In the following example, we are creating a session and storing user email. This
example contains the following files.
// [Link]
<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeBe
hind="[Link]"
Inherits="SessionExample._Default" %>
<head>
<style type="text/css">
.auto-style1 {
width: 100%;
}
.auto-style2 {
width: 105px;
}
</style>
</head>
<form id="form1" runat="server">
<p>Provide Following Details</p>
<table class="auto-style1">
<tr>
<td class="auto-style2">Email</td>
<td>

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 110


[Link] Programming
<asp:TextBox ID="email" runat="server" TextMode="Email"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style2">Password</td>
<td>
<asp:TextBox ID="password" runat="server" TextMode="Password"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style2"> </td>
<td>
<asp:Button ID="login" runat="server" Text="Login" OnClick="login_Click" />
</td>
</tr>
</table>
<br />
<asp:Label ID="Label3" runat="server"></asp:Label>
<br />
<asp:Label ID="Label4" runat="server"></asp:Label>
</form>
Code
// [Link]
using System;
using [Link];
namespace SessionExample
{
public partial class _Default : Page
{
protected void login_Click(object sender, EventArgs e)
{
if ([Link]=="qwe123")

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 111


[Link] Programming
{
// Storing email to Session variable
Session["email"] = [Link];
}
// Checking Session variable is not empty
if (Session["email"] != null)
{
// Displaying stored email
[Link] = "This email is stored to the session.";
[Link] = Session["email"].ToString();
}
}
}
}
Output:
This application will store user email to the session when user login.

It will show stored session value, user email.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 112


[Link] Programming
2.7 LIST CONTROLS:
2.7.1 RADIOBUTTON:
It is an input control which is used to takes input from the user. It allows user
to select a choice from the group of choices.
To create RadioButton we can drag it from the toolbox of visual studio.
This is a server-side control and [Link] provides own tag to create it. The
example is given below.
• < asp:RadioButtonID="RadioButton1" runat="server" Text="Male" GroupNa
me="gender"/>
Server renders it as the HTML control and produces the following code to the
browser.
• <input id="RadioButton1" type="radio" name="gender" value="RadioButton1
" /><labelforlabelfor="RadioButton1">Male</label>
Property Description
AccessKey It is used to set keyboard shortcut for the control.
TabIndex The tab order of the control.
BackColor It is used to set background color of the control.
BorderColor It is used to set border color of the control.
BorderWidth It is used to set width of border of the control.
Font It is used to set font for the control text.
ForeColor It is used to set color of the control text.
Text It is used to set text to be shown for the control.
ToolTip It displays the text when mouse is over the control.
Visible To set visibility of control on the form.
Height It is used to set height of the control.
Width It is used to set width of the control.
GroupName It is used to set name of the radio button group.
Example
In this example, we are creating two radio buttons and putting in a group
named gender.
[Link]

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 113


[Link] Programming
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebCont
[Link]" Inherits="[Link]" %>
<!DOCTYPE html>
<html xmlns="[Link]
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:RadioButton ID="RadioButton1" runat="server" Text="Male" GroupNa
me="gender" />
<asp:RadioButton ID="RadioButton2" runat="server" Text="Female" GroupN
ame="gender" />
</div>
<p>
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_
Click" style="width: 61px" />
</p>
</form>
<asp:Label runat="server" id="genderId"></asp:Label>
</body>
</html>
[Link]
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
namespace WebFormsControlls
{

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 114


[Link] Programming
public partial class WebControls : [Link]
{
protected void Button1_Click(object sender, EventArgs e)
{
[Link] = "";
if ([Link])
{
[Link] = "Your gender is "+[Link];
}
else [Link] = "Your gender is "+[Link];
} } }
For this control we have set some properties like this:

Output:
It produces the following output to the browser.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 115


[Link] Programming
It responses back to the client when user select the gender.

2.7.2 CHECKBOX:
It is used to get multiple inputs from the user. It allows user to select choices
from the set of choices.
It takes user input in yes or no format. It is useful when we want multiple
choices from the user.
To create CheckBox we can drag it from the toolbox in visual studio.
This is a server side control and [Link] provides own tag to create it. The
example is given below.
• < asp:CheckBox ID="CheckBox2" runat="server" Text="J2EE"/>
Server renders it as the HTML control and produces the following code to the
browser.
• < input id="CheckBox2" type="checkbox" name="CheckBox2" /><label for="
CheckBox2">J2EE</label>
Property Description
AccessKey It is used to set keyboard shortcut for the control.
TabIndex The tab order of the control.
BackColor It is used to set background color of the control.
BorderColor It is used to set border color of the control.
BorderWidth It is used to set width of border of the control.
Font It is used to set font for the control text.
ForeColor It is used to set color of the control text.
Text It is used to set text to be shown for the control.
ToolTip It displays the text when mouse is over the control.
Visible To set visibility of control on the form.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 116


[Link] Programming
Height It is used to set height of the control.
Width It is used to set width of the control.
Checked It is used to set check state of the control either true or false.
Example
[Link]
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebCont
[Link]" Inherits="[Link]" %>
<!DOCTYPE html>
<html xmlns="[Link]
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Select Courses</h2>
<asp:CheckBox ID="CheckBox1" runat="server" Text="J2SE" />
<asp:CheckBox ID="CheckBox2" runat="server" Text="J2EE" />
<asp:CheckBox ID="CheckBox3" runat="server" Text="Spring" />
</div>
<p>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_C
lick" />
</p>
</form>
<p>
Courses Selected: <asp:Label runat="server" ID="ShowCourses"></asp:Label
>
</p>
</body>
</html>

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 117


[Link] Programming
[Link]
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
namespace WebFormsControlls
{
public partial class WebControls : [Link]
{
protected void Page_Load(object sender, EventArgs e)
{
[Link] = "None";
}
protected void Button1_Click(object sender, EventArgs e)
{
var message = "" ;
if ([Link])
{
message = [Link]+" ";
}
if ([Link])
{
message += [Link] + " ";
}
if ([Link])
{
message += [Link];
}
[Link] = message;
}

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 118


[Link] Programming
}
}

Initially, there is no course selected then it shows none. It displays user


selection as shown in the following screenshot.

2.7.3 DROPDOWNLIST:
The DropDownList is a web server control which is used to create an HTML
Select component. It allows us to select an option from the dropdown list. It can
contain any number of items
[Link] provides a tag to create DropDownList for web application. The
following is the Syntax of DropDownList tag.
<asp:DropDownList id="DropDownList1" runat="server"
DataSource="<% databindingexpression %>"
DataTextField="DataSourceField"
DataValueField="DataSourceField"
AutoPostBack="True|False"
OnSelectedIndexChanged="OnSelectedIndexChangedMethod">
<asp:ListItem value="value" selected="True|False">
Text

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 119


[Link] Programming
</asp:ListItem>
</asp:DropDownList>
[Link] DropDownList Example
We are creating DropDownList by using Visual Studio 2017. This example
includes the following steps.
Create a Web Form
Add a new form by specifying its name.

Initially, it is an empty form. Now, we will add a new DropDownList by dragging it


from the toolbox.

After dragging, our web form looks like the below.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 120


[Link] Programming
Now, to add items to the list, visual studio provides Items property where we can
add items. The property window looks like this.

Click on the items (collection) and it will pop up a new window as given
below. Initially, it does not have any item. It provides add button to add new items
to the list.

Adding item to the DropDownList, by providing values to the Text and Value
properties.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 121


[Link] Programming
We have added more items to it and now, it looks like the following.

After clicking OK,


[Link]
<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true"
CodeBehind="[Link]" Inherits="DropDownListExample._Default" %>
<!DOCTYPE html>
<html xmlns="[Link]
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<p>Select a City of Your Choice</p>
<div>
<asp:DropDownList ID="DropDownList1" runat="server" >
<asp:ListItem Value="">Please Select</asp:ListItem>
<asp:ListItem>New Delhi </asp:ListItem>
<asp:ListItem>Greater Noida</asp:ListItem>
<asp:ListItem>NewYork</asp:ListItem>
<asp:ListItem>Paris</asp:ListItem>
<asp:ListItem>London</asp:ListItem>
</asp:DropDownList>

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 122


[Link] Programming
</div>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />

<br />
<br />
<asp:Label ID="Label1" runat="server" EnableViewState="False"></asp:Label>
</form>
</body>
</html>
// [Link]
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
namespace DropDownListExample
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if ([Link] == "")
{
[Link] = "Please Select a City";
}
else
[Link] = "Your Choice is: " + [Link];
}

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 123


[Link] Programming
}
}
Output:

At server side, selected city is fetched and display to the user.

Prepared By: Mr. M. Pandiaraj, MCA., [Link]., NET. 124

Common questions

Powered by AI

Namespaces in the .NET Framework provide a logical separation of classes and functions, preventing name collisions and organizing code into manageable sections. This enhances code organization by allowing developers to group related functionalities, making the codebase easier to navigate and maintain. For example, System and Microsoft namespaces encapsulate classes for specific tasks, promoting code reuse and reducing the learning curve for new developers .

The main components of the .NET Framework include CLR (Common Language Runtime), CTS (Common Type System), BCL (Base Class Library), CLS (Common Language Specification), FCL (Framework Class Library), .NET Assemblies, XML Web Services, and Windows Services. The CLR provides an environment for running .NET applications, CTS defines how types are declared and used, BCL provides foundational classes, CLS is a set of base rules to ensure interoperability, FCL offers reusable, object-oriented libraries, Assemblies are the building blocks of .NET applications, XML Web Services enable web-based connectivity, and Windows Services support background processes .

Server-side controls in ASP.NET, like TextBox and CheckBox, improve user interface design by providing a consistent way to handle user input and interactions. By allowing developers to specify properties such as text, appearance, and behavior on the server side, these controls help create dynamic and responsive user interfaces that enhance user experience. Additionally, server-side processing allows for the validation and processing of user input before it reaches the client, reducing errors and improving performance .

While the .NET Framework is initially built for Windows, cross-platform compatibility is achieved through .NET Core and Mono, allowing it to run on various operating systems. However, developers should consider potential Windows dependency issues, as certain features may be optimized primarily for Windows. Additionally, variations in operating system architecture might require additional testing to ensure consistent behavior across platforms .

The .NET Framework handles security through features like Code Access Security (CAS), which limits the permissions granted to code based on its origin, and digital signatures, which verify the authenticity of code. Furthermore, the framework supports TLS and secure cryptographic algorithms to ensure secure communications and data protection. Such features contribute to secure application development by mitigating risks from malicious threats and ensuring data integrity, making it a reliable choice for sensitive applications .

Different .NET Framework versions introduce enhancements that improve application development. For instance, version 3.5 introduced LINQ and AJAX-enabled Websites, enhancing data querying and web application responsiveness. Version 4 included support for parallel computing and the Dynamic Language Runtime, aiding in performance and language flexibility. Version 4.5 improved language support for C# and F#, making coding more efficient and reliable. Later versions like 4.7 included support for TLS and enhanced cryptography, crucial for secure communications .

.NET Framework supports multi-language development by providing a platform that supports several programming languages, such as C#, F#, and VB.NET. This allows developers to choose a language suited to their skills and project needs while maintaining access to the same libraries and tools. This flexibility reduces dependency on a single language, promotes code reusability, and fosters a broader developer community. Multi-language support also enhances productivity as developers can leverage existing knowledge .

C# plays a crucial role in the .NET ecosystem as a modern, object-oriented programming language that is type-safe and cross-platform. Its integration with .NET Core allows it to run on Windows, Linux, and macOS, making it versatile for diverse development needs. C# is popular for its strong resemblance to other high-level languages like Java, easy learning curve, and robust feature set, including rich library support and high performance due to its compilation to Intermediate Language (IL) for execution on the CLR .

Advantages of using the .NET Framework for high-performance applications include productivity boosts from pre-built libraries and tools, enhanced security features, and strong community support that aids in problem-solving. However, disadvantages include potential performance limitations in scenarios requiring low-level hardware interaction or complex algorithms, as .NET's abstraction layer may not provide the fine-tuned control needed for such tasks. Additionally, the large footprint of the framework can be a constraint in environments with limited resources .

ASP.NET enhances web development through features like server-side processing, where applications are run on the server and results are sent to the client browser. This allows for efficient resource utilization and centralized control over application logic. ASP.NET also supports a wide range of controls, such as TextBox, Button, and HyperLink, enabling developers to quickly build interactive web applications. The integration with IIS for handling ASP.NET applications further simplifies deployment and management compared to traditional technologies .

You might also like