You are on page 1of 196

CONTENTS

Unit Contents Page No.

UNIT 1
1 1-16
The .Net Framework

Unit 2
2 17-68
Introduction to C #

Unit 3
3 69-103
Classes and Objects

Unit 4
4 104-133
Visual Studio IDE Features

Unit 5
5 134-161
ADO.Net

Unit 6
6 162-192
Managing Console I/O Operations

“Only for Private Circulation”


“Only for Private Circulation”
C# Programming

UNIT - I
NOTES
THE .NET FRAMEWORK

Learning Objectives
• To introduce students with Microsoft Dot net framework and its
components.
• To introduce students with roles of Just in Time Compiler.
• To introduce students with the concept of garbage collection, assemblies,
web services, COM etc.

1.1 Ov e r v ie w Of Mic r Os Of t DOt Ne t

Microsoft Dot Net (.Net) is one of the recent and advanced technologies
introduced by Microsoft Corporation. These days we use to connect to the
internet using a computer and remote computer responses through a web page.
A collection of such web pages is called as Web Sites. The Concept in Dot Net
is that these websites can integrate with other sites and services using Standard
Protocols like HTTP.
Microsoft Dot Net Platform comprises of four core components such as:
• Dot Net Building Block Services such as file storage, calendar called
Passport Dot Net.
• Dot Net Device Software, which will run on latest Internet Devices like
Mobile Phones.
• Dot Net user experience such as integrating this technology to user
created documents (integrates with XML). For example if you code XML
via a Dot Net Language like C#, it will automatically create XML
document.
• Dot Net infrastructure, which includes Net Framework (Common
Language Runtime & Dot Net Framework Class Libraries) Microsoft
Visual Studio Dot Net such as Visual Basic Dot Net, Visual C++ Dot Net
etc. Dot NET Enterprise Servers and Microsoft Windows Dot Net.
We can build robust, scalable, distributed applications with the help of Dot
Net and the part that helps us to develop these applications is called the Dot Net
Framework. The Dot Net Framework contains Common Language Runtime
(CLR) and the Dot Net Framework class libraries called as Base Class Libraries. 1
The .Net Framework
“Only for Private Circulation”
C# Programming All the Dot Net languages (like C-sharp, VisualBasic.Net, Visual C++.Net
etc) have the Dot Net Framework class libraries built into them. The Dot Net
class Libraries also supports File I/O, database operations, XML (Extensible
NOTES Markup Language) and SOAP (Simple Object Access Protocol). For example,
you can develop XML Pages by using C-sharp language.
When someone talks about Dot Net development, then you should
understand that they are talking about Dot Net Framework. It includes a Runtime
environment and a set of Class Libraries, which is being used by a new language
called C-sharp abbreviated as C# (more or less similar to C/C++/Java family of
languages) and all other Dot Net Languages. Simply speaking C-sharp is a new
language for developing custom solutions for Microsoft's Dot Net Platform.

1.2 iNt r ODu c t iON t O v is u a L s t u DiO DOt Ne t

Visual Studio .NET is a complete set of development tools for building ASP
Web applications, XML Web services, desktop applications, and mobile
applications. Visual Basic .NET, Visual C++ .NET, Visual C# .NET, and Visual
J# .NET all use the same integrated development environment (IDE), which
allows them to share tools and facilitates in the creation of mixed-language
solutions. In addition, these languages leverage the functionality of the .NET
Framework, which provides access to key technologies that simplify the
development of ASP Web applications and XML Web services.

1.2.1 visual J#
Visual J# is a development tool that developers who are familiar with the
Java-language syntax can use to build applications and services on the .NET
Framework. It integrates the Java-language syntax into the Visual Studio .NET
integrated development environment (IDE). Visual J# also supports most of the
functionality found in Visual J++ 6.0, including Microsoft Extensions. Visual J#
is not a tool for developing applications intended to run on a Java Virtual
Machine. Applications and services built with Visual J# will run only in the .NET
Framework.

1.2.2 s mart Device a pplications


The Visual Studio .NET integrated development environment now includes
tools for developing applications for smart devices, such as the Pocket PC. Using
the tools and the .NET Compact Framework, a subset of the .NET Framework,
you can create, build, debug, and deploy applications that run on the .NET
Compact Framework in personal digital assistants (PDAs), mobile phones, and
other resource-constrained devices.

2 The .Net Framework


“Only for Private Circulation”
1.2.3 a s P.Ne t Mobile Designer C# Programming
ASP.NET Mobile Designer extends ASP.NET and the .NET Framework,
allowing you to build Web applications for mobile phones, PDAs, and pagers.
This designer is integrated into the Visual Studio IDE. You can create mobile NOTES
Web applications, use the Mobile Designer to modify a mobile Web form, and
then build and run the application, all from within Visual Studio.

1.2.4 w eb f orms
Web Forms are an ASP.NET technology that you use to create
programmable Web pages. Web Forms render themselves as browser-compatible
HTML and script, which allows any browser on any platform to view the pages.
Using Web Forms, you create Web pages by dragging and dropping controls onto
the designer and then adding code, similar to the way that you create Visual Basic
forms.

1.2.5 w indows f orms


Windows Forms is the new platform for Microsoft Windows application
development, based on the .NET Framework. This framework provides a clear,
object-oriented, extensible set of classes that enables you to develop rich
Windows applications. Additionally, Windows Forms can act as the local user
interface in a multi-tier distributed solution.

1.2.6 XML w eb s ervices


XML Web services are applications that can receive requests and data using
XML over HTTP. XML Web services not tied to a particular component
technology or object-calling convention and can be accessed by any language,
component model, or operating system. In Visual Studio .NET, you can quickly
create and include XML Web services using Visual Basic, Visual C#, JScript,
Managed Extensions for C++, or ATL Server.

1.2.7 XML s upport


Extensible Markup Language (XML) provides a method for describing
structured data. XML is a subset of SGML, which is optimized for delivery over
the Web. The World Wide Web Consortium (W3C) defines XML standards so
that structured data will be uniform and independent of applications. Visual
Studio .NET fully supports XML, providing the XML Designer to make it easier
to edit XML and create XML schemas.

1.3 iNt r ODu c t iON t O DOt Ne t (.Ne t ) f r a Me w Or k

The .NET Framework is a software framework developed by Microsoft


that runs primarily on Microsoft Windows. It includes a large library and provides
The .Net Framework 3

“Only for Private Circulation”


C# Programming language interoperability (each language can use code written in other languages)
across several programming languages. Programs written for the .NET
Framework execute in a software environment (as contrasted to hardware
NOTES environment), known as the Common Language Runtime (CLR), an application
virtual machine that provides services such as security, memory management,
and exception handling. The class library and the CLR together constitute the
.NET Framework.
The .NET Framework's Base Class Library provides user interface, data
access, database connectivity, cryptography, web application development,
numeric algorithms, and network communications. Programmers produce
software by combining their own source code with the .NET Framework and
other libraries. Microsoft also produces an integrated development environment
largely for .NET software called Visual Studio.
The .NET Framework is the next iteration of Microsoft's platform for
developing component-based software. It provides fundamental advances in
runtime services for application software. It also supports development of
applications that can be free of dependencies on hardware, operating system, and
language compiler.

Fig 1.1: Dot Net Framework Architecture


4 The .Net Framework
“Only for Private Circulation”
1.3.1 c ommon Language r untime (c Lr ) C# Programming
The .NET Framework provides a run-time environment called the common
language runtime, which runs the code and provides services that make the
development process easier. It has Just in Compiler (JIT) who is heart of heart of NOTES
dot net framework responsible for all the important tasks carried under .net
framework.
Compilers and tools expose the common language runtime's functionality
and enable you to write code that benefits from this managed execution
environment. Code that you develop with a language compiler that targets the
runtime is called managed code; it benefits from features such as cross-language
integration, cross-language exception handling, enhanced security, versioning
and deployment support, a simplified model for component interaction, and
debugging and profiling services.
MSIL (Microsoft Intermediate Language)
It is language independent code. When you compile code that uses the .NET
Framework library, you do not immediately create operating system - specific
native code.
Instead, you compile your code into Microsoft Intermediate Language
(MSIL) code. The MSIL code is not specific to any operating system or to any
language.

JIT (Just-in-Time) Compiler


Just - in - Time (JIT) compiler, this compiles MSIL into native code that is
specific to the operating system and machine architecture being targeted. Only
at this point can the operating system execute the application. The just - in - time
part of the name reflects the fact that MSIL code is only compiled as, and when,
it is needed.
In the past, it was often necessary to compile your code into several
applications, each of which targeted a specific operating system and CPU
architecture. Often, this was a form of optimization.
This is now unnecessary, because JIT compilers (as their name suggests)
use MSIL code, which is independent of the machine, operating system, and
CPU. Several JIT compilers exist, each targeting a different architecture, and the
appropriate one will be used to create the native code required.
The beauty of all this is that it requires a lot less work on your part - in fact,
you can forget about system - dependent details and concentrate on the more
interesting functionality of your code.

Jit are of three types


1. Pre JIT
2. Econo JIT
3. Normal JIT The .Net Framework 5

“Only for Private Circulation”


C# Programming 1 Pre JIT
It converts all the code in executable code and it is slow

NOTES 2 Econo JIT


It will convert the called executable code only. However, it will convert
code every time when a code is called again.

3 Normal JIT
It will only convert the called code and will store in cache so that it
will not require converting code again. Normal JIT is fast.
Programmatically, when our program needs memory, CLR allocates
the memory for scope and de-allocates the memory if the scope is
completed.
Language Compilers (e.g. C#, VB.Net, J#) will convert the Code/Program
to Microsoft Intermediate Language (MSIL) intern this will be converted to
Native Code by CLR. See the below Fig 1.2.

Fig 1.2: Common Language Runtime (CLR)


• Features of Common Language Runtime (CLR)
• Performance improvements.
• The ability to easily use components developed in other languages.
• Extensible types provided by a class library.
• Language features such as inheritance, interfaces, and overloading for
object-oriented programming.
• Support for explicit free threading that allows creation of multithreaded,
scalable applications.
• Support for structured exception handling.
6 The .Net Framework
“Only for Private Circulation”
• Support for custom attributes. C# Programming
• Garbage collection.
• Use of delegates instead of function pointers for increased type safety
NOTES
and security

1.3.2 .Net f ramework c lass Library (f c L)


Framework Class Library (FCL) is also called as Base Class Library and it
is common for all types of applications i.e. the way you access the Library
Classes and Methods in VB.NET will be the same in C#, and it is common for
all other languages in .NET.
The following are different types of applications that can make use of .net
class library.
1. Windows Application.
2. Console Application
3. Web Application.
4. XML Web Services.
5. Windows Services.
Generally, developers just need to import the BCL in their language code
and use its predefined methods and properties to implement common and
complex functions like reading and writing to file, graphic rendering, database
interaction, and XML document manipulation

1.3.3 c ommon Language s pecification (c Ls )


To fully interact with other objects regardless of the language they were
implemented in, objects must expose to callers only those features that are
common to all the languages they must interoperate with. For this reason, the
Common Language Specification (CLS), which is a set of basic language features
needed by many applications, has been defined. The CLS rules define a subset
of the Common Type System; that is, all the rules that apply to the common type
system apply to the CLS, except where stricter rules are defined in the CLS. The
CLS helps enhance and ensure language interoperability by defining a set of
features that developer can rely on to be available in a wide variety of languages.
The CLS also establishes requirements for CLS compliance; these help you
determine whether your managed code conforms to the CLS and to what extent
a given tool supports the development of managed code that uses CLS features.
If your component uses only CLS features in the API that it exposes to other
code (including derived classes), the component is guaranteed to be accessible
from any programming language that supports the CLS. Components that adhere
to the CLS rules and use only the features included in the CLS are said to be
CLS-compliant components.

The .Net Framework 7

“Only for Private Circulation”


C# Programming Most of the members defined by types in the .NET Framework Class
Library are CLS-compliant. However, some types in the class library have one
or more members that are not CLS-compliant. These members enable support
NOTES for language features that are not in the CLS. The types and members that are
not CLS-compliant are identified as such in the reference documentation, and in
all cases a CLS-compliant alternative is available. For more information about
the types in the .NET Framework class library, see the .NET Framework Class
Library.
The CLS was designed to be large enough to include the language constructs
that are commonly needed by developers, yet small enough that most languages
are able to support it. In addition, any language constructs that makes it
impossible to rapidly verify the type safety of code was excluded from the CLS
so that all CLS-compliant languages can produce verifiable code if they choose
to do so. For more information about verification of type safety, see Managed
Execution Process.

1.3.4 c ommon t ype s ystem (c t s )


The common type system defines how types are declared, used, and
managed in the common language runtime, and is also an important part of the
runtime's support for cross-language integration. The common type system
performs the following functions:
• Establishes a framework that helps enable cross-language integration,
type safety, and high-performance code execution.
• Provides an object-oriented model that supports the complete
implementation of many programming languages.
• Defines rules that languages must follow, which helps ensure that objects
written in different languages can interact with each other.
• Provides a library that contains the primitive data types (such as Boolean,
Byte, Char, Int32, and UInt64) used in application development
All types in the .NET Framework are either value types or reference types.

value t ypes
Value types are data types whose objects are represented by the object's
actual value. If an instance of a value type is assigned to a variable, that variable
is given a fresh copy of the value.

r eference t ypes
Reference types are data types whose objects are represented by a reference
(similar to a pointer) to the object's actual value. If a reference type is assigned
to a variable, that variable references (points to) the original value. No copy is
made.

8 The .Net Framework


“Only for Private Circulation”
The common type system in the .NET Framework supports the following C# Programming
five categories of types:
• Classes
NOTES
• Structures
• Enumerations
• Interfaces

1.4 Ga r b a Ge c OLLe c t iON (Gc )

One of the most important features of managed code is the concept of


garbage collection. Garbage Collection makes automatic memory management
possible in .NET Framework. When a class object is created at runtime, certain
memory space is allocated to it in the heap memory. However, after all the actions
related to the object are completed in the program, the memory space allocated
to it is a waste, as it cannot be used. In this case, garbage collection is very useful
as it automatically releases the memory space after it is no longer required.
Garbage collection will always work on Managed Heap and internally it
has an Engine, which is known as the Optimization Engine.
Garbage Collection occurs if at least one of multiple conditions is
satisfied. These conditions are given as follows:
• If the system has low physical memory, then garbage collection is
necessary.
• If the memory allocated to various objects in the heap memory exceeds
a pre-set threshold, then garbage collection occurs.
• If the GC.Collect method is called, then garbage collection occurs.
However, this method is only called under unusual situations as normally
garbage collector runs automatically.

t here are mainly three phases in garbage collection


Marking Phase
A list of all the live objects is created during the marking phase. This
is done by following the references from all the root objects. All of the
objects that are not on the list of live objects are potentially deleted
from the heap memory.

Relocating Phase
The references of all the objects that were on the list of all the live
objects are updated in the relocating phase so that they point to the new
location where the objects will be relocated to in the compacting phase.
The .Net Framework 9

“Only for Private Circulation”


C# Programming Compacting Phase
The heap gets compacted in the compacting phase as the space
occupied by the dead objects is released and the live objects remaining
NOTES are moved. All the live objects that remain after the garbage collection
are moved towards the older end of the heap memory in their original
order.

1.5 a s s e Mb Lie s

An assembly is a single deployable unit, which contains all the information


about the implementation of classes, structure and interfaces. The executable
code is stored in Assemblies. The assemblies are the self-describing unit and the
programs in .Net are constructed through these assemblies.
The .exe and .dll files are the kinds of assembly. They store all information
about itself and it is known as assembly metadata, which includes name and the
version number of the assembly. Namespaces are also stored in assemblies.
Assemblies can be private or shared where private assembly is accessible by
single application whereas shared assembly is shared by multiple application.

in .Net there are three types of a ssemblies are available

1.5.1 Private a ssemblies


Private Assemblies are designed to be used by one application and must
reside in that application's directory or subdirectory. It is created when we
compile our code using compiler. In this, it is stored on the hard disk in the form
of portable executable file.

1.5.2 s hared a ssemblies


Microsoft offers the shared assembly for those components that must be
distributed. It centered around two principles. Firstly, called side-by-side
execution, allows the CLR to house multiple versions of the same component on
a single machine. Secondly, termed binding, ensures that clients obtain the
version of the component they expect. It is created during run time and it occupies
memory only

1.5.3 s atellite a ssembly


A satellite Assembly is defined as an assembly with resources only, no
executable code.
Assembly can be stored in single and or multiple files. In single file the
MSIL code, metadata, resources and assembly metadata are all stored in single
file. In multiple file assembly, they are separated in different file. Assembly
contains the four elements:
10 The .Net Framework
“Only for Private Circulation”
• Assembly Manifest – It contains the assembly metadata, which describes C# Programming
the assembly and its contents.
• Source Code – It is compiled into Microsoft Intermediate Language
(MSIL). NOTES

• Type Metadata – It defines all types, properties and methods.


• Resources – Icons, images, text strings and other resources.

1.6 w e b s e r v ic e s

A web service is any piece of software that makes itself available over the
internet and uses a standardized XML messaging system. XML is used to encode
all communications to a web service. For example, a client invokes a web service
by sending an XML message, and then waits for a corresponding XML response.
As all communication is in XML, web services are not tied to any one operating
system or programming language—Java can talk with Perl; Windows
applications can talk with UNIX applications.
Web services are self-contained, modular, distributed, dynamic applications
that can be described, published, located, or invoked over the network to create
products, processes, and supply chains. These applications can be local,
distributed, or web-based. Web services are built on top of open standards such
as TCP/IP, HTTP, Java, HTML, and XML.

1.6.1 c omponents of w eb s ervices


The basic web services platform is XML + HTTP. All the standard web
services work using the following components −

1.6.1.1 s Oa P (s imple Object a ccess Protocol)


SOAP is an XML-based protocol for exchanging information between
computers.
• SOAP is a communication protocol.
• SOAP is for communication between applications.
• SOAP is a format for sending messages.
• SOAP is designed to communicate via Internet.
• SOAP is platform independent.
• SOAP is language independent.
• SOAP is simple and extensible.
• SOAP allows you to get around firewalls.
• SOAP will be developed as a W3C standard
The .Net Framework 11

“Only for Private Circulation”


C# Programming 1.6.1.2 u DDi (u niversal Description, Discovery and integration)
UDDI is an XML-based standard for describing, publishing, and finding
web services.
NOTES
• UDDI stands for Universal Description, Discovery, and Integration.
• UDDI is a specification for a distributed registry of web services.
• UDDI is platform independent, open framework.
• UDDI can communicate via SOAP, CORBA, and Java RMI Protocol.
• UDDI uses WSDL to describe interfaces to web services.
• UDDI is seen with SOAP and WSDL as one of the three foundation
standards of web services.
• UDDI is an open industry initiative enabling businesses to discover each
other and define how they interact over the Internet.

1.6.1.3 w s DL (w eb s ervices Description Language)


WSDL is an XML-based language for describing web services and how to
access them.
• WSDL stands for Web Services Description Language.
• WSDL was developed jointly by Microsoft and IBM.
• WSDL is an XML based protocol for information exchange in
decentralized and distributed environments.
• WSDL is the standard format for describing a web service.
• WSDL definition describes how to access a web service and what
operations it will perform.
• WSDL is a language for describing how to interface with XML-based
services.
• WSDL is an integral part of UDDI, an XML-based worldwide business
registry.
• WSDL is the language that UDDI uses.

1.6.2 w orking of w eb s ervice


A web service enables communication among various applications by using
open standards such as HTML, XML, WSDL, and SOAP. A web service takes
the help of −
• XML to tag the data
• SOAP to transfer a message
• WSDL to describe the availability of service

12

“Only for Private Circulation”


You can use C# to build new web services on Windows that can be invoked C# Programming
from your web application that is based on JavaServer Pages (JSP) and runs on
Linux
NOTES
1.6.3 c haracteristics of w eb s ervices
Web services have the following special behavioral characteristics −

1.6.3.1 XML-b ased


Web services use XML at data representation and data transportation layers.
Using XML eliminates any networking, operating system, or platform binding.
Web services based applications are highly interoperable at their core level.

1.6.3.2 Loosely c oupled


A consumer of a web service is not tied to that web service directly. The
web service interface can change over time without compromising the client's
ability to interact with the service. A tightly coupled system implies that the client
and server logic are closely tied to one another, implying that if one interface
changes, the other must be updated. Adopting a loosely coupled architecture tends
to make software systems more manageable and allows simpler integration
between different systems.

1.6.3.3 c oarse-Grained
Object-oriented technologies such as C# expose their services through
individual methods. An individual method is too fine an operation to provide any
useful capability at a corporate level. Building a C# program from scratch
requires the creation of several fine-grained methods that are then composed into
a coarse-grained service that is consumed by either a client or another service.

1.6.3.4 a bility to be s ynchronous or a synchronous


Synchronicity refers to the binding of the client to the execution of the
service. In synchronous invocations, the client blocks and waits for the service
to complete its operation before continuing. Asynchronous operations allow a
client to invoke a service and then execute other functions.
Asynchronous clients retrieve their result at a later point in time, while
synchronous clients receive their result when the service has completed.
Asynchronous capability is a key factor in enabling loosely coupled systems.

1.6.3.5 s upports r emote Procedure c alls (r Pc s)


Web services allow clients to invoke procedures, functions, and methods
on remote objects using an XML-based protocol. Remote procedures expose
input and output parameters that a web service must support. Component
development through Enterprise JavaBeans (EJBs) and .NET Components has
increasingly become a part of architectures and enterprise deployments over the
past couple of years. Both technologies are distributed and accessible through a
variety of RPC mechanisms. The .Net Framework 13

“Only for Private Circulation”


C# Programming A web service supports RPC by providing services of its own, equivalent
to those of a traditional component, or by translating incoming invocations into
an invocation of an EJB or a .NET component.
NOTES
1.6.3.6 s upports Document e xchange
One of the key advantages of XML is its generic way of representing not
only data, but also complex documents. These documents can be as simple as
representing a current address, or they can be as complex as representing an entire
book or Request for Quotation (RFQ). Web services support the transparent
exchange of documents to facilitate business integration.

1.7 c OMPONe Nt Ob Je c t MODe L (c OM)

Component Object Model (COM) is a method to facilitate communication


between different applications and languages. COM is used by the developers to
create re-usable software components, link components together to build
applications, and take advantage of Windows services. COM objects can be
created with a variety of programming languages. Object-oriented languages,
such as C#, provide programming mechanisms that simplify the implementation
of COM objects. The family of COM technologies includes COM+, Distributed
COM (DCOM) and ActiveX® Controls.
COM was the first programming model that provided component based
approach to software development. This component based approach of COM
allowed us to develop small, logical reusable and standalone modules that
integrates into a single application. But these components could not be displayed
over a network. Therefore, these drawbacks produce another model that is
DCOM (Distributed COM).
The DCOM programming model enables you to display COM components
over a network and easily distribute applications across platforms. DCOM
components also help in two-tier client/server applications. These models also
have some drawbacks that help the development of the COM+ approach.

1.7.1. c reating c OM c omponents in .Ne t


The following steps explain the way to create the COM server in C#:
1. Create a new Class Library project.
2. Create a new interface, say IManagedInterface, and declare the
methods required. Then provide the Guid (this is the IID) for the
interface using the GuidAttribute defined in
System.Runtime.InteropServices. The Guid can be created using the
Guidgen.exe. [Guid("3B515E51-0860-48ae-B49C-05DF356CDF4
B")]
14 The .Net Framework
“Only for Private Circulation”
3. Define a class that implements this interface. Again, provide the Guid C# Programming
(this is the CLSID) for this class also.
4. Mark the assembly as ComVisible. For this go to AssemblyInfo.cs file
and add the following statement [assembly: ComVisible (true)]. This NOTES
gives the accessibility of all types within the assembly to COM.
5. Build the project. This will generate an assembly in the output path.
Now register the assembly using regasm.exe (a tool provided with the
.NET Framework) - regasm \bin\debug\ComInDotNet.dll
\tlb:ComInDotNet.tlb this will create a TLB file after registration.
6. Alternatively this can be done in the Project properties --> Build -->
check the Register for COM interop.
After doing this the COM server becomes ready. Now a client has to be
created. It can be in any language. If the client is .NET, just add the above created
COM assembly as a reference and use it.

1.7.2 How to c all c OM c omponents from .Ne t ?


COM components and .NET Components have a different internal
architecture. For both of them to communicate with each other, the inter-
operation feature is required, this feature is called interoperability. Enterprises
that have written their business solutions using the old native COM technology
need a way for re-using these components in the new .NET environment.
.NET components communicate with COM using RCW (Runtime Callable
Wrapper)
Here RCW is Runtime Callable Wrappers; The Common Language
Runtime (CLR) exposes COM objects through a proxy called the Runtime
Callable Wrapper (RCW). Although the RCW appears to be an ordinary object
to .NET clients, its primary function is to marshal calls between a .NET client
and a COM object.

t o use a c OM component
• Right click the Project and click on Add References.
• Select the COM tab
• And at last select COM component

e xercise
Q.1 Write the overview of Microsoft Dot Net.
Q.2 Describe Microsoft Visual Studio and its Applications.
Q.3 What is Dot Net Framework? Draw dot net Framework architecture.
Q.4 Write various components of dot net framework architecture.

The .Net Framework 15

“Only for Private Circulation”


C# Programming Q.5 Write short notes on
a) CLR
b) CLS
NOTES
c) CTS
d) FCL
Q.6 What is MSIL code? Write various roles of JIT compiler.
Q.7 What is Garbage Collection? Explain.
Q.8 What is Assembly? State and explain different types of assemblies in
.Net.
Q.9 What is Web Service? Explain different types of web service
components.
Q.10 Write working of web services along with their characteristics.
Q.11 Explain in detail Component Object Model (COM) in .Net.

*****

16 The .Net Framework


“Only for Private Circulation”
C# Programming

UNIT - II
NOTES
INTRODUCTION TO C #

Learning Objectives
• To introduce students with evolution of C# programming language along
with characteristics.
• To familiarize students with user and program interface of Microsoft
Visual Studio
• To introduce learners with implementation of Object Oriented
Programming in C#.

2.1 e v OLu t iON Of c #

C# is developed by Anders Hejlsberg and his team during the development


of .Net Framework.
C# has evolved much since its first release in 2002, which was introduced
with .NET Framework 1.0. The following table lists important features
introduced in each version of C#:
Table 2.1: Evolution of C#

Introduction to C # 17

“Only for Private Circulation”


C# Programming

NOTES

18 Introduction to C #
“Only for Private Circulation”
C# Programming

2.2 c Ha r a c t e r is t ic s Of c #
NOTES
C# is object oriented programming language. It provides a lot of
characteristics that are given below.
1. Simple
C# is a simple language in the sense that it provides structured
approach (to break the problem into parts), rich set of library functions,
data types etc

2. Modern programming language


C# programming is based upon the current trend and it is very
powerful and simple for building scalable, interoperable and robust
applications.

3. Object oriented
C# is object oriented programming language. OOPs makes
development and maintenance easier where as in Procedure-oriented
programming language it is not easy to manage if code grows as
project size grow

4. Type safe
C# type safe code can only access the memory location that it has
permission to execute. Therefore, it improves a security of the
program.

5. Interoperability
Interoperability process enables the C# programs to do almost anything
that a native C++ application can do.
6. Scalable and Updateable
C# is automatic scalable and updateable programming language. For
updating our application, we delete the old files and update them with
new ones.

7. Component oriented
C# is component oriented programming language. It is the
predominant software development methodology used to develop
more robust and highly scalable applications.

8. Structured programming language


C# is a structured programming language in the sense that we can
break the program into parts using functions. Therefore, it is easy to
understand and modify. Introduction to C # 19

“Only for Private Circulation”


C# Programming 9. Rich Library
C# provides many inbuilt functions that makes the development fast.

NOTES 10. Fast speed


The compilation and execution time of C# language is fast.

2.3 a PPLic at iONs Of c #

The C# language can be used to build all kinds of applications. Not only
Windows or Web applications but also C# can be used to build mobile, Windows
Store, and Enterprise applications. C# can also be used within the SQL Server
database to build reports, jobs and modules to do the backend work.
Following is a list of types of applications C# can develop.
1. Windows client applications
2. Windows libraries and components
3. Windows services
4. Web applications
5. Web services and Web API
6. Native iOS and Android mobile apps
7. Backend services
8. Azure cloud applications and services
9. Backend database using ML/Data tools
10. Interoperability software such as Office, SharePoint, SQL Server and
so on.
11. Artificial Intelligence and Machine learning
12. Blockchains and distributed ledger technology including
cryptocurrency
13. Internet of Things (IoT) devices
14. Gaming consoles and gaming systems
15. Video games

2.4 Dif f e r e Nc e b e t w e e N c ++ a ND c #

C++ is a statically typed, multiparadigm, and object-oriented programming


20
language. In beginning, C++ was termed as C with classes. It is developed by
Introduction to C #
“Only for Private Circulation”
Bjarne Stroustrup at AT & T Bell Laboratories. C# is a general-purpose, modern C# Programming
and object-oriented programming language pronounced as “C sharp”. It was
developed by Microsoft led by Anders Hejlsberg and his team.
NOTES
f ollowing are some major differences between c ++ and c #
Table 2.2: Major Differences between C++ and C#

Introduction to C # 21

“Only for Private Circulation”


C# Programming

2.5 Dif f e r e Nc e b e t w e e N Java a ND c #


NOTES
Java is a general-purpose computer programming language that is
concurrent, class-based, object-oriented etc. Java applications are typically
compiled to bytecode that can run on any Java virtual machine (JVM) regardless
of computer architecture. C# is a general-purpose, modern and object-oriented
programming language pronounced as “C sharp”. It was developed by Microsoft
led by Anders Hejlsberg and his team.

f ollowing are some major differences between c # and Java


Table 2.3: Major Differences between C# and Java

22 Introduction to C #
“Only for Private Circulation”
C# Programming

2.6 iNt r ODu c t iON t O c # e Nv ir ONMe Nt


NOTES
C# is an elegant and type-safe object-oriented language that enables
developers to build a variety of secure and robust applications that run on the
.NET Framework. You can use C# to create Windows client applications, XML
Web services, distributed components, client-server applications, database
applications, and much, much more. Visual C# provides an advanced code editor,
convenient user interface designers, integrated debugger, and many other tools
to make it easier to develop applications based on the C# language and the .NET
Framework.
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# 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.

2.6.1 .Net s trategy


The Microsoft .NET strategy is a marketing plan that Microsoft followed
in the early 2000s. Steve Ballmer described it as the company's "most ambitious
undertaking since Internet Strategy Day in 1995". In support of this strategy,
between 2000 and 2002, Microsoft released ".NET" branded updates to its works,
including Visual Studio .NET, Visual Basic .NET, .NET Passport, .NET My
Services, .NET Framework, ASP.NET and ADO.NET. A Windows .NET Server
was also announced. Microsoft had plans to include Microsoft SQL Server,
Microsoft Exchange Server and MSN into this strategy.
By 2003, however, the .NET strategy had dwindled into a failed branding
campaign because the brand had failed to articulate what Microsoft had in mind
in the first place. As such, Windows .NET Server was released under the title of
Introduction to C # 23

“Only for Private Circulation”


C# Programming Windows Server 2003. Since then, Visual Studio and .NET Passport have been
stripped of ".NET" in their brandings. However, Microsoft and the rest of the
computing industry use ".NET" to indicate close association with .NET
NOTES Framework, e.g. .NET Compiler Platform, .NET Foundation and .NET Reflector.

2.6.2 t he Origins of the .Ne t t echnology


Microsoft. NET is one of the latest and new technologies introduced by
Microsoft Corporation. Nowadays we use to connect to the internet using a
computer and a remote computer responses via a web page and a collection of
web pages are called as Web Sites. The Concept in .NET is that these websites
can integrate with other sites and services using Standard Protocols like HTTP.
Microsoft .NET Platform comprises of four core components such as:
• NET Building Block Services such as file storage, calendar called
Passport. NET
• NET Device Software which will run on latest Internet Devices like
Mobile Phones.
• NET user experience such as integrating this technology to user created
documents (integrates with XML). For example if you code XML via a
.NET Language like C#, it will automatically create XML document.
• NET infrastructure which includes NET Framework (Common
Language Runtime & .NET Framework Class Libraries) Microsoft Visual
Studio.NET such as Visual Basic.NET ,Visual C++.NET etc NET
Enterprise Servers and Microsoft Windows. NET.
We can build robust, scalable, distributed applications with the help of .NET
and the part that helps us to develop these applications is called the .NET
Framework. The .NET Framework contains Common Language Runtime (CLR)
and the .NET Framework class libraries also called as Base Class Libraries.
.NET is a software framework which is designed and developed by
Microsoft. The first version of the .Net framework was 1.0 which came in the
year 2002. In easy words, it is a virtual machine for compiling and executing
programs written in different languages like C#, VB.Net etc. It is used to develop
Form-based applications, Web-based applications, and Web services. There is a
variety of programming languages available on the .Net platform, VB.Net and
C# being the most common ones. It is used to build applications for Windows,
phone, web, etc. It provides a lot of functionalities and also supports industry
standards.
.NET Framework supports more than 60 programming languages in which
11 programming languages are designed and developed by Microsoft. The
remaining Non-Microsoft Languages which are supported by .NET Framework
but not designed and developed by Microsoft 11 Programming Languages which
are designed and developed by Microsoft are:
24 Introduction to C #
“Only for Private Circulation”
• C#.NET C# Programming
• VB.NET
• C++.NET
NOTES
• J#.NET
• F#.NET
• JSCRIPT.NET
• WINDOWS POWERSHELL
• IRON RUBY
• IRON PYTHON
• C OMEGA
• ASML(Abstract State Machine Language)
The runtime which we discussed just now is also used by VisualStudio.NET.
Visual Studio.NET provides us with a visual environment to design and develop
.NET Applications. Every language in VisualStudio.NET uses this runtime to
execute its applications.
Release History of .NET Framework and its compatibility with the different
Windows version
Table 2.4: Release History of .NET Framework

Introduction to C # 25

“Only for Private Circulation”


C# Programming t he .Ne t f ramework
.NET is a software framework, which is designed and developed by
Microsoft. The first version of the .Net framework was 1.0, which came in the
NOTES year 2002. In easy words, it is a virtual machine for compiling and executing
programs written in different languages like C#, VB.Net etc.
It is used to develop Form-based applications, Web-based applications, and
Web services. There is a variety of programming languages available on the .Net
platform, VB.Net and C# being the most common ones. It is used to build
applications for Windows, phone, web, etc. It provides many functionalities and
supports industry standards.
.NET Framework supports 60+ programming languages from which
following 11 programming languages are designed and developed by Microsoft.
1. #.NET
2. VB.NET
3. C++.NET
4. J#.NET
5. F#.NET
6. JSCRIPT.NET
7. WINDOWS POWERSHELL
8. IRON RUBY
9. IRON PYTHON
10. C OMEGA
11. ASML(Abstract State Machine Language)

2.7 c OMMON La NGu a Ge r u Nt iMe (c Lr )

Common Language Runtime (CLR) is the basic and Virtual Machine


component of the .NET Framework. It a run-time environment that manages and
executes the code written in any .NET programming language. It helps in making
the development process easier by providing the various services such as
remoting, thread management, type-safety, memory management, robustness,
etc. Basically, it is responsible for managing the execution of .NET programs
regardless of any .NET programming language. It also helps in the management
of code, as code that targets the runtime is known as the Managed Code and code
doesn’t target to runtime is known as Unmanaged code.

26 Introduction to C #
“Only for Private Circulation”
2.7.1. f unctions of c ommon Language r untime (c Lr ) C# Programming
• It converts the program into native code.
• Handles Exceptions
NOTES
• 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.

2.8 f r a Me w Or k b a s e c La s s e s

It is a .NET Framework Class Library (FCL) is the collection of classes,


namespaces, interfaces and value types that are used for .NET applications. It is
the collection of reusable, object-oriented class libraries and methods, etc that
can be integrated with CLR. Also called the Assemblies.
It contains thousands of classes that supports the following functions.
• Base and user-defined data types
• Support for exceptions handling
• input/output and stream operations
• Communications with the underlying system
• Access to data
• Ability to create Windows-based GUI applications
• Ability to create web-client and server applications
• Support for creating web services

2.8.1 .Net f ramework c lass Library (f c L) Namespaces


.Net Framework Class Library (FCL) consist of thousands of namespaces.
Following are the commonly used namespaces that contains useful classes and
interfaces and defined in Framework Class Library.

Introduction to C # 27

“Only for Private Circulation”


C# Programming Table 2.5: Framework Class Library (FCL) Namespaces

NOTES

28 Introduction to C #
“Only for Private Circulation”
C# Programming

2.9 u s e r a ND Pr OGr a Ms iNt e r f a c e


NOTES
The .NET framework provides the following tools for manag1ng user and
application interfaces:
• Windows forms
• Web Forms
• Console Applications
• Web Services
These tools enable users to develop user-friendly desktop-based as well as
web-based applications using a wide variety of languages on the .NET platform.

2.9.1 w indows f orms


Windows forms (also called Win forms) are used to create GUI for Windows
desktop applications. The idea of Win forms has been borrowed from Windows
Foundation Classes (WFC), which were used for Visual J++. Win form provide
an integrated and unified way of developing GUI. It has a rich variety of
Windows controls and user interface support.
With Win Form we can make single user interface, and use it in VC++, VB,
C#. Using Visual Studio .NET simply design the GUI, by dragging the controls
on a form. Now you can use the same from in VB, VC++ or in C#. All this is
made possible because Visual Studio .NET used the System.Winforms
namespace to draw the GUI. Any language that has the appropriate CLS
compliance can use this form directly.

2.9.2 w eb f orms
Just as the Win Forms provide a unified way of developing GUI for desktop
applications, the Web Forms provide similar tool for web applications. Web forms
has been introduced in .NET as a part of ASP.NET. Web Forms are a form engine,
that provides a browser based user interface. In all, Web Forms are used to create
web applications.
With ASP.NET Microsoft has provided such presentation-business layer
separation-by introducing the concept of Web Forms:
1. ASP.NET Web Forms provide an easy and powerful way to build
dynamic Web User Interface Ul.
2. ASP.NET Web Forms pages can targat any browser client.
3. ASP.NET Web Forms provide syntex compatibility with existing ASP
pages.

Introduction to C # 29

“Only for Private Circulation”


C# Programming 4. ASP.NET server controls an easy way to encapsulate common
functionality.
5. ASP.NET ships with 45 built-in server controls. Developers can use
NOTES the control built by third parties.

2.9.3 c onsole a pplications


Console Applications are command line oriented applications that allow
user to read characters from the console, and write characters to the console.
Console applications are typically designed without graphical user interface
and are compiled in a stand-alone executable file.

2.9.4 w eb s ervices
Web services is an extension of ActiceX. Those programmers who have
used ASP and JSP both, know the apparent shortcomings of ASP. JSP has been
enriched with the concepts of Beans and Tags. ASP equavalent for Beans and
Tags was ActiceX Controls and ActiveX automation servers. Web Services
provides tools for developing Web applications.

2.10 v is u a L s t u DiO .Ne t

Visual Studio .NET is a Microsoft-integrated development environment


(IDE). It is used to develop computer programs, as well as websites, web apps,
web services and mobile apps. Visual Studio uses Microsoft software
development platforms such as Windows API, Windows Forms, Windows
Presentation Foundation, Windows Store and Microsoft Silverlight.
Visual Studio is used to write native code and managed code supported by
Microsoft Windows, Windows Mobile, Windows CE, .NET Framework, .NET
Compact Framework and Microsoft Silverlight. Visual Studio .NET’s code editor
supports IntelliSense and code refactoring, while the Visual Studio .NET
integrated debugger supports both source and machine-level debugging. Visual
Studio .NET includes other built-in tools, like a form designer, which is useful
when building GUI applications; a Web designer that creates dynamic Web pages;
a class designer that is used to create custom libraries, and a schema designer for
database support.

2.11 .Ne t La NGu a Ge s

Visual Studio supports different programming languages and allows the


code editor and debugger to support (to varying degrees) nearly any programming
language, provided a language-specific service exists. Built-in languages include
30 Introduction to C #
“Only for Private Circulation”
C, C++, C++/CLI, Visual Basic .NET, C#, F#, JavaScript, TypeScript, XML, C# Programming
XSLT, HTML, and CSS. Support for other languages such as Python, Ruby,
Node.js, and M among others is available via plug-ins.
Every .NET-compliant language supports the same data types, uses the same NOTES
.NET Framework classes, compiles to the same MSIL, and uses a single common
language runtime to manage execution. Because of this, every .NET-compliant
language is a first-class Microsoft .NET citizen.-Developers are free to choose
the best language for a particular component without losing any of the power
and freedom of the platform. In addition, components written in one language
can easily interoperate with components written in another language.
The following are the commonly used languages provided by the Microsoft:
• VC++
• VB.NET
• .C#
• J#
• JScript .NET

2.11.1 v c ++
Although Visual C++ (VC++), has undergone changes to incorporate .NET;
yet VC++ also maintains its status being a platform dependent programming.
Many new MFC classes have been added a programmer can choose between
using MFC and compiling the program into a platform specific executable file;
or using .NET framework classes and compile into platform independent MISL
file. A programmer can also specify (via directives) whenever he uses "unsafe"
(the code that by passes CLR, e.g. the use of pointers) code.

2.11.2 v b .Ne t
Out of ALL .NET languages, Visual Basic.NET (VB.NET) is one language
that has probably undergone into the most of changes. Now VB.NET may be
considered a complete Object- Oriented Language. Visual Basic .NET provides
substantial language innovations over previous versions of visual basic. Visual
Basic .NET supports inheritance, constructors, polymorphism, constructor
overloading, structured exceptions, stricter type checking, free threading, and
many other features.

2.11.3 c #
Microsoft has also developed a brand new programming language C# (C
Sharp). This language makes full use of .NET. It is a pure object oriented
language. C# is developed to make full use of all the intricacies of .NET. The
learning curve of C# for a Java programmer is minimal. Microsoft has also come
up with a The Microsoft Java Language Conversion Assistant-which is a tool
that automatically converts existing Java-language source code into C# for
Introduction to C # 31

“Only for Private Circulation”


C# Programming developers who want to move their existing applications to the Microsoft .NET
Framework.

NOTES 2.11.4 J#
Microsoft has also developed J# (Java Sharp). C# is similar to Java, but it
is not entirely' identical. It is for this reason that Microsoft has developed J# -
the syntax of J# is identical to Visual J++. Microsoft's growing legal battle with
Sun, over Visual J++ - forced Microsoft to discontinue Visual J++. So J# is
Microsoft's indirect continuation of Visual J++. It has been reported that porting
a medium sized Visual J++ project, entirely to J# takes only a few days of effort.

2.11.5 Js cript.Ne t
Jscript.NET is rewritten to be fully .NET aware. It includes support for
classes, inheritance, types and compilation, and it provides improved
performance and productivity features. JScript.NET is also integrated with visual
Studio .NET. You can take advantage of any .NET Framework class in JScript
.NET.

2.11.6 t hird-party languages


Microsoft encourages third party vendors to make use of Visual Studio. Net.
Third, party vendors can write compilers for different languages ~ that compile
the language to MSIL (Microsoft Intermediate Language). These vendors need
not develop their own development environment. They can easily use Visual
Studio.NET as an IDE for their .NET compliant language. A vendor has already
produced COBOL.NET that integrates with Visual Studio.NET and compiles
into MSIL. Theoretically, it would then be possible to come up with Java
compiler that compiles into MSIL, instead of Java Byte code; and uses CLR
instead of JVM. However, Microsoft has not pursued this due to possible legal
action by Sun.
Several third party languages are supporting the .NET platform. These
languages include APL, COBOL, Pascal, Eiffel, Haskell, ML, Oberon, Perl,
Python, Scheme and Smalltalk

2.12 c # Dat a t y Pe s

A data type specifies the type of data that a variable can store such as integer,
floating, character etc. The variables in C#, are categorized into the following
types −
• Value types
• Reference types
• Pointer types
32 Introduction to C #
“Only for Private Circulation”
2.12.1 value t ype C# Programming
Value type variables can be assigned a value directly. They are derived from
the class System.ValueType.
NOTES
The value types directly contain data. Some examples are int, char, and float,
which stores numbers, alphabets, and floating point numbers, respectively. When
you declare an int type, the system allocates memory to store the value. List of
value types is as follows:
Table 2.6: Value Types in C#

2.12.2 r eference t ype


The reference data types do not contain the actual data stored in a variable,
but they contain a reference to the variables. If the data is changed by one of the
variables, the other variable automatically reflects this change in value.
Using multiple variables, the reference types can refer to a memory location.
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, and string.

2.12.3 Object t ype


The Object Type is the ultimate base class for all data types in C# Common
Type System (CTS). Object is an alias for System.Object class. The object types Introduction to C # 33

“Only for Private Circulation”


C# Programming 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.
NOTES 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.

2.13 c # iDe Nt if ie r s

An identifier is a name used to identify a class, variable, function, or any


other user-defined item. The basic rules for naming classes in C# are as follows

1. A name must begin with a letter that could be followed by a sequence
of letters, digits (0 - 9) or underscore. The first character in an identifier
cannot be a digit.
2. It must not contain any embedded space or symbol such as? - + ! @ #
% ^ & * ( ) [ ] { } . ; : " ' / and \. However, an underscore ( _ ) can be
used.
3. It should not be a C# keyword.
The following are some examples of identifiers −
Class Names
class Calculation
class Demo

Valid Functions Names


void display()
void getMarks()

Variable Names
int a;
int marks;
int rank;
double res_marks;

2.14 c # va r ia b Le s

A variable is nothing but a name given to a storage area that our programs
can manipulate. Each variable in C# has a specific type, which determines the
size and layout of the variable's memory the range of values that can be stored
34 Introduction to C # within that memory and the set of operations that can be applied to the variable.

“Only for Private Circulation”


t he basic value types provided in c # can be categorized as C# Programming
Table 2.7: Basic Value Types

NOTES

2.14.1 r ules for defining variables


• A variable can have alphabets, digits and underscore.
• A variable name can start with alphabet and underscore only. It can't start
with digit.
• No white space is allowed within variable name.
• A variable name must not be any reserved word or keyword e.g. char,
float etc.

2.15 c # c ONs t a Nt s

The constants refer to fixed values that the program may not alter during
its execution. These fixed values are also called literals. Constants can be of any
of the basic data types like an integer constant, a floating constant, a character
constant, or a string literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values
cannot be modified after their definition.

2.15.1 integer Literals


An integer literal can be a decimal, or hexadecimal constant. A prefix
specifies the base or radix: 0x or 0X for hexadecimal, and there is no prefix id
for decimal.
An integer literal can also have a suffix that is a combination of U and L,
for unsigned and long, respectively. The suffix can be uppercase or lowercase
and can be in any order.
Here are some examples of integer literals:
212
215u
0xFeeL
Introduction to C # 35

“Only for Private Circulation”


C# Programming 2.15.2 f loating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part,
and an exponent part. You can represent floating point literals either in decimal
NOTES form or exponential form.
Here are some examples of floating-point literals −
3.14159
314159E-5F

2.15.3 c haracter c onstants


Character literals are enclosed in single quotes. For example, 'x' and can be
stored in a simple variable of char type. A character literal can be a plain character
(such as 'x'), an escape sequence (such as '\t'), or a universal character (such as
'\u02C0').
There are certain characters in C# when they are preceded by a backslash.
They have special meaning and they are used to represent like newline (\n) or
tab (\t). Here, is a list of some of such escape sequence codes:
Table 2.8: Escape Sequence Codes

2.15.4 s tring Literals


String literals or constants are enclosed in double quotes "" or with @"". A
string contains characters that are similar to character literals: plain characters,
escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and
separating the parts using whitespaces.
Here are some examples of string literals
36 Introduction to C # "hello, dear"

“Only for Private Circulation”


"hello, \ C# Programming
dear"
"hello, " "d" "ear"
@"hello dear" NOTES

2.16 c # s t at e Me Nt s

The actions of a program are expressed using statements. C# supports


several different kinds of statements, a number of which are defined in terms of
embedded statements.

2.16.1 b lock statement


A block permits multiple statements to be written in contexts where a single
statement is allowed. A block consists of a list of statements written between the
delimiters { and }.

2.16.2 Declaration statements


Declaration statements are used to declare local variables and constants.

2.16.3 e xpression statements


Expression statements are used to evaluate expressions. Expressions that
can be used as statements include method invocations, object allocations using
the new operator, assignments using = and the compound assignment operators,
increment and decrement operations using the ++ and -- operators and await
expressions.

2.16.4 s election s tatements


Selection statements are used to select one of a number of possible
statements for execution based on the value of some expression. This group
contains the if and switch statements.

2.16.5 iteration s tatements


Iteration statements are used to execute repeatedly an embedded statement.
This group contains the while, do, for, and foreach statements.

2.16.6 Jump s tatements


Jump statements are used to transfer control. This group contains the break,
continue, goto, throw, return, and yield statements.

2.16.7 t he try...catch s tatement


The try...catch statement is used to catch exceptions that occur during
execution of a block, and the try...finally statement is used to specify finalization
code that is always executed, whether an exception occurred or not. Introduction to C # 37

“Only for Private Circulation”


C# Programming 2.16.8 t he c hecked and u nchecked s tatements
The checked and unchecked statements are used to control the overflow-
checking context for integral-type arithmetic operations and conversions.
NOTES
2.16.9 t he Lock s tatement
The lock statement is used to obtain the mutual-exclusion lock for a given
object, execute a statement, and then release the lock.

2.16.10 t he using s tatement


The using statement is used to obtain a resource, execute a statement, and
then dispose of that resource.

2.17 Ob Je c t -Or ie Nt e D Pr OGr a MMiNG (OOP) c ONc e Pt

Object-oriented programming (OOP) is a programming paradigm based on


the concept of "objects", which may contain data, in the form of fields, often
known as attributes; and code, in the form of procedures, often known as
methods. For example, a person is an object which has certain properties such as
height, gender, age, etc. It also has certain methods such as move, talk, and so
on.

Object
This is the basic unit of object-oriented programming. That is both data and
function that operate on data are bundled as a unit called an object.

c lass
When you define a class, you define a blueprint for an object. This doesn't
actually define any data, but it does define what the class name means, that is,
what an object of the class will consist of and what operations can be performed
on such an object.
OOP has four basic concepts on which it is totally based. Let's have a
look at them individually −
• Abstraction − It refers to, providing only essential information to the
outside world and hiding their background details. For example, a web
server hides how it processes data it receives, the end user just hits the
endpoints and gets the data back.
• Encapsulation − Encapsulation is a process of binding data members
(variables, properties) and member functions (methods) into a single unit.
It is also a way of restricting access to certain properties or component.
The best example for encapsulation is a class.

38 Introduction to C #
“Only for Private Circulation”
• Inheritance − The ability to create a new class from an existing class is C# Programming
called Inheritance. Using inheritance, we can create a Child class from a
Parent class such that it inherits the properties and methods of the parent
class and can have its own additional properties and methods. For NOTES
example, if we have a class Vehicle that has properties like Color, Price,
etc, we can create 2 classes like Bike and Car from it that have those 2
properties and additional properties that are specialized for them like a
car has numberOfWindows while a bike cannot. Same is applicable to
methods.
• Polymorphism − The word polymorphism means having many forms.
Typically, polymorphism occurs when there is a hierarchy of classes and
they are related by inheritance. C++ polymorphism means that a call to
a member function will cause a different function to be executed
depending on the type of object that invokes the function.

2.18 c # a r r ay

Like other programming languages, array in C# is a group of similar types


of elements that have contiguous memory location. In C#, array is an object of
base type System.Array. In C#, array index starts from 0. We can store only fixed
set of elements in C# array. All arrays consist of contiguous memory locations.
The lowest address corresponds to the first element and the highest address to
the last element.

c # a rray t ypes
There are 3 types of arrays in C# programming:
2.18.1 Single Dimensional Array
2.18.2 Multidimensional Array
2.18.3 Jagged Array

2.18.1. s ingle Dimensional a rray


Single dimensional array in C# is the simplest type of array that contains
only one row for storing data. It has single set of square bracket (“[ ]”).

2.18.1.1 Declaring s ingle Dimensional a rray


To declare an array in C#, you can use the following 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. Introduction to C # 39

“Only for Private Circulation”


C# Programming For example,
double[] balance;

NOTES 2.18.1.2 initializing s ingle Dimensional a rray


Declaring an array does not initialize the array in the memory. When the
array variable is initialized, you can assign values to the array.
Array is a reference type, so you need to use the new keyword to create an
instance of the array. For example,
double[] balance = new double[10];

2.18.1.3 a ssigning values to s ingle Dimensional a rray


You can assign values to individual array elements, by using the index
number, like −
double[] balance = new double[10];
balance[0] = 4500.0;
You can assign values to the array at the time of declaration, as shown −
double[] balance = { 2340.0, 4523.69, 3421.0};
You can also create and initialize an array, as shown −
int [] marks = new int[5] { 99, 98, 92, 97, 95};
You may also omit the size of the array, as shown −
int [] marks = new int[] { 99, 98, 92, 97, 95};
You can copy an array variable into another target array variable. In such
case, both the target and source point to the same memory location −
int [] marks = new int[] { 99, 98, 92, 97, 95};
int[] score = marks;
When you 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.

2.18.1.4 a ccessing s ingle Dimensional a rray e lements


An element is accessed by indexing the array name. This is done by placing
the index of the element within square brackets after the name of the array. For
example,
double salary = balance[9];
The following example, demonstrates the above-mentioned concepts
declaration, assignment, and accessing arrays –
Example of Single Dimensional Array:
40 Introduction to C # using System;

“Only for Private Circulation”


namespace ArrayApplication { C# Programming
class MyArray {
static void Main(string[] args) {
NOTES
int [] n = new int[10]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n */
for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100;
}
/* output each array element's value */
for (j = 0; j < 10; j++ ) {
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}
Console.ReadKey();
}
}
}

Output
When the above code is compiled and executed, it produces the following
result –
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

2.18.2 Multidimensional a rray


The multidimensional array is also known as rectangular arrays in C#. It
can be two dimensional or three dimensional. The data is stored in tabular form
Introduction to C # 41

“Only for Private Circulation”


C# Programming (row * column) which is also known as matrix. To create multidimensional array,
we need to use comma inside the square brackets.
You can declare a 2-dimensional array of strings as
NOTES
string [,] names;
or, a 3-dimensional array of int variables as
int [ , , ] m;

2.18.2.1 t wo-Dimensional a rrays


The simplest form of the multidimensional array is the 2-dimensional array.
A 2-dimensional array is a list of one-dimensional arrays. A 2-dimensional array
can be thought of as a table, which has x number of rows and y number of
columns.
Multidimensional arrays may be initialized by specifying bracketed values
for each row. The Following array is with 3 rows and each row has 4 columns.
int [,] a = new int [3,4]
{
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
An element in 2-dimensional array is accessed by using the subscripts. That
is, row index and column index of the array. For example,
int val = a[2,3];
Example of multidimensional array which initializes array at the time of
declaration
using System;
public class MultiArrayExample
{
public static void Main(string[] args)
{
int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
Console.Write(arr[i,j]+" ");
}
42 Introduction to C #
“Only for Private Circulation”
Console.WriteLine(); C# Programming
}
}
NOTES
}

Output
When the above code is compiled and executed, it produces the following
result
1 2 3
4 5 6
7 8 9

2.18.3 Jagged a rray


Jagged array is also known as "array of arrays" because its elements are
arrays. The element size of jagged array can be different.

2.18.3.1 Declaration of Jagged array


Let's see an example to declare jagged array that has two elements.
int[][] arr = new int[2][];

2.18.3.2 initialization of Jagged array


Let's see an example to initialize jagged array. The size of elements can be
different.
arr[0] = new int[4];
arr[1] = new int[6];

2.18.3.3 initialization and filling elements in Jagged array


arr[0] = new int[4] { 11, 21, 56, 78 };
arr[1] = new int[6] { 42, 61, 37, 41, 59, 63 };
Here, size of elements in jagged array is optional.
Example of jagged array in C# which declares, initializes and traverse
jagged arrays.
public class JaggedArrayTest
{
public static void Main()
{
int[][] arr = new int[2][];// Declare the array

Introduction to C # 43

“Only for Private Circulation”


C# Programming arr[0] = new int[] { 11, 21, 56, 78 };// Initialize the array
arr[1] = new int[] { 42, 61, 37, 41, 59, 63 };
// Traverse array elements
NOTES
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < arr[i].Length; j++)
{
System.Console.Write(arr[i][j]+" ");
}
System.Console.WriteLine();
}
}
}

Output
When the above code is compiled and executed, it produces the following
result
11 21 56 78
42 61 37 41 59 63

2.19 c # s t r iNGs

In C#, string is an object of System.String class that represent sequence of


characters. We can perform many operations on strings such as concatenation,
comparision, getting substring, search, trim, replacement etc.

2.19.1 c # s tring Methods


Table 2.9: C# String Methods

44 Introduction to C #
“Only for Private Circulation”
C# Programming

NOTES

Introduction to C # 45

“Only for Private Circulation”


C# Programming

NOTES

46 Introduction to C #
“Only for Private Circulation”
C# Programming

NOTES

2.20 c # OPe r at Or s

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
• Miscellaneous Operators

2.20.1 a rithmetic Operators


Table 2.10: Arithmetic Operators

2.20.2 r elational Operators


Table 2.11: Relational Operators

Introduction to C # 47

“Only for Private Circulation”


C# Programming

NOTES

2.20.3 Logical Operators


Table 2.12: Logical Operators

2.20.4 b itwise Operators


Table 2.13: Bitwise Operators

2.20.5 a ssignment Operators


Table 2.14: Assignment Operators

48 Introduction to C #
“Only for Private Circulation”
C# Programming

NOTES

2.20.6 Miscellaneous Operators


Table 2.15: Miscellaneous Operators

2.21 c # c ONt r OL s t at e Me Nt s

In C#, there are two types of control statements

2.21.1 Decision Making s tatements


2.21.2 Looping (iterative) s tatements
2.21.1 Decision Making s tatements
C# provides following types of decision-making statements:

2.21.1.1 if s tatement
2.21.1.2 if…else s tatement
2.21.1.3 Nested if….else s tatement
2.21.1.4 switch s tatement
2.21.1.5 Nested switch s tatement

Introduction to C # 49

“Only for Private Circulation”


C# Programming 2.21.1.1 if s tatement
An if statement consists of a boolean expression followed by one or more
statements.
NOTES
s yntax
The syntax of an if statement in C# is −
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
If the boolean expression evaluates to true, then the block of code inside
the if statement is executed. If boolean expression evaluates to false, then the
first set of code after the end of the if statement (after the closing curly brace) is
executed.

f lowchart for if statement

Flowchart 2.1: if statement


Example of if statement
using System;
public class IfExample
{
50 Introduction to C #
“Only for Private Circulation”
public static void Main(string[] args) C# Programming
{
int num = 10;
NOTES
if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}
}
}

Output
When the above code is compiled and executed, it produces the following
result
It is even number

2.21.1.2 if...else s tatement


The C# if-else statement also tests the condition. It executes the if block if
condition is true otherwise else block is executed.

t he syntax of an if...else statement in c #


if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
} else
{
/* statement(s) will execute if the boolean expression is false */
}
If the boolean expression evaluates to true, then the if block of code is
executed, otherwise else block of code is executed.

Introduction to C # 51

“Only for Private Circulation”


C# Programming f lowchart for if...else statement

NOTES

Flowchart 2.2: if…else statement


Example of if…else statement
using System;
public class IfExample
{
public static void Main(string[] args)
{
int num = 11;
if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}
else
{
Console.WriteLine("It is odd number");
}
}
}
52 Introduction to C #
“Only for Private Circulation”
Output C# Programming
When the above code is compiled and executed, it produces the following
result:
NOTES
It is odd number

2.21.1.3 Nested if….else s tatement


It is always legal in C# to nest if-else statements, which means you can use
one if or else if statement inside another if or else if statement(s).

s yntax
The syntax for a nested if statement is as follows −
if( boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
}
You can nest else if...else in the similar way as you have nested if statement.
Example of nested if…else statement
using System;
namespace Tutlane
{
class Program
{
static void Main(string[] args)
{
int x = 5, y = 20;
if (x > y)
{
if (x >= 10)
{
Console.WriteLine("x value greater than or equal to 10");
}
Introduction to C # 53

“Only for Private Circulation”


C# Programming else
{
Console.WriteLine("x value less than 10");
NOTES
}
}
else
{
if (y <= 20)
{
Console.WriteLine("y value less than or equal to 20");
}
else
{
Console.WriteLine("y value greater than 20");
}
}
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}
}

Output
When the above code is compiled and executed, it produces the following
result:
y value less than or equal to 20
Press Enter Key to Exit..

2.21.1.4 s witch s tatement


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.

s yntax
The syntax for a switch statement in C# is as follows −
switch(expression) {
54 Introduction to C #
“Only for Private Circulation”
case constant-expression1 : C# Programming
statement(s);
break;
NOTES
case constant-expression2 :
case constant-expression3 :
statement(s);
break;
/* you can have any number of case statements */
default : /* Optional */
statement(s);
}

t he following rules apply to a switch statement −


• The expression used in a switch statement must have an integral or
enumerated type, or be of a class type in which the class has a single
conversion function to an integral or enumerated type.
• You can have any number of case statements within a switch. Each case
is followed by the value to be compared to and a colon.
• The constant-expression for a case must be the same data type as the
variable in the switch, and it must be a constant or a literal.
• When the variable being switched on is equal to a case, the statements
following that case will execute until a break statement is reached.
• When a break statement is reached, the switch terminates, and the flow
of control jumps to the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, then it will
raise a compile time error.
• A switch statement can have an optional default case, which must appear
at the end of the switch. The default case can be used for performing a
task when none of the cases is true.

Introduction to C # 55

“Only for Private Circulation”


C# Programming f lowchart for switch statement

NOTES

Flowchart 2.3: switch statement

e xample of switch case


using System;
public class switchcase {
public static void Main(String[] args)
{
int nitem = 5;
switch (nitem) {
case 1:
Console.WriteLine("case 1");
break;
case 5:
Console.WriteLine("case 5");
56 Introduction to C # break;

“Only for Private Circulation”


case 9: C# Programming
Console.WriteLine("case 9");
break;
NOTES
default:
Console.WriteLine("No match found");
break;
}
}
}

Output
When the above code is compiled and executed, it produces the following
result:
case 5

2.21.1.5 Nested switch s tatement


It is possible to have a switch as part of the statement sequence of an outer
switch. Even if the case constants of the inner and outer switch contain common
values, no conflicts will arise.

s yntax
The syntax for a nested switch statement is as follows −
switch(ch1) {
case 'A':
Console.WriteLine("This A is part of outer switch" );
switch(ch2) {
case 'A':
Console.WriteLine("This A is part of inner switch" );
break;
case 'B': /* inner B case code */
}
break;
case 'B': /* outer B case code */
}

e xample of Nested switch statement


using System;
namespace DecisionMaking {
class Program {
static void Main(string[] args) {
Introduction to C # 57

“Only for Private Circulation”


C# Programming int a = 100;
int b = 200;
switch (a) {
NOTES case 100:
Console.WriteLine("This is part of outer switch ");
switch (b) {
case 200:
Console.WriteLine("This is part of inner switch ");
break;
}
break;
}
Console.WriteLine("Exact value of a is : {0}", a);
Console.WriteLine("Exact value of b is : {0}", b);
Console.ReadLine();
}
}
}

Output:
When the above code is compiled and executed, it produces the following
result −
This is part of outer switch
This is part of inner switch
Exact value of a is : 100
Exact value of b is : 200

2.21.2 Looping (iterative) s tatements


There may be a situation, when you need to execute a block of code several
number of times. In general, the statements are executed sequentially: The first
statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for
more complicated execution paths.
A loop statement allows us to execute a statement or a group of statements
multiple times and following is the general from of a loop statement in most of
the programming languages
C# provides following types of loop to handle looping requirements:
2.21.2.1 while loop
2.21.2.2 for loop
2.21.2.3 do…while loop

58 Introduction to C # 2.21.2.4 foreach loop

“Only for Private Circulation”


2.21.2.1 while loop C# Programming
A while loop statement in C# repeatedly executes a target statement as long
as a given condition is true.
NOTES
s yntax
The syntax of a while loop in C# is −
while(condition) {
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The
condition may be any expression, and true is any non-zero value. The loop
iterates while the condition is true

f lowchart for while loop

Flowchart 2.4: while loop

Introduction to C # 59

“Only for Private Circulation”


C# Programming e xample of while loop
using System;
public class WhileExample
NOTES
{
public static void Main(string[] args)
{
int i=1;
while(i<=5)
{
Console.WriteLine(i);
i++;
}
}
}

Output
When the above code is compiled and executed, it produces the following
result −
1
2
3
4
5

2.21.2.2 for loop


A for loop is a repetition control structure that allows you to efficiently write
a loop that needs to execute a specific number of times.

s yntax
The syntax of a for loop in C# is −
for ( init; condition; increment ) {
statement(s);
}

Here is the flow of control in a for loop −


• The init step is executed first, and only once. This step allows you to
declare and initialize any loop control variables. You are not required to
put a statement here, as long as a semicolon appears.
60 Introduction to C #
“Only for Private Circulation”
• Next, the condition is evaluated. If it is true, the body of the loop is C# Programming
executed. If it is false, the body of the loop does not execute and flow of
control jumps to the next statement just after the for loop.
• After the body of the for loop executes, the flow of control jumps back NOTES
up to the increment statement. This statement allows you to update any
loop control variables. This statement can be left blank, as long as a
semicolon appears after the condition.
• The condition is now evaluated again. If it is true, the loop executes and
the process repeats itself (body of loop, then increment step, and then
again testing for a condition). After the condition becomes false, the for
loop terminates.

f lowchart of for loop

Flowchart 2.5: for loop


Introduction to C # 61

“Only for Private Circulation”


C# Programming e xample of for loop
using System;
public class ForExample
NOTES
{
public static void Main(string[] args)
{
for(int i=1;i<=5;i++){
Console.WriteLine(i);
}
}
}

Output
When the above code is compiled and executed, it produces the following
result −
1
2
3
4
5

2.21.2.3 do…while loop


Unlike for and while loops, which test the loop condition at the start of the
loop, the do...while loop checks its condition at the end of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is
guaranteed to execute at least one time.

s yntax
The syntax of a do...while loop in C# is −
do {
statement(s);
} while( condition );
Notice that the conditional expression appears at the end of the loop, so the
statement(s) in the loop execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the
statement(s) in the loop execute again. This process repeats until the given
condition becomes false.
62 Introduction to C #
“Only for Private Circulation”
f lowchart for do…while loop C# Programming

NOTES

Flowchart 2.6: do…while loop

e xample of do…while loop


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

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

Introduction to C # 63

“Only for Private Circulation”


C# Programming Output
When the above code is compiled and executed, it produces the following
result −
NOTES
1
2
3
4
5

2.21.2.4 foreach loop


The foreach loop executes a statement or a block of statements for each
element in an instance of the type that implements the
System.Collections.IEnumerable or System.Collections.Generic.IEnumerable
<T> interface

e xample of foreach loop


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

foreach(char ch in myArray)
{
Console.WriteLine(ch);
}
}
}
}

Output
When the above code is compiled and executed, it produces the following
result −
64 Introduction to C #
“Only for Private Circulation”
H C# Programming
e
l
NOTES
l
o

2.22 c # t y Pe c ONv e r s iONs

Type conversion is converting one type of data to another type. It is also


known as Type Casting. In C#, type casting has two forms −
• Implicit type conversion − These conversions are performed by C# in
a type-safe manner. For example, are conversions from smaller to larger
integral types and conversions from derived classes to base classes.
• Explicit type conversion − These conversions are done explicitly by
users using the pre-defined functions. Explicit conversions require a cast
operator.

2.22.1 c # t ype c onversion Methods


C# provides the following built-in type conversion methods –
Table 2.16: C# Type Conversion Methods

Introduction to C # 65

“Only for Private Circulation”


C# Programming

NOTES

2.22 c # Mathematical f unctions


The System.Math class in C# provides methods are properties to perform
mathematical operations, trigonometric, logarithmic calculations, etc.
Some of its methods include –
Table 2.17: C# Mathematical Functions

66 Introduction to C #
“Only for Private Circulation”
C# Programming

NOTES

e xercise
Q.1 Describe evolution of C# programming language with its
characteristics.
Q.2 Write characteristics of C# programming language and write various
types of applications C# can develop.
Q.3 Write Difference between C++ and C#.
Q.4 Write major differences between C# and Java.
Q.5 Describe Origins of the Microsoft .NET Technology.
Q.6 Write in details Microsoft . NET Framework.
Q.7 Explain CLR with its various functions.
Q.8 State and explain various components of User and Programs Interface
of Visual Studio .Net.
Q.9 State and explain features of various languages of Visual Studio .Net.
Q.10 What are the C# data types? Explain.
Q.11 Write the concept of C# Identifiers and C# Variables.
Q.12 What are the C# Constants? Explain.
Q.13 Write various types of C# Statements.
Q.14 What is Array? Write Single dimensional array in C# with example.
Q.15 Explain in detail Two dimensional Array in C# with example.
Q.16 What is Jagged Array? Explain with example.
Q.17 What is role of C# String class? Write various methods of C# String
class.
Introduction to C # 67

“Only for Private Circulation”


C# Programming Q.18 Write various types of C# operators.
Q.19 What are the types of C# decision making statements? Write syntax
and example of if statement in C#.
NOTES
Q.20 Write syntax and example of if…else statement in C#.
Q.21 Write syntax and example of nested if…else statement in C#.
Q.22 What is role of switch statement? Write syntax and example of switch
statement in C#.
Q.23 Is it possible to nest switch statement? Explain with example.
Q.24 What are the types of C# looping statements? Write syntax and
example of while loop in C#.
Q.25 Write syntax and example of for loop in C#.
Q.26 What is difference in while and do…while looping statements?
Explain with example.
Q.27 What is role of foreach loop? Explain with example.
Q.28 Write various type conversion methods used in C#.
Q.29 Write various mathematical functions used in C#.

*****

68 Introduction to C #
“Only for Private Circulation”
C# Programming

UNIT - III
NOTES
CLASSES AND OBJECTS

Learning Objectives
• To introduce students with concepts of Classes and Objects using C#.
• To introduce students with Object Oriented Concepts such as inheritance,
polymorphism etc. using C#.

3.1 b a s ic Pr iNc iPLe s Of Ob Je c t Or ie Nt e D


Pr OGr a MMiNG (OOP)

There are 4 major principles that make an language Object Oriented. These
are Encapsulation, Data Abstraction, Polymorphism and Inheritance. These are
also called as four pillars of Object Oriented Programming.

Fig 3.1: Pillars of Object Oriented Programming

3.1.1 e ncapsulation
Encapsulation is the mechanism of hiding of data implementation by
restricting access to public methods. Instance variables are kept private and
accessor methods are made public to achieve this.

3.1.2 a bstraction
Abstract means a concept or an Idea, which is not associated with any
particular instance. Using abstract class/Interface, we express the intent of the
class rather than the actual implementation. In a way, one class should not know
the inner details of another in order to use it, just knowing the interfaces should
be good enough. Classes and Objects 69

“Only for Private Circulation”


C# Programming 3.1.3 inheritance
Inheritances expresses “is-a” and/or “has-a” relationship between two
objects. Using Inheritance, In derived classes we can reuse the code of existing
NOTES super classes. In Java, concept of “is-a” is based on class inheritance (using
extends) or interface implementation (using implements).

3.1.4 Polymorphism
It means one name many forms. It is further of two types — static and
dynamic. Static polymorphism is achieved using method overloading and
dynamic polymorphism using method overriding. It is closely related to
inheritance. We can write a code that works on the superclass, and it will work
with any subclass type as well.

3.2 c # c La s s

In C#, class is a group of similar objects. It is a template from which objects


are created. When you define a class, you define a blueprint for a data type. This
does not actually define any data, but it does define what the class name means.
That is, what an object of the class consists of and what operations can be
performed on that object. Objects are instances of a class. The methods and
variables that constitute a class are called members of the class.

Defining a c lass
A class definition starts with the keyword class followed by the class name;
and the class body enclosed by a pair of curly braces. Following is the general
form of a class definition.

s yntax:
<access specifier> class class_name {
// member variables
<access specifier> <data type> variable1;
<access specifier> <data type> variable2;
...
<access specifier> <data type> variableN;
// member methods
<access specifier> <return type> method1(parameter_list) {
// method body
}

70 Classes and Objects <access specifier> <return type> method2(parameter_list) {

“Only for Private Circulation”


// method body C# Programming
}
...
NOTES
<access specifier> <return type> methodN(parameter_list) {
// method body
}
}

e xample
class Student
{
int id;
String name;
}

3.3 c # Ob Je c t s

In C#, Object is a real world entity that has state and behavior. Here, in
programming language, state means data and behavior means functionality.
Object is a runtime entity, it is created at runtime. Object is an instance of a class.
All the members of the class can be accessed through object.
Student s1 = new Student();//creating an object of Student
C# Object and Class Example
using System;
public class Student
{
int id;//data member (also instance variable)
String name;//data member(also instance variable)
public static void Main(string[] args)
{
Student s1 = new Student();//creating an object of Student
s1.id = 101;
s1.name = "Raj";
Console.WriteLine(s1.id);
Classes and Objects 71

“Only for Private Circulation”


C# Programming Console.WriteLine(s1.name);
}
}
NOTES

Output
When the above code is compiled and executed, it produces the following
result −
101
Raj

3.4 c ONs t r u c t Or s

A special method of the class that is automatically invoked when an instance


of the class is created is called a constructor.
The main use of constructors is to initialize private fields of the class while
creating an instance for the class. When you have not created a constructor in
the class, the compiler will automatically create a default constructor of the class.
The default constructor initializes all numeric fields in the class to zero and all
string and object fields to null.

c haracteristics of the c onstructor


• The name of the constructors must have to be the same as that of the
name of the class in which will resides.
• A constructor can never be final, abstract, synchronized, and static.
• You can produce only a single static constructor.
• A static constructor cannot be used as a parameterized constructor.
• Constructors usually don't have a return type, not even void.
• The number of constructors can be any within a class.
• Constructors can contain access modifiers along with it
In C#, constructors can be divided into following types

3.4.1 Default c onstructor


3.4.2 Parametrized Constructor
3.4.3 Copy Constructor
3.4.4 Static Constructor
3.4.5 Private Constructor

72 Classes and Objects 3.4.1 Default Constructor

“Only for Private Circulation”


A constructor without any parameters is called a default constructor. A C# Programming
default constructor has every instance of the class to be initialized to the same
values. The default constructor initializes all numeric fields to zero and all string
and object fields to null inside a class. NOTES

e xample of Default c onstructor


using System;
public class Employee
{
public Employee()
{
Console.WriteLine("Default Constructor Called");
}
public static void Main(string[] args)
{
Employee e1 = new Employee();
}
}

Output
Default Constructor Called

3.4.2 Parametrized c onstructor


A constructor with at least one parameter is called a parametrized
constructor. It is used to provide different values to distinct objects.
using System;
namespace Constructor
{
class paraconstrctor
{
public int a, b;
public paraconstrctor(int x, int y {
a = x;
b = y;
}
}
Classes and Objects 73

“Only for Private Circulation”


C# Programming class MainClass
{
static void Main()
NOTES
{
paraconstrctor v = new paraconstrctor(100, 175);
Console.WriteLine("\t");
Console.WriteLine("Value of a=" + v.a );
Console.WriteLine("Value of b=" + v.b);
Console.Read();
}
}
}

Output
Default Constructor Called
Value of a=100
Value of b=175

3.4.3 c opy c onstructor


The constructor which creates an object by copying variables from another
object is called a copy constructor. The purpose of a copy constructor is to
initialize a new instance to the values of an existing instance.

e xample of c opy c onstructor


class Demo
{
string name;
int age;
public Demo(string name, int age)
{
this.name = name;
this.age = age;
}
public Demo(Demo d) //copy constructor
{

74 Classes and Objects this.name = d.name;

“Only for Private Circulation”


this.age = d.age; C# Programming
}
public void getData()
NOTES
{
Console.WriteLine("Name is:{0}", name);
Console.WriteLine("Age is:{0}", age);
}
}
class Program
{
//main method
static void Main(string[] args)
{
Demo obj = new Demo("Raj",20);
obj.getData();
Demo obj1 = new Demo(obj); //new object
obj1.getData();
Console.ReadLine();
}
}

Output
Name is:Raj
Age is=20
Name is:Raj
Age is=20

3.4.4 s tatic c onstructor


When a constructor is created using a static keyword, it will be invoked
only once for all of instances of the class and it is invoked during the creation of
the first instance of the class or the first reference to a static member in the class.
A static constructor is used to initialize static fields of the class and to write the
code that needs to be executed only once.

Classes and Objects 75

“Only for Private Circulation”


C# Programming c haracteristics of a static constructor
• A static constructor does not take access modifiers or have parameters.
• A static constructor is called automatically to initialize the class before
NOTES
the first instance is created or any static members are referenced.
• A static constructor cannot be called directly.
• The user has no control on when the static constructor is executed in the
program.
• A typical use of static constructors is when the class is using a log file
and the constructor is used to write entries to this file.

e xample of s tatic c onstructor


using System;
public class Account
{
public int id;
public String name;
public static float rateOfInterest;
public Account(int id, String name)
{
this.id = id;
this.name = name;
}
static Account()
{
rateOfInterest = 9.5f;
}
public void display()
{
Console.WriteLine(id + " " + name+" "+rateOfInterest);
}
}
class TestEmployee{
public static void Main(string[] args)
{
76 Classes and Objects
“Only for Private Circulation”
Account a1 = new Account(101, "Yash"); C# Programming
Account a2 = new Account(102, "Raj");
a1.display();
NOTES
a2.display();
}
}

Output
101 Yash 9.5
102 Raj 9.5

3.4.5 Private c onstructor


Private Constructor is a special instance constructor present in C# language.
Basically, private constructors are used in class that contains only static members.
The private constructor is always declared by using a private keyword.

c haracteristics of Private c onstructor


• It is the implementation of a singleton class pattern.
• Use private constructor when class have only static members.
• Using private constructor, prevents the creation of the instances of that
class.
• If a class contains only private constructor without parameter, then it
prevents the automatic generation of default constructor.
• If a class contains only private constructors and does not contain public
constructor, then other classes are not allowed to create instances of that
class except nested class.

e xample of Private c onstructor


using System;
class privconst
{
public static string name;
public static int num;
private privconst() {
Console.WriteLine("Welcome to Private Constructor");
}
public privconst (string a, int b)
Classes and Objects 77

“Only for Private Circulation”


C# Programming {
name = a;
num = b;
NOTES
}
}
class privconstmain
{
static void Main()
{
privconst obj2 = new privconst ("Raj", 2);
Console.WriteLine(privconst.name + ", " + privconst.num);
}
}

Output
Raj, 2

3.5 De s t r u c t Or iN c #

Destructors in C# are methods inside the class used to destroy instances of


that class when they are no longer needed. The Destructor is called implicitly by
the .NET Framework’s Garbage collector and therefore programmer has no
control as when to invoke the destructor. An instance variable or an object is
eligible for destruction when it is no longer reachable.

c haracteristics of Destructors
• A Destructor is unique to its class i.e. there cannot be more than one
destructor in a class.
• A Destructor has no return type and has exactly the same name as the
class name (Including the same case).
• It is distinguished apart from a constructor because of the Tilde symbol
(~) prefixed to its name.
• A Destructor does not accept any parameters and modifiers.
• It cannot be defined in Structures. It is only used with classes.
• It cannot be overloaded or inherited.
• It is called when the program exits.
• Internally, Destructor called the Finalize method on the base class of
object.

78 Classes and Objects


“Only for Private Circulation”
e xample of Destructor in c # C# Programming
namespace LineApplication {
class Line {
NOTES
private double length; // Length of a line
public Line() { // constructor
Console.WriteLine("Object is being created");
}
~Line() { //destructor
Console.WriteLine("Object is being deleted");
}
public void setLength( double len ) {
length = len;
}
public double getLength() {
return length;
}
static void Main(string[] args) {
Line line = new Line();
// set line length
line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
}
}
}

Output
Object is being created
Length of line : 6
Object is being deleted

3.6 Me Mb e r iNit ia Liz at iON

C# allows you instantiate an object or collection and perform member


assignments in a single statement. Classes and Objects 79

“Only for Private Circulation”


C# Programming 3.6.1 Object Initializer
3.6.2 Collection Initializer

NOTES 3.6.1 Object initializer


C# Object Initializer is a new way to assign values at the time of object
creation. It does not require constructor call to assign fields values. You can create
an object and then this syntax initializes the freshly created object with its
properties, to the variable in the assignment. It can also place indexers, to
initializing fields and properties.

e xample of Object initializer in c #


using System;
namespace CSharpFeatures
{
class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
class ObjectInitializer
{
public static void Main(string[] args)
{
// Using Object Initialilzer
Student student = new Student { ID=101, Name="Raj",
Email="raj@example.com" };
// Displaying Initialized Values
Console.WriteLine(student.ID);
Console.WriteLine(student.Name);
Console.WriteLine(student.Email);
}
}
}

Output
101
Raj
raj@example.com
80 Classes and Objects
“Only for Private Circulation”
3.6.2 c ollection initializer C# Programming
Collection initializer is also similar to object initializers. The collections are
initialized similarly like objects are initialized using an object initializer. Or in
other words, generally, we used the Add() method to add elements in collections, NOTES
but using a collection initializer you can add elements without using Add()
method. Collection Initializer allows us to initialize a collection type that
implements IEnumerable interface.

e xample of c ollection initializer


using System;
using System.Collections.Generic;
namespace CSharpFeatures
{
class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
class ObjectInitializer
{
public static void Main(string[] args)
{
List<Student> students = new List<Student> {
new Student { ID=101, Name="Jay", Email="jay@example.com" },
new Student { ID=102, Name="Yash", Email="yash@abc.com" },
new Student { ID=103, Name="Raj", Email="raj@example.com" }
};
foreach (Student student in students)
{
Console.Write(student.ID+" ");
Console.Write(student.Name+" ");
Console.Write(student.Email+" ");
Console.WriteLine();
}
Classes and Objects 81

“Only for Private Circulation”


C# Programming }
}
}
NOTES

Output
101 Jay jay@example.com
102 Yash yash@abc.com
103 Raj raj@example.com

3.7 t He ‘t His ’ r e f e r e Nc e

In C# programming, this is a keyword that refers to the current instance of


the class. There can be 3 main usage of this keyword in C#.
• It can be used to refer current class instance variable. It is used if field
names (instance variables) and parameter names are same, that is why
both can be distinguish easily.
• It can be used to pass current object as a parameter to another method.
• It can be used to declare indexers.

e xample of ‘this’ r eference


using System;
public class Employee
{
public int id;
public String name;
public Employee(int id, String name)
{
this.id = id;
this.name = name;
}
public void display()
{
Console.WriteLine(id + " " + name);
}
}
82 Classes and Objects
“Only for Private Circulation”
class TestEmployee{ C# Programming
public static void Main(string[] args)
{
NOTES
Employee e1 = new Employee(101, "Raj");
Employee e2 = new Employee(102, "Yash");
e1.display();
e2.display();
}
}

Output
101 Raj
102 Yash

3.8 Ne s t iNG Of c La s s e s iN c #

In C#, a user is allowed to define a class within another class. Such types
of classes are known as nested class. This feature enables the user to logically
group classes that are only used in one place, thus this increases the use of
encapsulation, and create more readable and maintainable code.

s yntax
class Outer_class {
// Code..
class Inner_class {
// Code..
}
}

e xample of Nested c lasses in c #


using System;
public class Outer_class
{
public void method1()
{
Console.WriteLine("Outer class method"); Classes and Objects 83

“Only for Private Circulation”


C# Programming }
public class Inner_class {
public void method2()
NOTES
{
Console.WriteLine("Inner class Method");
}
}
}
public class nestclass {
public static void Main()
{
Outer_class obj1 = new Outer_class();
obj1.method1();
Outer_class.Inner_class obj2 =
new Outer_class.Inner_class();
obj2.method2();
}
}

Output
Outer class method
Inner class Method

3.9 c ONs t a Nt a ND r e a D ONLy Me Mb e r s iN c #

In C#, a const keyword is used to declare constant fields and constant local.
The value of the constant field is the same throughout the program or in other
words, once the constant field is assigned the value of this field is not be changed.
In C#, constant fields and locals are not variables, a constant is a number, string,
null reference, boolean values.

e xample of c onstant Members in c #


sing System;
class constmeb
{
84 Classes and Objects
“Only for Private Circulation”
public const int myvar = 1; C# Programming
public const string str = "Hello";
public static void Main()
NOTES
{
Console.WriteLine("The value of myvar: {0}", myvar);
Console.WriteLine("The value of str: {0}", str);
}
}

Output
The value of myvar: 1
The value of str: Hello
In C#, you can use a readonly keyword to declare a readonly variable. This
readonly keyword shows that you can assign the variable only when you declare
a variable or in a constructor of the same class in which it is declared.

e xample of readonly members in c #


using System;
class readonlymem
{
public readonly int myvar1;
public readonly int myvar2;
public readonlymem (int b, int c)
{
myvar1 = b;
myvar2 = c;
Console.WriteLine("Display value of myvar1 {0}, "+
"and myvar2 {1}", myvar1, myvar2);
}
public static void Main()
{
readonlymem obj1 = new readonlymem (100, 200);
}
}

Classes and Objects 85

“Only for Private Circulation”


C# Programming Output
Display value of myvar1 100, and myvar2 200

NOTES
3.10 c # Pr OPe r t ie s

Properties are the special type of class members that provides a flexible
mechanism to read, write, or compute the value of a private field. Properties can
be used as if they are public data members, but they are actually special methods
called accessors. This enables data to be accessed easily and help to promote the
flexibility and safety of methods. Encapsulation and hiding of information can
also be achieved using properties. It uses pre-define methods which are “get”
and “set” methods which helps to access and modify the properties.
Accessors: The block of “set” and “get” is known as “Accessors”. It is very
essential to restrict the accessibility of property. There are two type of accessors
i.e. get accessors and set accessors. There are different types of properties based
on the “get” and set accessors:
• Read and Write Properties: When property contains both get and set
methods.
• Read-Only Properties: When property contains only get method.
• Write Only Properties: When property contains only set method.
• Auto Implemented Properties: When there is no additional logic in the
property accessors

t he syntax for Defining Properties


<access_modifier> <return_type> <property_name>
{
get { // body }
set { // body }
}

e xample of c # Properties
using System;
public class Student
{
private string name = "C# Programming";
public string Name
{
86 Classes and Objects
“Only for Private Circulation”
get C# Programming
{
return name;
NOTES
}
set
{
name = value;
}
}
}
class TestStudent {
public static void Main(string[] args)
{
Student s = new Student();
s.Name = "Raj";
Console.WriteLine("Name: " + s.Name);
}
}

Output
Raj

3.11 c # iNDe Xe r s

An indexer allows an object to be indexed such as an array. When you define


an indexer for a class, this class behaves similar to a virtual array. You can then
access the instance of this class using the array access operator ([ ]). Indexers are
almost similar to the Properties. The main difference between Indexers and
Properties is that the accessors of the Indexers will take parameters.

s yntax
[access_modifier] [return_type] this [argument_list]
{
get
{
Classes and Objects 87

“Only for Private Circulation”


C# Programming // get block code
}
set
NOTES
{
// set block code
}
}
Where,
• access_modifier: It can be public, private, protected or internal.
• return_type: It can be any valid C# type.
• this: It is the keyword which points to the object of the current class.
• argument_list: This specifies the parameter list of the indexer.
• get{ } and set { }: These are the accessors.

e xample
using System;
class IndexerCreation
{
private string[] val = new string[3];
public string this[int index]
{
get
{
return val[index];
}
set
{
val[index] = value;
}
}
}
class main {
public static void Main() {

88 Classes and Objects


“Only for Private Circulation”
IndexerCreation ic = new IndexerCreation(); C# Programming
ic[0] = "C";
ic[1] = "C++";
NOTES
ic[2] = "C#";
Console.Write("Printing values stored in objects used as arrays\n");
Console.WriteLine("First value = {0}", ic[0]);
Console.WriteLine("Second value = {0}", ic[1]);
Console.WriteLine("Third value = {0}", ic[2]);
}
}

Output
Printing values stored in objects used as arrays
First value = C
Second value = C++
Third value = C#

3.12 iNHe r it a Nc e iN c #

Inheritance is one of the most important concepts in object-oriented


programming. It let us to define a class in terms of another class. Inheritance
provides facility to reuse the code functionality and increase the execution time
of program.
In inheritance, the class, which derives the members of another class, is
called derived class and the class whose members are derived is called base class.
The derived class is the specialized class for the base class.

s yntax of inheritance with base class and derived class:


<acess-specifier> class <base_class>
{
...
}
class <derived_class> : <base_class>
{
...
} 89
Classes and Objects
“Only for Private Circulation”
C# Programming e xample
public class baseclass
{
NOTES
public void GetDetails()
{
// Method implementation
}
}
public class derviedclass : baseclass
{
}
class Program
{
static void Main(string[] args)
{
derviedclass obj = new derviedclass ();
obj.GetDetails();
}
}

c # supports following types of inheritance


3.12.1 Single Level Inheritance
3.21.2 Multilevel Inheritance
3.21.3 Hierarchical Inheritance
Multiple inheritance is not supported by C# programming language, but it
can be used through interface.

3.12.1 s ingle Level inheritance


When only one class is derived from the base class then it is called as Single
Level inheritance. In, single level inheritance there is only one base class and
one derived class.

e xample of s ingle Level inheritance


using System;
namespace Application
{
90 Classes and Objects
“Only for Private Circulation”
class A C# Programming
{
public void show()
NOTES
{
Console.WriteLine("Single Level Inheritance");
}
}
class B : A
{
public void display()
{
Console.WriteLine("Called");
}
}
class single
{
public static void Main()
{
B obj = new B();
obj.show();
obj.display();
}
}
}

w hen we run above c # program, it gives following output


Single Level Inheritance
Called

3.12.2 Multilevel inheritance


When one class derives another one class, which is further derived by
another class, then it is called as multilevel inheritance. Multilevel inheritance is
transitive, so the last derived class acquires all the members of all its base classes.

Classes and Objects 91

“Only for Private Circulation”


C# Programming e xample of Multilevel inheritance
using System;
namespace Application
NOTES
{
class A
{
public void show()
{
Console.WriteLine("Base Class A");
}
}
class B : A
{
public void display()
{
Console.WriteLine("Derived Class B");
}
}
class C : B
{
public void show1()
{
Console.WriteLine("Multilevel Inheritance Called");
}
class multilevel
{
public static void Main()
{
C obj = new C();
obj.show();
obj.display();
obj.show1();
}
92 Classes and Objects
“Only for Private Circulation”
} C# Programming
}
}
NOTES

w hen we run above c # program, it gives following output


Base Class A
Derived Class B
Multilevel Inheritance Called

3.12.3 Hierarchical inheritance


When multiple classes are derived from only one base class, then it is called
as hierarchical inheritance. In this type of inheritance, there are is only one base
class and multiple derived classes present. Hierarchical inheritance is used when
one class feature is required in multiple classes.

e xample of Hierarchical inheritance


using System;
namespace Application
{
class A
{
public void show()
{
Console.WriteLine("Base Class A");
}
}
class B : A
{
public void display()
{
Console.WriteLine("Derived Class B");
}
}
class C : A //class C is derived by class A
{
public void show1()
Classes and Objects 93

“Only for Private Circulation”


C# Programming {
Console.WriteLine("Derived Class C");
}
NOTES
}
class hierarchical
{
public static void Main()
{
B objl = new B();
C obj2 = new C();
objl.show();
objl.display();
obj2.show1();
}
}
}

w hen we run above c # program, it gives following output


Base Class A
Derived Class B
Derived Class C

3.13 c # iNt e r f a c e s

An interface is defined as a syntactical contract that all the classes inheriting


the interface should follow. Interface in C# is a blueprint of a class. It is like
abstract class because all the methods, which are declared inside the interface,
are abstract methods. It cannot have method body and cannot be instantiated.
Interfaces define properties, methods, and events, which are the members of the
interface. Interfaces contain only the declaration of the members. It is the
responsibility of the deriving class to define the members.
It is used to achieve multiple inheritance which can't be achieved by class.
It is used to achieve fully abstraction because it cannot have method body. Its
implementation must be provided by class or struct. The class or struct which
implements the interface, must provide the implementation of all the methods
declared inside the interface.
94 Classes and Objects
“Only for Private Circulation”
s yntax of interface C# Programming
interface <interface_name >
{
NOTES
// declare Events
// declare indexers
// declare methods
// declare properties
}

e xample of interface in c #
using System;
interface inter1
{
void display();
}
class testClass : inter1
{
public void display()
{
Console.WriteLine("This is Interface in C#");
}
public static void Main (String []args)
{
testClass t = new testClass();
t.display();
}
}

w hen we run above c # program, it gives following output


This is Interface in C#
Example of interface to demonstrate use of multiple inheritance in C#
using System;
public interface A
{
Classes and Objects 95

“Only for Private Circulation”


C# Programming void disp();
}
public interface B
NOTES
{
public void show();
}
public class Test : A, B
{
public void disp()
{
Console.WriteLine("Interface A Called");
}
public void show()
{
Console.WriteLine("Interface B Called");
}
}
public class TestInterface
{
public static void Main()
{
Test obj =new Test ();
obj.disp();
obj.show();
}
}

w hen we run above c # program, it gives following output


Interface A Called
Interface B Called

96 Classes and Objects


“Only for Private Circulation”
C# Programming

3.14 c # POLy MOr PHis M


NOTES
Polymorphism means having many forms. In object-oriented programming
paradigm, polymorphism is often expressed as 'one interface, multiple functions.
Polymorphism is one of the important pillars of object-oriented programming.
Following are the two types of polymorphism
3.14.1 Static Polymorphism
3.14.2 Dynamic Polymorphism
Static polymorphism is also called as compile-time polymorphism and
dynamic polymorphism is also called as run-time polymorphism. In static
polymorphism, the response to a function is determined at the compile time and
in dynamic polymorphism, it is decided at run-time.
Static polymorphism can be further divided into following types:
3.14.1.1 Function Overloading
2.14.1.2 Operator Overloading

3.14.1.1 f unction Overloading


Function overloading is also called as method overloading is the simple
way of implementing polymorphism. It is the ability to redefine a function in
more than one form. A user can implement function overloading by defining two
or more functions in a class sharing the same name. C# can distinguish the
methods with different method signatures. i.e. the methods can have the same
name but with different parameters list within the same class.

important r ules of f unction Overloading


• Overloaded methods are differentiated based on the number and type of
the parameters passed as arguments to the methods.
• You cannot define more than one method with the same name, Order and
the type of the arguments.
• The compiler does not consider the return type while differentiating the
overloaded method. You cannot declare two methods with the same
signature and different return type.
• If both methods have the same parameter types, but different return type,
then it is not possible.

e xample of f unction Overloading


using System;
class methoverload
Classes and Objects 97

“Only for Private Circulation”


C# Programming {
public int Add(int a, int b)
{
NOTES
int sum = a + b;
return sum;
}
public int Add(int a, int b, int c)
{
int sum = a + b + c;
return sum;
}
public static void Main(String[] args)
{
methoverload ob = new methoverload ();
int sum1 = ob.Add(1, 2);
Console.WriteLine("sum of the two " + "integer value : " + sum1);
int sum2 = ob.Add(1, 2, 3);
Console.WriteLine("sum of the three " + "integer value : " + sum2);
}
}

w hen we run above c # program, it gives following output


sum of the two integer value : 3
sum of the three integer value : 6

2.14.1.2 Operator Overloading


C# lets you to redefine or overload most of the built-in operators. A
programmer can use operators with user-defined types as well. Overloaded
operators are functions with special names the keyword operator followed by the
symbol for the operator being defined.
Table 3.1: Overloadable and Non-Overloadable Operators in C#

98 Classes and Objects


“Only for Private Circulation”
C# Programming

NOTES

e xample of Operator Overloading


class Distance
{
public int Values;
{
get;
set;
}
public static Distance operator + ( Distance d1, Distance d2 )
{
Distance d = new Distance();
d.Values = d1.values + d2.values;
return d;
}
}
class Program
{
static void Main ( string[ ] args )
{
Distance d1 = new Distance();
Distance d2 = new Distance();
Classes and Objects 99

“Only for Private Circulation”


C# Programming d1.Values = 10;
d1.Values = 20;
Distance d3 = d1 + d2;
NOTES
Console.WriteLine(“Sun is {0}”, d3.Values );
Console.Read();
}
}

w hen we run above c # program, it gives following output


Sum is 25

3.14.2 Dynamic Polymorphism


C# allows you to create abstract classes that are used to provide partial class
implementation of an interface. Implementation is completed when a derived
class inherits from it. Abstract classes contain abstract methods, which are
implemented by the derived class. The derived classes have more specialized
functionality.
Here are the rules about abstract classes −
• You cannot create an instance of an abstract class
• You cannot declare an abstract method outside an abstract class
• When a class is declared sealed, it cannot be inherited, abstract classes
cannot be declared sealed.

e xample of Dynamic Polymorphism


using System;
namespace PolymorphismApplication
{
abstract class Shape
{
public abstract int area();
}
class Square: Shape
{
private int side;
public Square( int a=0)
{
100 Classes and Objects
“Only for Private Circulation”
side = a; C# Programming
}
public override int area ()
NOTES
{
return (side*side);
}
}
class Program
{
static void Main(string[] args)
{
Square s = new Square(10);
int a = s.area();
Console.WriteLine("Area of square is: {0}",a);
Console.ReadKey();
}
}
}

w hen we run above c # program, it gives following output


Area of square is: 100

3.15 Me t HOD Ov e r r iDiNG

Method Overriding is a technique that allows the invoking of functions from


another class (base class) in the derived class. Creating a method in the derived
class with the same signature as a method in the base class is called as method
overriding.

e xample of Method Overriding


using System;
public class A
{
public virtual void disp()
{
Classes and Objects 101

“Only for Private Circulation”


C# Programming Console.WriteLine("Virtual Method");
}
}
NOTES
public class B: A
{
public override void disp()
{
Console.WriteLine("Override Method");
}
}
public class TestOverriding
{
public static void Main()
{
B obj = new B();
obj.disp();
}
}

w hen we run above c # program, it gives following output


Override Method

e xercise
Q.1 What is class? Describe principles of object-oriented programming.
Q.2 Define object. Write a C# program to create object of a class.
Q.3 What is constructor? Write various characteristics of a constructor.
Q.4 What are the types of constructor? Write a C# program to demonstrate
use of default constructor.
Q.5 Explain parameterized constructor with example.
Q.6 What is copy constructor? Explain with example.
Q.7 Explain with example the concept of static constructor.
Q.8 Describe the concept of private constructor.
Q.9 What is destructor? Write a C# program to demonstrate use of
destructor.
Q.10 Explain object initializer with help of C# example.
102 Classes and Objects
“Only for Private Circulation”
Q.11 What is use of collection initializer? Explain with example. C# Programming
Q.12 What is use of ‘this’ reference? Give example.
Q.13 How classes are nested in C#? Explain with example.
NOTES
Q.14 Explain the use of constant and read only members in C#.
Q.15 Explain the concept of C# properties with example.
Q.16 What is indexer? Write a C# program to demonstrate use of indexer.
Q.17 Define Inheritance. Write Single level inheritance in C# with example.
Q.18 Write multilevel inheritance in C# with example
Q.19 How hierarchical inheritance implemented in C#? Explain with
example.
Q.20 What is role of interface? Write a C# program to demonstrate use of
interface.
Q.21 Define Polymorphism. Write the concept of function overloading in
C#.
Q.22 How operator overloading implemented in C#? Explain with example.
Q.23 What is dynamic polymorphism? Explain with example in C#.
Q.24 Explain the concept of method overriding with C# example.

*****

Classes and Objects 103

“Only for Private Circulation”


C# Programming

UNIT - IV
NOTES
VISUAL STUDIO IDE FEATURES

Learning Objectives
• To introduce students with Microsoft Visual Studio Integrated
Development Environment (IDE).
• To introduce students with Windows Forms, components, and controls.

4.1 Mic r Os Of t v is u a L s t u DiO iNt e Gr at e D


De v e LOPMe Nt e Nv ir ONMe Nt (iDe )

Visual Studio .NET is an IDE from Microsoft for developing .Net based
applications in supported programming languages usually in C#. It can also be
used to develop ASP Web applications, XML Web services, desktop applications,
and mobile applications. Various supporting programming languages includes,
Visual Basic .NET, Visual C++ .NET, Visual C# .NET, and Visual J# .NET thus,
enabling tools and facilitates sharing for the creation of mixed-language
solutions.

4.1.1 visual s tudio integrated Development e nvironment


(iDe ) f eatures
Various features of Visual Studio along with description are as below:
Table 4.1: Various Features of Visual Studio

Visual Studio
104 IDE Features
“Only for Private Circulation”
C# Programming

NOTES

Visual Studio
IDE Features 105

“Only for Private Circulation”


C# Programming

NOTES

4.2 iNt r ODu c t iON t O w iNDOw f Or Ms

The Microsoft Visual Studio integrated development environment (IDE)


contains two basic window types: tool windows and document windows. These
two window types behave differently as tool windows and document windows
cannot be grouped together in the IDE.
Visual Studio
106 IDE Features
“Only for Private Circulation”
4.2.1 t ool windows C# Programming
Tool windows are listed on the View menu and are defined by the current
application and its add-ins. Developer can arrange tool windows in the IDE to:
NOTES
• Show or hide automatically
• Tab link with other tool windows
• Dock against the edges of the IDE
• Float over
• Display on other monitors
In addition, developer can display more than one instance of certain tool
windows at a time. For example, developer could display more than one Web
browser window. Developer can create another instance of a tool window by
choosing New Window on the Window menu. Also, developer can determine
how the Close and Auto Hide buttons affect a group of tool windows docked
together.

4.2.2 Document windows


Document windows are dynamically created when developer open or create
files or other items. The list of open document windows appears in the Window
menu in the current z-order, with the top-most window listed first.
The ways in which developer manage document windows depends greatly
upon the interface mode selected on the General page of the Environment folder
in the Options dialog box. Developer can choose to work in either Multiple
Document Interface (MDI) or Tabbed Documents mode. Experiment with these
settings to create a document-editing environment that satisfies needs and
preferences.

4.2.3 Dockable windows


In Tabbed Mode, developer can make document windows dockable or
undockable by selecting or clearing Dockable on the Window menu. In MDI
mode, document windows are undockable.

4.2.4 t iled/c ascading windows


Windows can be arranged into cascading stacks or tiled only in MDI mode.

4.2.5 t ab Groups
Tab Groups are available only in Tabbed Documents mode. They extend
ability to manage limited workspace while working with two or more open
documents in the IDE. Developer can organize multiple document windows into
either vertical or horizontal Tab Groups and easily shuffle documents from one
Tab Group to another.
Visual Studio
IDE Features 107

“Only for Private Circulation”


C# Programming 4.2.6 s plit w indows
When developer find needing to be in two places at once in a document,
viewing script in the HEAD of an html document while debugging code in the
NOTES BODY for example, split windows are useful.
To divide document into two independently scrolling sections, choose Split
from the Window menu. Select Remove Split from the Window menu to
eliminate it.

4.2.7 r ecycling windows


In addition, developer can choose to have a document window behave like
a Web browser by displaying each new document as it is opened within the same
window. Choose the option Re-use current document window, if saved, which is
available on the General page under the Environment folder in the Options dialog
box.

4.3 v is u a L s t u DiO c OMPONe Nt s

Microsoft Visual Studio has a code editor with IntelliSense as well as code
refactoring. The integrated debugger works not only as a source-level debugger
but also as a machine-level debugger. Forms designer provided in visual studio
is used for building GUI applications. Web designer, Class designer, and
Database schema designer etc.
Visual Studio also accepts plug-ins to enhance it’s functionality like adding
support for source-control systems (like Subversion and Visual SourceSafe) or
adding new toolsets like editors and visual designers for domain-specific
languages or toolsets for other aspects of the software development lifecycle (like
the Team Foundation Server client: Team Explorer).

4.3.1 c ode e ditor


Microsoft Visual studio consists a code editor that supports syntax
highlighting and code completion using IntelliSense for variables, functions,
methods, loops, and LINQ queries. IntelliSense is supported for the included
languages, as well as for XML, Cascading Style Sheets, and JavaScript when
developing web sites and web applications. Autocomplete suggestions appear in
a modeless list box over the code editor window, in proximity of the editing
cursor. In Visual Studio 2008 onwards, it can be made temporarily semi-
transparent to see the code obstructed by it. The code editor is used for all
supported languages.
A source-code editor is a text editor program designed specifically for
editing source code of computer programs. It may be a standalone application or
Visual Studio it may be built into an integrated development environment (IDE).
108 IDE Features
“Only for Private Circulation”
4.3.2 integrated Debugger C# Programming
Microsoft Visual Studio consists a debugger that works both as a source-
level debugger and as a machine-level debugger. It works with both managed
code as well as native code and can be used for debugging applications written NOTES
in any language supported by Visual Studio.
In addition, it can also attach to running processes, monitor, and debug those
processes. If source code for the running process is available, it displays the code
as it is being run. If source code is not available, it can show the disassembly.
The Visual Studio debugger can also create memory dumps as well as load them
later for debugging. The debugger can be configured to be launched when an
application running outside the Visual Studio environment crashes.
The debugger lets setting breakpoints, which allow execution to be stopped
temporarily at a certain position, and watches which monitor the values of
variables as the execution progresses. The debugger supports Edit and Continue,
which allows code to be edited as it is being debugged.

4.3.3 f orms Designer


Visual Studio includes a host of visual designers to aid in the development
of applications. These tools include:

4.3.3.1 w indows f orms Designer


The Windows Forms designer is used to build GUI applications using
Windows Forms. Layout can be controlled by housing the controls inside other
containers or locking them to the side of the form. Controls that display data (like
textbox, list box and grid view) can be bound to data sources like databases or
queries. Data-bound controls can be created by dragging items from the Data
Sources window onto a design surface. The UI is linked with code using an event-
driven programming model.

4.3.3.2 w indows Presentation f oundation (w Pf ) Designer


The WPF designer supports the drag and drop metaphor. It is used to author
user interfaces targeting Windows Presentation Foundation. It supports all WPF
functionality including data binding and automatic layout management. It
generates XAML code for the UI. The generated XAML file is compatible with
Microsoft Expression Design, the designer-oriented product. The XAML code
is linked with code using a code-behind model.

4.3.3.3 w eb Designer
Visual Studio also includes a web-site editor and designer that allows web
pages to be authored by dragging and dropping widgets. It is used for developing
ASP.NET applications and supports HTML, CSS and JavaScript. It uses a code-
behind model to link with ASP.NET code.
Visual Studio
IDE Features 109

“Only for Private Circulation”


C# Programming 4.3.3.4 c lass Designer
The Class Designer is used to author and edit the classes using UML
modeling. The Class Designer can generate C# and VB.NET code outlines for
NOTES the classes and methods. It can also generate class diagrams from hand-written
classes.

4.3.3.5 Data Designer


The data designer can be used to graphically edit database schemas,
including typed tables, primary and foreign keys and constraints. It can also be
used to design queries from the graphical view.

4.3.3.6 Mapping Designer


The mapping designer is used by LINQ to SQL to design the mapping
between database schemas and the classes that encapsulate the data. The new
solution from ORM approach, ADO.NET Entity Framework, replaces and
improves the old technology.

4.4 c ONt r OLs

As you design and modify the user interface of your Windows Forms
applications, you will need to add, align, and position controls. Controls are
objects that are contained within form objects. Each type of control has its own
set of properties, methods, and events that make it suitable for a particular
purpose. You can manipulate controls in the designer and write code to add
controls dynamically at run time.

f ollowing are commonly used controls of visual s tudio iDe

4.4.1 t extb ox
TextBox controls allow entering text on a form at runtime. By default, it
takes a single line of text, however, you can make it accept multiple texts and
even add scroll bars to it.
User can create a TextBox by dragging a TextBox control from the Toolbox
and dropping it on the form.

4.4.1.1 t he Properties of the t extb ox c ontrol


The following are some of the commonly used properties of the TextBox
control

Visual Studio
110 IDE Features
“Only for Private Circulation”
Table 4.2: Properties of the TextBox Control C# Programming

NOTES

4.4.1.2 Methods of t extb ox c ontrol


The following are some of the commonly used methods of the TextBox
control:
Table 4.3: Methods of TextBox Control

Visual Studio
IDE Features 111

“Only for Private Circulation”


C# Programming

NOTES

4.4.1.3 e vents of the t extb ox c ontrol


The following are some of the commonly used events of the Text control:
Table 4.4: Events of the TextBox Control

4.4.2 Label
In Windows Forms, Label control is used to display text on the form and it
does not take part in user input or in mouse or keyboard events. The Label is a
class and it is defined under System.Windows.Forms namespace.

4.4.2.1 t he Properties of the Label c ontrol


The following are some of the commonly used properties of the Label
control:
Table 4.5: Properties of the Label Control

Visual Studio
112 IDE Features
“Only for Private Circulation”
4.4.2.2 Methods of the Label c ontrol C# Programming
The following are some of the commonly used methods of the Label
control:
NOTES
Table 4.6: Methods of the Label Control

4.4.2.3 e vents of the Label c ontrol


The following are some of the commonly used events of the Label control:
Table 4.7: Events of the Label Control

4.4.3 LinkLabel
A LinkLabel control is a label control that can display a hyperlink. A
LinkLabel control is inherited from the Label class so it has all the functionality
provided by the Windows Forms Label control. LinkLabel control does not
participate in user input or capture mouse or keyboard events.

4.4.3.1 t he Properties of the LinkLabel c ontrol


The following are some of the commonly used properties of the LinkLabel
control:
Table 4.8: Properties of the LinkLabel Control

Visual Studio
IDE Features 113

“Only for Private Circulation”


C# Programming

NOTES

4.4.3.2 t he Methods of the LinkLabel c ontrol


The following are some of the commonly used methods of the LinkLabel
control:
Table 4.9: Methods of the LinkLabel Control

4.4.3.3 t he e vents of the LinkLabel c ontrol


The following are some of the commonly used events of the LinkLabel
control
Table 4.10: Events of the LinkLabel Control

4.4.4 s tatusb ar
The Windows Forms StatusBar Control is used on forms as an area, usually
displayed at the bottom of a window, in which an application can display various
kinds of status information. StatusBar controls can have status bar panels on them
that display text or icons to indicate state, or a series of icons in an animation
that indicate a process is working

Visual Studio
114 IDE Features
“Only for Private Circulation”
4.4.4.1 Properties of s tatusb ar c ontrol C# Programming
Following are the Properties of StatusBar Control
Table 4.11: Properties of StatusBar Control
NOTES

4.4.4.2 Methods of s tatusb ar c ontrol


Following are the Methods of StatusBar Control
Table 4.12: Methods of StatusBar Control

4.4.4.3 e vents of s tatusb ar c ontrol


Following are the events of StatusBar Control
Table 4.13: Events of StatusBar Control

Visual Studio
IDE Features 115
“Only for Private Circula-
C# Programming 4.4.5 c heckedListb ox
This control presents several items in a list. Each item is checkable—the
user can check a box. The CheckedListBox control in Windows Forms is a way
NOTES to make longer, dynamic checkable lists.

4.4.5.1 Properties of c heckedListb ox


Following are important properties of CheckedListBox control:
Table 4.14: Properties of CheckedListBox

Visual Studio
116 IDE Features
“Only for Private Circulation”
C# Programming

NOTES

4.4.5.2 Methods of c heckedListb ox


Following are important methods of CheckedListBox control
Table 4.15: Methods of CheckedListBox

Visual Studio
IDE Features 117

“Only for Private Circulation”


C# Programming 4.4.5.3 e vents of c heckedListb ox
Following are important event of CheckedListBox control:
Table 4.16: Events of CheckedListBox
NOTES

4.4.6 c ombob ox
The ComboBox control is used to display a drop-down list of various items.
It is a combination of a text box in which the user enters an item and a drop-
down list from which the user selects an item.

4.4.6.1 Properties of the c ombob ox c ontrol


The following are some of the commonly used properties of the ComboBox
control:
Table 4.17: Properties of the ComboBox Control

Visual Studio
118 IDE Features
“Only for Private Circulation”
4.4.6.2 Methods of the c ombob ox c ontrol C# Programming
The following are some of the commonly used methods of the ComboBox
control:
NOTES
Table 4.18: Methods of the ComboBox Control

4.4.6.3 e vents of the c ombob ox c ontrol


The following are some of the commonly used events of the ComboBox
control:
Table 4.19: Events of the ComboBox Control

4.4.7 Listb ox c ontrol


The ListBox represents a Windows control to display a list of items to a
user. A user can select an item from the list. It allows the programmer to add
items at design time by using the properties window or at the runtime.

4.4.7.1 Properties of the Listb ox c ontrol


The following are some of the commonly used properties of the ListBox
control:
Table 4.20: Properties of the ListBox Control

Visual Studio
IDE Features 119

“Only for Private Circulation”


C# Programming

NOTES

4.4.7.2 Methods of the Listb ox c ontrol


The following are some of the commonly used methods of the ListBox
control:
Table 4.21: Methods of the ListBox Control

4.4.7.3 e vents of the Listb ox c ontrol


The following are some of the commonly used events of the ListBox
control:
Table 4.22: Events of the ListBox Control

4.4.8 Listview
The ListView control is used to display a list of items. Along with the
TreeView control, it allows you to create a Windows Explorer like interface.

Visual Studio
120 IDE Features
“Only for Private Circulation”
4.4.8.1 Properties of the Listview c ontrol C# Programming
The following are some of the commonly used properties of the ListView
control:
NOTES
Table 4.23: Properties of the ListView Control

4.4.8.2 Methods of the Listview c ontrol


The following are some of the commonly used methods of the ListView
control:
Table 4.24: Methods of the ListView Control

4.4.8.3 e vents of the Listview c ontrol


The following are some of the commonly used events of the ListView
control:
Table 4.25: Events of the ListView Control

Visual Studio
IDE Features 121

“Only for Private Circulation”


C# Programming 4.4.9 r adiob utton
The RadioButton control is used to provide a set of mutually exclusive
options. The user can select one radio button in a group. If you need to place
NOTES more than one group of radio buttons in the same form, you should place them
in different container controls like a GroupBox control.

4.4.9.1 Properties of the r adiob utton c ontrol


The following are some of the commonly used properties of the
RadioButton control:
Table 4.26: Properties of the RadioButton Control

4.4.9.2 Methods of the r adiob utton c ontrol


The following are some of the commonly used methods of the RadioButton
control:
Table 4.27: Methods of the RadioButton Control

4.4.9.3 e vents of the r adiob utton c ontrol


The following are some of the commonly used events of the RadioButton
control:
Table 4.28: Events of the RadioButton Control

4.4.10 b utton
The Button control represents a standard Windows button. It is generally
used to generate a Click event by providing a handler for the Click event.

Visual Studio
122 IDE Features
“Only for Private Circulation”
4.4.10.1 Properties of the b utton c ontrol C# Programming
The following are some of the commonly used properties of the Button
control:
NOTES
Table 4.29: Properties of the Button Control

4.4.10.2 Methods of the b utton c ontrol


The following are some of the commonly used methods of the Button
control:
Table 4.30: Methods of the Button Control

4.4.10.3 e vents of the b utton c ontrol


The following are some of the commonly used events of the Button control:
Table 4.31: Events of the Button Control

4.4.11 Panel
The Panel Control is a container control to host a group of similar child
controls. One of the major uses I have found for a Panel Control is when you
need to show and hide a group of controls. Instead of show and hide individual
controls, you can simply hide and show a single Panel and all child controls. Visual Studio
IDE Features 123

“Only for Private Circulation”


C# Programming 4.4.11.1 Properties of Panel c ontrol
Following are commonly used properties of Panel control
Table 4.32: Properties of Panel Control
NOTES

4.4.11.2 Methods of Panel c ontrol


Following are important methods of Panel control:
Table 4.33: Methods of Panel Control

4.4.11.3 e vents of Panel c ontrol


Following are important events of Panel control:
Table 4.34: Events of Panel Control

4.4.12 Groupb ox
In a GroupBox other controls may be placed. When designing user
Visual Studio interfaces in Windows Forms, you can use this control to create a square shape
124 IDE Features
“Only for Private Circulation”
where you can place other controls. This creates an important level of visual C# Programming
continuity.

4.4.12.1 Properties of Groupb ox c ontrol NOTES


Following are important properties of the GroupBox control:
Table 4.35: Properties of GroupBox Control

4.4.12.2 Methods of Groupb ox c ontrol


Following are important methods of the GroupBox control:
Table 4.36: Methods of GroupBox Control

4.4.12.3 e vents of Groupb ox c ontrol


Following are important events of the GroupBox control:
Table 4.37: Events of GroupBox Control

Visual Studio
IDE Features 125

“Only for Private Circulation”


C# Programming

NOTES

4.4.13 Dialogb ox
There are many built-in dialog boxes to be used in Windows forms for
various tasks like opening and saving files, printing a page, providing choices
for colors, fonts, page setup, etc., to the user of an application. These built-in
dialog boxes reduce the developer's time and workload.
All of these dialog box control classes inherit from the CommonDialog class
and override the RunDialog() function of the base class to create the specific
dialog box.
The RunDialog() function is automatically invoked when a user of a dialog
box calls its ShowDialog() function.
The ShowDialog method is used to display all the dialog box controls at
run-time. It returns a value of the type of DialogResult enumeration. The values
of DialogResult enumeration are −
• Abort − returns DialogResult.Abort value, when user clicks an Abort
button.
• Cancel − returns DialogResult.Cancel, when user clicks a Cancel button.
• Ignore − returns DialogResult.Ignore, when user clicks an Ignore button.
• No − returns DialogResult.No, when user clicks a No button.
• None − returns nothing and the dialog box continues running.
• OK − returns DialogResult.OK, when user clicks an OK button
• Retry − returns DialogResult.Retry , when user clicks an Retry button
• Yes − returns DialogResult.Yes, when user clicks an Yes button

t he following diagram shows the common dialog class inheritance

Visual Studio Fig 4.1: DialogBox Classes in .Net


126 IDE Features
“Only for Private Circulation”
4.4.13.1 c olorDialog C# Programming
The ColorDialog control class represents a common dialog box that displays
available colors along with controls that enable the user to define custom colors.
It lets the user select a color. NOTES
The main property of the ColorDialog control is Color, which returns a
Color object

Properties of the c olorDialog c ontrol


The following are some of the commonly used properties of the
ColorDialog control:
Table 4.38: Properties of the ColorDialog Control

Methods of the c olorDialog c ontrol


The following are some of the commonly used methods of the ColorDialog
control:
Table 4.39: Methods of the ColorDialog Control

e vents of the c olorDialog c ontrol


The following are some of the commonly used events of the ColorDialog
control:
Table 4.40: Events of the ColorDialog Control

Visual Studio
IDE Features 127

“Only for Private Circulation”


C# Programming 4.4.13.2 f ont Dialog
It prompts the user to choose a font from among those installed on the local
computer and lets the user select the font, font size, and color. It returns the Font
NOTES and Color objects.

Properties of the f ontDialog c ontrol


The following are some of the commonly used properties of the FontDialog
control:
Table 4.41: Properties of the FontDialog Control

Methods of the f ontDialog c ontrol


The following are some of the commonly used methods of the FontDialog
control:
Table 4.42: Methods of the FontDialog Control

e vents of the f ontDialog c ontrol


The following are some of the commonly used events of the FontDialog
control:
Table 4.43: Events of the FontDialog Control

Visual Studio
128 IDE Features
“Only for Private Circulation”
4.4.13.3 Open f ile Dialog C# Programming
The OpenFileDialog control prompts the user to open a file and allows the
user to select a file to open. The user can check if the file exists and then open it.
The OpenFileDialog control class inherits from the abstract class FileDialog. NOTES
If the ShowReadOnly property is set to True, then a read-only check box
appears in the dialog box. You can also set the ReadOnlyChecked property to
True, so that the read-only check box appears checked.

Properties of the Open f ile Dialog c ontrol


The following are some of the commonly used properties of the
OpenFileDialog control:
Table 4.44: Properties of the OpenFileDialog Control

Methods of the Openf ileDialog c ontrol


The following are some of the commonly used methods of the
OpenFileDialog control:
Table 4.45: Methods of the OpenFileDialog Control

Visual Studio
IDE Features 129

“Only for Private Circulation”


C# Programming 4.4.13.4 s avef ileDialog
The SaveFileDialog control prompts the user to select a location for saving
a file and allows the user to specify the name of the file to save data. The
NOTES SaveFileDialog control class inherits from the abstract class FileDialog.

Properties of the s avef ileDialog c ontrol


The following are some of the commonly used properties of the
SaveFileDialog control:
Table 4.46: Properties of the SaveFileDialog Control

Methods of the s avef ileDialog c ontrol


The following are some of the commonly used methods of the
SaveFileDialog control:
Table 4.47: Methods of the SaveFileDialog Control

Visual Studio
130 IDE Features
“Only for Private Circulation”
4.4.13.5 PrintDialog C# Programming
The PrintDialog control lets the user to print documents by selecting a
printer and choosing which sections of the document to print from a Windows
Forms application. NOTES
There are various other controls related to printing of documents. Let us
have a brief look at these controls and their purpose. These other controls are −
• The PrintDocument control − it provides support for actual events and
operations of printing in Visual Basic and sets the properties for printing.
• The PrinterSettings control − it is used to configure how a document
is printed by specifying the printer.
• The PageSetUpDialog control − it allows the user to specify page-
related print settings including page orientation, paper size and margin
size.
• The PrintPreviewControl control − it represents the raw preview part
of print previewing from a Windows Forms application, without any
dialog boxes or buttons.
• The PrintPreviewDialog control − it represents a dialog box form that
contains a PrintPreviewControl for printing from a Windows Forms
application.

Properties of the PrintDialog c ontrol


The following are some of the commonly used properties of the PrintDialog
control:
Table 4.48: Properties of the PrintDialog Control

Visual Studio
IDE Features 131

“Only for Private Circulation”


C# Programming Methods of the PrintDialog c ontrol
The following are some of the commonly used methods of the PrintDialog
control:
NOTES
Table 4.49: Methods of the PrintDialog Control

4.4.14 Menu c ontrol


A Menu on a Windows Form is created with a MainMenu object, which is
a collection of MenuItem objects. MainMenu is the container for the Menu
structure of the form and menus are made of MenuItem objects that represent
individual parts of a menu.
You can add menus to Windows Forms at design time by adding the
MainMenu component and then appending menu items to it using the Menu
Designer. In .NET 4.0 or later versions, MenuStrip control has replaced
MainMenu.

Properties of the Menus trip c ontrol


The following are some of the commonly used properties of the MenuStrip
control:
Table 4.50: Properties of the MenuStrip Control

e vents of the Menus trip c ontrol


The following are some of the commonly used events of the MenuStrip
control:
Table 4.51: Events of the MenuStrip Control

Visual Studio
132 IDE Features
“Only for Private Circulation”
e xercise C# Programming
Q.1 What is IDE? State and explain various features of Visual Studio IDE.
Q.2 State and explain various windows of Visual Studio IDE.
NOTES
Q.3 Write important properties, methods, and events of the TextBox
control.
Q.4 What is difference between TextBox and Label control with respect to
properties and methods.
Q.5 Write important properties, methods, and events of the LinkLabel
control.
Q.6 What is role of StatusBar control? Write important properties of the
StatusBar control.
Q.7 Write important properties, methods, and events of the
CheckedListBox control.
Q.8 What is difference between CheckedListBox and ComboBox control
with respect to properties and methods.
Q.9 Write important properties, methods, and events of the ListBox
control.
Q.10 What is difference between ListBox and ListView control with respect
to properties and methods.
Q.11 Write important properties, methods, and events of the RadioButton
control.
Q.12 What is role of Panel control? Write important properties of the Panel
control.
Q.13 Write important properties, methods, and events of the GroupBox
control.
Q.14 What is role of DialogBox control? Write important properties,
methods, and events of the ColorDialog control.
Q.15 Write important properties, methods, and events of the FontDialog
control.
Q.16 What is difference between OpenFileDialog and SaveFileDialog
control with respect to properties and methods.
Q.17 Write important properties, and methods of the PrintDialog control.
Q.18 What is role of MenuStrip control? Write important properties, and
events of the MenuStrip control.

*****
Visual Studio
IDE Features 133

“Only for Private Circulation”


C# Programming

UNIT - V
NOTES
ADO.NET

Learning Objectives
• To introduce students with ADO.Net components such as Namespaces,
Classes, Methods for various databases.
• To introduce students with use of database connections, commands,
adapters, datasets etc.

5.1 t He a DO.Ne t c OMPONe Nt MODe L

ADO.Net is a module of .Net Framework which is used to establish


connection between application and data sources. Data sources can be such as
SQL Server and XML. ADO.NET consists of classes that can be used to connect,
retrieve, insert and delete data.
All the ADO.NET classes are located into System.Data.dll and integrated
with XML classes located into System.Xml.dll.
ADO.NET has two main components that are used for accessing and
manipulating data are the .NET Framework data provider and the DataSet.

Fig. 5.1: ADO.Net Component Model

5.2 a DO.Ne t Dat a Pr Ov iDe r s

Data provider is used to connect to the database, execute commands and


retrieve the record. It is lightweight component with better performance. It also
allows us to place the data into DataSet to use it further in our application.

134 ADO.Net
“Only for Private Circulation”
The .NET Framework provides the following data providers that we can C# Programming
use in our application.
Table 5.1: ADO.Net Data Providers
NOTES

5.2.1 a DO.Net Data Providers Objects


Table 5.2: ADO.Net Data Providers Objects

5.2.1.1 c onnection
It is used to establish a connection to a specific data source. It sets a link
between a data source and ADO.NET. A Connection object sits between a data
source and a DataAdapter. These is need to define a data provider and a data
source when you create a connection. Connection can also be connected to a
Command object to execute SQL queries, which can be used to retrieve, add,
update and delete data to a data source. ach data provider has a Connection class.
Following is the list of the name of various connection classes for data providers.

5.2.1.2 c ommand
The command object is one of the basic components of ADO .NET. It uses
the connection object to execute SQL queries. The queries can be in the Form of ADO.Net 135

“Only for Private Circulation”


C# Programming Inline text, Stored Procedures or direct Table access. It can be used to execute
queries and Stored Procedures with Parameters.
Following are properties associated with the Command class:
NOTES
Table 5.3: Properties Associated with the Command Class

Following are the execute methods associated with the Command class
Table 5.4: Methods Associated with the Command Class

5.2.1.3 Datar eader


A data reader provides an easy way for the programmer to read data from a
database as if it were coming from a stream. The DataReader is the solution for
forward streaming data through ADO.NET. The data reader not only allows you
to move forward through each record of database, but it also enables you to parse
136
the data from each column.
ADO.Net
“Only for Private Circulation”
Similar to other ADO.NET objects, each data provider has a data reader C# Programming
class for example; OleDbDataReader is the data reader class for OleDb data
providers. Similarly, SqlDataReader and ODBC DataReader are data reader
classes for SQL and ODBC data providers, respectively. NOTES

Properties of Data r eader


Table 5.5: Properties of DataReader

Methods of Datar eader


Table 5.6: Methods of DataReader

5.2.1.4 Dataa dapter


DataAdapter provides the communication between the Dataset and the
Datasource. We can use the DataAdapter in combination with the DataSet Object.
DataAdapter provides this combination by mapping Fill method, which changes
the data in the DataSet to match the data in the data source, and Update, which
changes the data in the data source to match the data in the DataSet.
.NET makes two primary data adapters available for use with the databases.
Other data adapters can also be integrated with Visual Studio .NET.

Primary Data a dapters are mentioned below.


• OleDbData Adapter, which is suitable for use with certain OLE DB
providers.
• SQLDataAdapaters, which is specific to a Microsoft SQL server. This is
faster than the OleDBDataAdapter. because it works directly with SQL
servers and does not go through an OLE Db Layer.

Properties of Dataa dapter


We use data adapter objects to act on records from a Data Source. We can
also specify, which action we want to perform by using one of following four
data adapter properties, which executes a SQL statement.

ADO.Net 137

“Only for Private Circulation”


C# Programming The properties are given below.
• Select command retrieves rows from Data Source
• Insert command writes inserted rows from data set into Data Source
NOTES
• Update command writes modified rows from data set into Data Source.
• Delete command deletes rows from Data Source.

Methods used by a data adapter


Actually, we use data adapters to fill or to make changes in a data set table
to a data store. These methods comprises of following.
• Fill: Use this method of a SQL data adapter to add or refresh row from a
Data Source and place them in a Data Set table. The fill method uses
Select statement, which is specified in the Select command property
• Update: Use this method of data adapter object to transmit the changes
to a dataset table to the corresponding Data Source. This method calls
the corresponding insert, delete or update command for each specified
row in a data table in a data set.
• Close: Use this method for the connection to a database.

5.2.2 Datas et
It is a collection of data tables that contain the data. It is used to fetch data
without interacting with a Data Source that's why, it also known as disconnected
data access method. It is an in-memory data store that can hold more than one
table at the same time. We can use DataRelation object to relate these tables. The
DataSet can also be used to read and write data as XML document.

Datas et c onstructors:
Table 5.7: DataSet Constructors

Datas et Properties
Table 5.8 DataSet Properties

138 ADO.Net
“Only for Private Circulation”
C# Programming

NOTES

Datas et Methods
The following table contains some commonly used methods of DataSet.
Table 5.9 DataSet Methods

ADO.Net 139

“Only for Private Circulation”


C# Programming

5.3 c r e at iNG Dat a b a s e c ONNe c t iON


NOTES
The Connection Object is a part of ADO.NET Data Provider and it is a
unique session with the Data Source. The Connection Object is Handling the part
of physical communication between the C# application and the Data Source.
The Connection Object connect to the specified Data Source and open a
connection between the C# application and the Data Source, depends on the
parameter specified in the Connection String . When the connection is
established, SQL Commands will execute with the help of the Connection Object
and retrieve or manipulate data in the Data Source.
Once the Database activity is over , Connection should be closed and release
the Data Source resources
In C# the type of the Connection is depend on which Data Source system
you are working with. The following are the commonly used Connections from
the C# applications:
C# SQL Server Connection
C# OLEDB Connection
C# ODBC Connection

Let us see c # s QL s erver connection: s qlc onnection


It is used to establish an open connection to the SQL Server database. It is
a sealed class so that cannot be inherited. SqlConnection class uses
SqlDataAdapter and SqlCommand classes together to increase performance when
connecting to a Microsoft SQL Server database.
Connection does not close explicitly even it goes out of scope. Therefore,
you must explicitly close the connection by calling Close() method.

s qlc onnection s ignature


public sealed class SqlConnection : System.Data.Common.DbConnection,
ICloneable, IDisposable

s qlc onnection c onstructors


Table 5.10: SqlConnection Constructors

140 ADO.Net
“Only for Private Circula-
s qlc onnection Methods C# Programming
Table 5.11: SqlConnection Methods

NOTES

s qlc onnection e xample


Now, let's create an example that establishes a connection to the SQL Server.
We will consider a student database and will use it to connect.
using System;
using System.Data.SqlClient;
namespace AdoNetConsoleApplication
{
class Program
{
static void Main(string[] args)
{
new Program().Connecting();
}
public void Connecting()
{
SqlConnection con = null;
try
{
// Creating Connection
con = new SqlConnection("data source=.; database=student; integrated
security=SSPI");
con.Open();
ADO.Net 141

“Only for Private Circulation”


C# Programming Console.WriteLine("Connection Established Successfully");
}
catch (Exception e)
NOTES
{
Console.WriteLine("Something went wrong.\n"+e);
}
finally
{ // Closing the connection
con.Close();
}
}
}
}
If we run this code successfully, then following output will generate:

Output
Connection Established Successfully

5.4 Dat a b a s e c OMMa ND

The Command Object in ADO.NET executes SQL statements and Stored


Procedures against the data source specified in the C# Connection Object. The
Command Object requires an instance of a C# Connection Object for executing
the SQL statements.
In order to retrieve a resultset or execute an SQL statement against a Data
Source, first you have to create a Connection Object and open a connection to
the Data Source specified in the connection string. Next step is to assign the open
connection to the connection property of the Command Object. Then the
Command Object can execute the SQL statements. After the execution of the
SQl statement, the Command Object will return a result set. We can retrieve the
result set using a Data Reader
The following are the commonly used Connections from the C#
applications:
C# SQL Server Command
C# OLEDB Command
C# ODBC Command
142 ADO.Net
“Only for Private Circulation”
Let us see C# SQL Server connection: SqlCommand C# Programming
This class is used to store and execute SQL statement for SQL Server
database. It is a sealed class so that cannot be inherited.
NOTES
s qlc ommand s ignature
public sealed class SqlCommand : System.Data.Common.DbCommand,
ICloneable, IDisposable

c onstructors
This class provides the following constructors:
Table 5.12: SqlCommand Constructors

Methods
Table 5.13: SqlCommand Methods

ADO.Net 143
“Only for Private Circula-
C# Programming s qlc ommand e xample
using System;
using System.Data.SqlClient;
NOTES
namespace AdoNetConsoleApplication
{
class Program
{
static void Main(string[] args)
{
new Program().CreateTable();
}
public void CreateTable()
{
SqlConnection con = null;
try
{
// Creating Connection
con = new SqlConnection("data source=.; database=student;
integrated security=SSPI");
// writing sql query
SqlCommand cm = new SqlCommand("select * from student",
con);
// Opening Connection
con.Open();
// Executing the SQL query
SqlDataReader sdr = cm.ExecuteReader();
while (sdr.Read())
{
Console.WriteLine(sdr["name"]+" "+ sdr["email"]);
}
}
catch (Exception e)
{
144 ADO.Net
“Only for Private Circulation”
Console.WriteLine("Something went wrong." + e); C# Programming
}
// Closing the connection
NOTES
finally
{
con.Close();
}
}
}
}
If we run this code successfully, then following output will generate:

Output
Raj raj@gmail.com

5.5 Dat a r e Pe at e r

The DataRepeater control allows you to display rows of your data in a


scrollable container giving you more flexibility and customization than standard
grid controls.
Use of DataRepeater Control in C# Windows Forms
Step 1: Drag and drop DataRepeater control from toolbox on the window
form.

Fig 5.2: DataRepeater Control Design Surface


ADO.Net 145

“Only for Private Circulation”


C# Programming Step 2: Drag and drop textbox in the DataRepeater Control to display data

NOTES

Fig 5.3: Controls Added in DataRepeater Control Design Surface


Step 3: Bind Data in DataRepeater control using C#
using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class frmDataRepeater : Form
{
public frmDataRepeater()
{
InitializeComponent();
}
private void frmDataRepeater_Load(object sender, EventArgs e)
{
//Connect to the Database
string constring = "Server=(local);Database=my; User Id=sa;
Password=sa";
SqlConnection sqlcon = new SqlConnection(constring);
//Open the connection
146 ADO.Net
“Only for Private Circulation”
sqlcon.Open(); C# Programming
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
NOTES
// Write the query
cmd.CommandText = "select * from regform";
da.SelectCommand = cmd;
cmd.Connection = sqlcon;
da.SelectCommand = cmd;
//create a dataset
DataSet ds = new DataSet();
da.Fill(ds);
//Close the connection
sqlcon.Close();
// Bind data to TextBox
textBox1.DataBindings.Add("Text", da, "id");
textBox2.DataBindings.Add("Text", da, "pass");
textBox3.DataBindings.Add("Text", da, "name");
dataRepeater1.Visible = true;
dataRepeater1.DataSource = ds.Tables[0];
}
}
}
When we will build and run this application following output will generate

Fig 5.4: DataRepeater Control Output Window1


ADO.Net 147

“Only for Private Circulation”


C# Programming You can see next data by making scroll bar down

NOTES

Fig 5.5: DataRepeater Control Output Window2

5.6 c ONNe c t iNG t O Dat a s Ou r c e s

In ADO.NET, you use a Connection object to connect to a specific data


source by supplying necessary authentication information in a connection string.
The Connection object you use depends on the type of data source.
Each .NET Framework data provider included with the .NET Framework
has a DbConnection object: the .NET Framework Data Provider for OLE DB
includes an OleDbConnection object, the .NET Framework Data Provider for
SQL Server includes a SqlConnection object, the .NET Framework Data Provider
for ODBC includes an OdbcConnection object, and the .NET Framework Data
Provider for Oracle includes an OracleConnection object.

5.6.1 e stablishing the c onnection


To connect to Microsoft SQL Server, use the SqlConnection object of the
.NET Framework Data Provider for SQL Server. To connect to an OLE DB data
source, use the OleDbConnection object of the .NET Framework Data Provider
for OLE DB. To connect to an ODBC data source, use the OdbcConnection
object of the .NET Framework Data Provider for ODBC. To connect to an Oracle
data source, use the OracleConnection object of the .NET Framework Data
Provider for Oracle.

5.6.2 c losing c onnection


It is always necessary to close the connection when you are finished using
it, so that the connection can be returned to the pool. C# automatically disposes
of the connection when the code exits the block, even in the case of an unhandled
exception. You can also use the Close or Dispose methods of the connection
148 ADO.Net
“Only for Private Circulation”
object for the provider that you are using. Connections that are not explicitly C# Programming
closed might not be added or returned to the pool.
Let us see how to make connections with different databases
NOTES
5.6.3 c onnecting to s QL s erver
The .NET Framework Data Provider for SQL Server supports a connection
string format. The following C# code example demonstrates how to create and
open a connection to a SQL Server database.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
}

5.6.4 c onnecting to an OLe Db Data s ource


The .NET Framework Data Provider for OLE DB provides connectivity to
data sources exposed using OLE DB (through SQLOLEDB, the OLE DB
Provider for SQL Server), using the OleDbConnection object.
For the .NET Framework Data Provider for OLE DB, the connection string
format is identical to the connection string format used in ADO, with the
following exceptions:
• The Provider keyword is required.
• The URL, Remote Provider, and Remote Server keywords are not
supported
The following C# code example demonstrates how to create and open a
connection to an OLE DB data source.
using (OleDbConnection connection = new OleDbConnection
(connectionString))
{
connection.Open();
}

5.6.5 c onnecting to an ODb c Data s ource


The .NET Framework Data Provider for ODBC provides connectivity to
data sources exposed using ODBC using the OdbcConnection object.
The following C# code example demonstrates how to create and open a
connection to an ODBC data source.
using (OdbcConnection connection = new OdbcConnection
(connectionString))
{
connection.Open();
} ADO.Net 149

“Only for Private Circulation”


C# Programming 5.6.6 c onnecting to an Oracle Data s ource
The .NET Framework Data Provider for Oracle provides connectivity to
Oracle data sources using the OracleConnection object.
NOTES
The following C# code example demonstrates how to create and open a
connection to an Oracle data source
using OracleConnection connection = new oracleConnection
connectionString))
{
connection.Open();
// Do work here.
}
OracleConnection nwindConn = new OracleConnection("Data Source=
MyOracleServer; Integrated Security=yes;");
nwindConn.Open();

5.7 c HOOs iNG a .Ne t Dat a Pr Ov iDe r

Data provider is used to connect to the database, execute commands and


retrieve the record. It is lightweight component with better performance. It also
allows us to place the data into DataSet to use it further in our application.
The .NET Framework provides the following data providers that we can
use in our application.
Table 5.14: NET Framework Data Provider

150 ADO.Net
“Only for Private Circulation”
5.7.1 .Ne t f ramework Data Providers Objects C# Programming
Table 5.15: NET Framework Data Provider Objects

NOTES

5.7.2 .Ne t f ramework Data Provider for s QL s erver


Data provider for SQL Server is a lightweight component. It provides better
performance because it directly access SQL Server without any middle
connectivity layer. In early versions, it interacts with ODBC layer before
connecting to the SQL Server that created performance issues.
The .NET Framework Data Provider for SQL Server classes is located in
the System.Data.SqlClient namespace. We can include this namespace in our C#
application by using the following syntax.
using System.Data.SqlClient;
This namespace contains the following important classes.
Table 5.16: Classes under System.Data.SqlClient

5.7.3 .Ne t f ramework Data Provider for OLe Db


It is used to connect with OLE DB. It requires the System.Data.OleDb
namespace.
using System.Data.OleDb ADO.Net 151

“Only for Private Circulation”


C# Programming 5.7.4 .Ne t f ramework Data Provider for Oracle
It is used to connect with Oracle database through Oracle client. The data
provider supports Oracle client software version 8.1.7 or a later version. This
NOTES data provider supports both local and distributed transactions.
Oracle Data Provider classes are located into System.Data.OracleClient
namespace. We must use both System.Data.OracleClient and System.data to
connect our application with the Oracle database.
using System.Data;
using System.Data.OracleClient;

5.7.5 w hich .Ne t f ramework Data Provider is better


Selection of data provider is depends on the design and data source of our
application. Choice of optimum .NET Framework data provider can improve the
performance, capability and integrity of our application. The following table
demonstrates advantages and disadvantages of data provider
Table 5.17: Comparison of Data Providers of .Net Framework

5.8 Ma Na Ge a c ONNe c t iON (c ONNe c t iON POOLiNG)

Creating a database connection is somewhat time-consuming because it


involves the overhead of network-level handshaking and security credentialing
for each new connection request.
ADO.NET uses a technique called connection pooling, which minimizes
the cost of repeatedly opening and closing connections. Connection pooling
reuses existing active connections with the same connection string instead of
creating new connections when a request is made to the database. It involves the
use of a connection manager that is responsible for maintaining a list, or pool, of
available connections for a given connection string. Several pools exist if
different connection strings ask for connection pooling.
152 ADO.Net
“Only for Private Circulation”
You can turn off pooling for a specific connection by including the C# Programming
Pooling=false key-value pair in your connection string. The SqlConnection class
also includes two methods ClearPool and ClearAllPools that let you clear its
associated pool or all pools currently managed by the provider within your NOTES
application respectively.
The following C# example shows a sql connection string with the
connection pooling option:
using System.Data.SqlClient;
namespace ConnectionPooling
{
class Program
{
static void Main(string[] args)
{
string sqlConnectString = "Data Source=localhost;Integrated
security=SSPI;Initial Catalog=AdventureWorks;";
SqlConnection connection = new SqlConnection();
// Set the connection string with pooling option
connection.ConnectionString = sqlConnectString + "Connection
Timeout=30;Connection Lifetime=0;Min Pool Size=0;Max Pool
Size=100;Pooling=true;";
//Open connection
connection.Open();
//Close connection
connection.Close();
}
}
}
A Connection String in the Web.Config file with connection pooling option:
<connectionStrings>
<clear />
<add name="sqlConnectionString" connectionString="Data
Source=mySQLServer;Initial Catalog=myDatabase;Integrated
Security=True;Connection Timeout=15;Connection Lifetime=0;Min Pool
Size=0;Max Pool Size=100;Pooling=true;" />
</connectionStrings>
ADO.Net 153

“Only for Private Circulation”


C# Programming s QL s erver connection string pooling attributes
• Connection Lifetime: Length of time in seconds after creation after which
a connection is destroyed. The default is 0, indicating that connection
NOTES will have the maximum timeout.
• Connection Reset: Specifies whether the connection is reset when
removed from the pool. The default is true.
• Enlist: Specifies whether the connection is automatically enlisted in the
current transaction context of the creation thread if that transaction
context exists. The default is true.
• Load Balance Timeout: Length of time in seconds that a connection can
remain idle in a connection pool before being removed.
• Max Pool Size: Maximum number of connections allowed in the pool.
The default is 100.
• Min Pool Size: Minimum number of connections maintained in the pool.
The default is 0.
• Pooling: When true, the connection is drawn from the appropriate pool,
or if necessary, created and added to the appropriate pool. The default is
true

5.9 b u iLDiNG a ND e Xe c u t iNG c OMMa ND Ob Je c t s

The command object is one of the basic components of ADO .NET.


1. The Command Object uses the connection object to execute SQL
queries.
2. The queries can be in the Form of Inline text, Stored Procedures or
direct Table access.
3. An important feature of Command object is that it can be used to
execute queries and Stored Procedures with Parameters.
4. If a select query is issued, the result set it returns is usually stored in
either a DataSet or a DataReader object.
When creating a Command object, you have the choice of several
constructors. The most useful accepts a CommandText value and a Connection.
Here’s an example with the SqlCommand class:
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(commandText, con);
For standard providers, there are three ways to execute a command:
ExecuteNonQuery( ) , ExecuteReader( ), and ExecuteScalar( ). You choose one
154 ADO.Net of these methods, depending on the type of command you are executing. For

“Only for Private Circulation”


example, ExecuteReader( ) returns a DataReader and provides read-only access C# Programming
to query results.
Some providers include additional members. For example, the ADO.NET
SQL Server provider includes an ExecuteXmlReader( ) method that retrieves NOTES
data as an XML document.

5.9.1 e xecuting a c ommand t hat Doesn’t r eturn r ows


The SQL language includes several nonquery commands. The best known
include UPDATE, DELETE, and INSERT. You can also use other commands to
create, alter, or drop tables, constraints, relations, and so on. To execute any of
these commands, just set the CommandText property with the full SQL statement,
open a connection, and invoke the ExecuteNonQuery( ) method. Consider the
following examples that update, delete, and insert records:

5.9.2 u pdating a r ecord


The UPDATE statement, at its simplest, uses the following syntax:
UPDATE table SET update_expression WHERE search_condition;
The UPDATE expression can thus modify a single record, or it can apply a
change to an entire batch of records in a single table.
Following example puts the UPDATE statement to work with a simple
command that modifies a single field in a single category record in the Northwind
database.
using System;
using System.Data.SqlClient;
public class UpdateRecord
{
public static void Main()
{
string connectionString = "Data Source=localhost;" +
"Initial Catalog=Northwind;Integrated Security=SSPI";
string SQL = "UPDATE Categories SET CategoryName='Beverages'" +
"WHERE CategoryID=1";
// Create ADO.NET objects.
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(SQL, con);
// Execute the command.
con.Open();
ADO.Net 155

“Only for Private Circulation”


C# Programming int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
// Display the result of the operation.
NOTES
Console.WriteLine(rowsAffected.ToString() + " row(s) affected");
}
}
the ExecuteNonQuery( ) method returns the number of rows affected, not
the row itself. In order to see the results of the change, you need to either query
the row or use a tool such as SQL Server’s Enterprise Manager to browse the
database.
If the UPDATE statement fails to update any records because the WHERE
clause is too restrictive, an error isn’t generated. You must examine number of
affected rows to determine if this is this case. If you are adding this logic to a
custom data access component, you might want to raise an exception if this
happens, because it indicates that no update took place.

5.9.3 Deleting a r ecord


The SQL DELETE statement simply specifies a search condition that selects
one or more records to be removed
DELETE FROM table WHERE search_condition;
Modify the previous example to delete a record simply by changing the
SQL variable string SQL = "DELETE FROM Categories WHERE
CategoryID=1";

5.9.4 inserting a r ecord


you can insert a record using a list of column names, followed by a list of
column values in the same order:
INSERT INTO table (column_list) VALUES (value_list);

e xample
string SQL = "INSERT INTO Categories (CategoryName, Description) " +
"VALUES ('Beverages', 'Soft drinks, coffees, teas, beers, and ales')";

5.9.5 e xecuting a c ommand t hat r eturns a s ingle value


ExecuteScalar( ) method returns a single value. If you perform a query, this
will be the first value in the first column of the first row. More likely, you’ll use
ExecuteNonQuery( ) to return an aggregate value, which is the result of a
calculation using a subset of rows.

156 ADO.Net
“Only for Private Circulation”
C# Programming

5.10 b u iLDiNG Dat a s e t s a ND Dat at a b Le s


NOTES
The DataSet represents a subset of the database in memory. That means the
ADO.NET DataSet is a collection of data tables which contains the relational
data in memory in tabular format.
It does not require a continuous open or active connection to the database.
The DataSet is based on the disconnected architecture. This is the reason why it
is used to fetch the data without interacting with any data source

s ignature of Datas et in c #
public class DataSet :
System.ComponentModel.MarshalByValueComponent,
System.ComponentModel.IListSource,
System.ComponentModel.ISupportInitializeNotification, S
System.Runtime.Serialization.ISerializable,
System.Xml.Serialization.IXmlSerializable
Let us understand the how to create and use DataSet with an example. Here,
we want to create two data tables (Customers and Orders) and then we want to
add both these data tables into the DataSet and then we want to log the data into
the console.

5.10.1 c reating c ustomers Data t able


DataTable Customer =new DataTable (“Customer”);
DataColumn CustomerId=new DataColumn(“ID”, typeof(Int32));
Customer.Columns.Add(CustomerId);
DataColumn CustomerName=new DataColumn(“Name”, typeof(string));
Customer.Columns.Add(CustomerName);
DataColumn CustomerMobile=new DataColumn(“Mobile”, typeof(string));
Customer.Columns.Add(CustomerMobile);
Customer.Rows.Add(1, “Yash”, 7558555564);
Customer.Rows.Add(2, “Raj”, 8558545568);
Here, we created one DataTable with the name Customer. Then we created
three data columns and added these three columns into the Customer data table.
Finally, we created two data rows and add these two data rows into the Customer
data table.

ADO.Net 157

“Only for Private Circulation”


C# Programming 5.10.2 c reating Orders Data t able
DataTable Orders =new DataTable (“Orders”);
DataColumn OrderId=new DataColumn(“ID”, typeof(Int32));
NOTES
Customer.Columns.Add(OrderId);
DataColumn CustId=new DataColumn(“CustomerID”, typeof(Int32));
Customer.Columns.Add(CustId);
DataColumn OrderAmount=new DataColumn(“Amount”, typeof(Int32));
Customer.Columns.Add(OrderAmount);
Customer.Rows.Add(101, 1, 10000);
Customer.Rows.Add(102, 2, 85568);
Here, we created the DataTable with the name Orders. Then we created
three data columns (Id, CustomerId, and Amount) and add these three columns
into the Orders table. Finally, we created two data rows and add these data rows
into the Orders table

5.10.3 c reating Datas et with Datat able:


Create a DataSet object and then add the two data table (Customers and
Orders) into the DataSet
DataSet dataset=new DataSet();
Dataset.Tables.Add(Customer);
Dataset.Tables.Add(Orders);
First, we created an instance of the DataSet and then added the two data
tables using the Tables property of DataSet object.

5.10.4 f etch Datat able from Datas et


You can fetch the datatable from a dataset in two ways i.e. using the index
position and using the table name (if provided)

5.10.4.1 f etching Datat able from Datas et using index position


As we first added the Customers table to DataSet, so the Customer table
Index position is 0. If you want to iterate through the Customers table data, then
you could use a foreach loop to iterate
foreach(dataRow row in dataset.Tables[0].Rows)
{
Console.WriteLine(row[“ID”]+”, ”+row[“Name”]+”, ”+row[“Mobile”]);
}

158 ADO.Net
“Only for Private Circulation”
5.10.4.2 f etching Datat able f rom Datas et using Name C# Programming
The second data table that we added to the dataset is Orders and it will be
added at index position 1. Further if you notice while creating the datatable we
have provided a name for the data table i.e. Orders. Now, if you want to fetch NOTES
the data table from the dataset, then you can use the name instead of the index
position.
foreach(dataRow row in dataset.Tables[“Orders”].Rows)
{
Console.WriteLine(row[“ID”]+”, ”+row[“CustomerId”]+”, ”+row[“
Amount”]);
}

5.11 Dat a a Da Pt e r w it H Dat a s e t

A DataAdapter is used to retrieve data from a data source and populate


tables within a DataSet. The DataAdapter also resolves changes made to the
DataSet back to the data source. The DataAdapter uses the Connection object of
the .NET data provider to connect to a data source, and Command objects to
retrieve data from and resolve changes to the data source.

Let us see use of s qlDataa dapter with Datas et in c #:


SqlDataAdapter Class is a part of the C# ADO.NET Data Provider and it
resides in the System.Data.SqlClient namespace. SqlDataAdapter provides the
communication between the Dataset and the SQL database. We can use
SqlDataAdapter Object in combination with Dataset Object. DataAdapter
provides this combination by mapping Fill method, which changes the data in
the DataSet to match the data in the data source, and Update, which changes the
data in the data source to match the data in the DataSet.
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.Fill(ds);
The SqlDataAdapter Object and DataSet objects are combine to perform
both data access and data manipulation operations in the SQL Server Database.
When the user perform the SQL operations like Select , Insert etc. in the data
containing in the Dataset Object , it won't directly affect the Database, until the
user invoke the Update method in the SqlDataAdapter.

c # program that uses s qlDataa dapter type


using System;
using System.Windows.Forms;
ADO.Net 159

“Only for Private Circulation”


C# Programming using System.Data;
using System.Data.SqlClient;
namespace WindowsApplication1
NOTES
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection sqlCnn ;
SqlCommand sqlCmd ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
string sql = null;
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Select * from product";
sqlCnn = new SqlConnection(connetionString);
try
{
sqlCnn.Open();
sqlCmd = new SqlCommand(sql, sqlCnn);
adapter.SelectCommand = sqlCmd;
adapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[0] + " -- "
+ ds.Tables[0].Rows[i].ItemArray[1]);
160 ADO.Net
“Only for Private Circulation”
} C# Programming
adapter.Dispose();
sqlCmd.Dispose();
NOTES
sqlCnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

e xercise
Q.1 Explain with diagram ADO.Net component model.
Q.2 State and explain various ADO.Net Data Providers.
Q.3 Write short Notes on
a) Connection Object
b) Command Object
c) DataReader
d) DataAdapter
Q.4 Write important Properties and Methods of DataSet Object.
Q.5 Write notes on creating database connection and write a C# example
to demonstrate use of SqlConnection.
Q.6 Explain the use of SqlCommand object with example using C#.
Q.7 What is DataRepeater? Explain use of DataRepeater control with C#
example.
Q.8 How Data Sources connected in ADO.Net? Explain.
Q.9 What are the different Data Providers in ADO.Net? Explain.
Q.10 How to manage a database connection in ADO.Net? Explain.
Q.11 Describe Building and Executing Command Objects.
Q.12 Describe Building Datasets and Datatables.
Q.13 How DataAdapter works with DataSet? Explain with example.
******
ADO.Net 161

“Only for Private Circulation”


C# Programming

UNIT - VI
NOTES
MANAGING CONSOLE
I/O OPERATIONS

Learning Objectives
• To introduce students with Console I/O concepts in C#.
• To introduce students with Syntax, Statements, Operators in C#.
• To introduce students with the concepts of error and exception handling
in C#.

6.1 c ONs OLe c La s s

The Console class in C# is used to represent the standard input, output, and
error streams for console applications. In order to implement the user interface
in console applications, Microsoft provided us with a class called Console. The
Console class is available in the “System” namespace. This Console class
provides some methods and properties using which we can implement the user
interface in a console application.
All the properties and methods available in the console class are static. So
we can access these members by using the Console class name.

Properties of c onsole c lass in c #:


Table 6.1: Properties of Console Class in C#

Managing Console
162 I/O Operations
“Only for Private Circulation”
Methods of c onsole class in c #: C# Programming
Table 6.2: Methods of Console Class in C#

NOTES

6.2 c ONs OLe iNPu t

In C#, the simplest method to get input from the user is by using the
ReadLine() method of the Console class. However, Read() and ReadKey() are
also available for getting input from the user. They are also included in Console
class.

6.2.1 Difference between r eadLine(), r ead() and r eadk ey() method:


The difference between ReadLine(), Read() and ReadKey() method is:
• ReadLine(): The ReadLine() method reads the next line of input from
the standard input stream. It returns the same string.
• Read(): The Read() method reads the next character from the standard
input stream. It returns the ascii value of the character. Managing Console
I/O Operations 163

“Only for Private Circulation”


C# Programming • ReadKey(): The ReadKey() method obtains the next key pressed by user.
This method is usually used to hold the screen until user press a key.

NOTES e xample 6.1 Get s tring input f rom u ser


sing System;
namespace Sample
{
class Test
{
public static void Main(string[] args)
{
string testString;
Console.Write("Enter a string - ");
testString = Console.ReadLine();
Console.WriteLine("You entered '{0}'", testString);
}
}
}
When we run the program, the output will be:
Enter a string - Hello World
You entered 'Hello World'

6.2.2 r eading Numeric values (integer and floating point types)


Reading a character or string is very simple in C#. But, reading numeric
values can be slightly tricky in C#. We’ll still use the same ReadLine() method
we used for getting string values. But since the ReadLine() method receives the
input as string, it needs to be converted into integer or floating point type. One
simple approach for converting our input is using the methods of Convert class.
Example 6.2: Reading Numeric Values from User using Convert class
using System;
namespace UserInput
{
class MyClass
{
public static void Main(string[] args)
Managing Console
164 I/O Operations {

“Only for Private Circulation”


string userInput; C# Programming
int intVal;
double doubleVal;
NOTES
Console.Write("Enter integer value: ");
userInput = Console.ReadLine();
/* Converts to integer type */
intVal = Convert.ToInt32(userInput);
Console.WriteLine("You entered {0}",intVal);
Console.Write("Enter double value: ");
userInput = Console.ReadLine();
/* Converts to double type */
doubleVal = Convert.ToDouble(userInput);
Console.WriteLine("You entered {0}",doubleVal);
}
}
}
When we run the program, the output will be:
Enter integer value: 101
You entered 101
Enter double value: 59.412
You entered 59.412

6.3 c ONs OLe Ou t Pu t

In order to output something in C#, we can use


Console.WriteLine() OR
Console.Write()
Here, Console is a class within namespace System and WriteLine and Write
are methods of class Console.

6.3.1 Difference between w riteLine() and w rite() method


The main difference between WriteLine() and Write() is that the Write()
method only prints the string provided to it, while the WriteLine() method prints
the string and moves to the start of next line as well. Managing Console
I/O Operations 165

“Only for Private Circulation”


C# Programming Example 6.3: Use of WriteLine() and Write() methods
using System;
namespace Sample
NOTES
{
class Test
{
public static void Main(string[] args)
{
Console.WriteLine("Prints on ");
Console.WriteLine("New line");
Console.Write("Prints on ");
Console.Write("Same line");
}
}
}
When we run the program, the output will be
Prints on
New line
Prints on Same line

6.4 f Or Mat t e D Ou t Pu t

WriteLine is used to output a line of string in C#. It is often required to


output a integer, string or other variable in a certain way. We need to use
formatting in such cases.
The format parameter in formatting is embedded with zero or more format
specifications of the form "{ N [, M ][: formatString ]}", arg1, ... argN,
where:
N is a zero-based integer indicating the argument to be formatted.
M is an optional integer indicating the width of the region to contain the
formatted value, padded with spaces. If M is negative, the formatted value is left-
justified; if M is positive, the value is right-justified.
formatString is an optional string of formatting codes.
Managing Console
166 I/O Operations
“Only for Private Circulation”
argN is the expression to use at the equivalent position inside the quotes in C# Programming
the string.
Consider the following example to understand it:
NOTES
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("{0,5} {1,5}", 123, 456); // Right-aligned
Console.WriteLine("{0,-5} {1,-5}", 123, 456); // Left-aligned
Console.WriteLine("{0,-10:D6} {1,-10:D6}", 123, 456); // D6 means
6 decimal digits
Console.ReadLine();
}
}
}
If you run the above program you should be able to see an output something
similar to
123 456
123 456
000123 000456

6.4.1 Numeric f ormatting


Standard numeric format strings are used to return strings in commonly
used formats. They take the form X0, in which X is the format specifier and 0 is
the precision specifier. The format specifier can be one of the nine built-in format
characters that define the most commonly used numeric format types.
The following table shows the most common numeric formatting options
in C#:

Managing Console
I/O Operations 167

“Only for Private Circulation”


C# Programming Table 6.3: Common Numeric Formatting Options in C#

NOTES

e xample of common numeric formatting


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int i = 123456;
Console.WriteLine("{0:C}", i); // $123,456.00
Console.WriteLine("{0:D}", i); // 123456
Console.WriteLine("{0:E}", i); // 1.234560E+005
Console.WriteLine("{0:F}", i); // 123456.00
Console.WriteLine("{0:G}", i); // 123456
Console.WriteLine("{0:N}", i); // 123,456.00
Console.WriteLine("{0:P}", i); // 12,345,600.00 %
Managing Console
168 I/O Operations
“Only for Private Circulation”
Console.WriteLine("{0:X}", i); // 1E240 C# Programming
Console.ReadLine();
}
NOTES
}
}
If you run above you should see the following command
$123,456.00
123456
1.234560E+005
123456.00
123456
123,456.00
12,345,600.00 %
1E240

6.4.2 s tandard Numeric f ormat


The standard numeric Format Specifiers can be used to convert numbers to
strings in various formats. There are various formats in which a number can be
converted; the list of format types is:
6.4.2.1 Number ("N") Format Specifier
6.4.2.2 Decimal ("D") Format Specifier
6.4.2.3 Exponential ("E") Format Specifier
6.4.2.4 Percent ("P") Format Specifier
6.4.2.5 Fixed-Point ("F") Format Specifier

6.4.2.1 Number ( "N") f ormat s pecifier


This Format Specifier can be used to convert a number into a string of the
form "-d,ddd,ddd.ddd....." where d represents any number between 0 to 9. The
negative sign represents a negative number and "." denotes the decimal point in
the number and "," denotes the group separator.
Example of Number ( "N") Format Specifier
namespace NumberFormatting
{
class Program
{
Managing Console
static void Main(string[] args) I/O Operations 169

“Only for Private Circulation”


C# Programming {
double dblValue = -12445.6789;
Console.WriteLine("The double value is as : " + dblValue);
NOTES
Console.WriteLine("The Number Formatting is as :"+
dblValue.ToString("N", CultureInfo.InvariantCulture));
}
}
}
If you run above you should see the following command
The double value is as : -12445.6789
The Number Formatting is as:-12,445.68

6.4.2.2 Decimal ("D") f ormat s pecifier


This decimal Format Specifier string can be used to convert a number into
the decimal format string as in:
Example of Decimal ("D") Format Specifier
namespace NumberFormatting
{
class Program
{
static void Main(string[] args)
{
int value= 12345;
Console.WriteLine("The value is :" + value);
Console.WriteLine("The decimal format string is :"+
value.ToString("D"));
Console.WriteLine("The decimal format string with 8 number digits
is as :"+ value.ToString("D8"));
}
}
}
If you run above you should see the following command
The value is : 12345
The decimal format string is : 12345
Managing Console
170 I/O Operations The decimal format string with 8 number digits is as : 00012345

“Only for Private Circulation”


6.4.2.3 e xponential ("e ") f ormat s pecifier C# Programming
The exponential ("E") Format Specifier converts a number to a string of the
form "-d.ddd…E+ddd" or "-d.ddd…e+ddd", where each "d" indicates a digit (0-
9). The string starts with a minus sign if the number is negative NOTES
Example of Exponential ("E") Format Specifier
namespace NumberFormatting
{
class Program
{
static void Main(string[] args)
{
double value = 12345.6789;
Console.WriteLine("The value is as :" + value);
Console.WriteLine("The exponential value is as :" +
value.ToString("E", CultureInfo.InvariantCulture));
}
}
}
If you run above you should see the following command
The value is as : 12345.6789
The exponential value is as : 1.234568E+004

6.4.2.4 Percent ("P") f ormat s pecifier


The percent ("P") Format Specifier multiplies a number by 100 and converts
it to a string that represents a percentage.
Example of Percent ("P") Format Specifier
namespace NumberFormatting
{
class Program
{
static void Main(string[] args)
{
double number = .2468013;
Console.WriteLine("The number is as :" + number);
Managing Console
Console.WriteLine("The percent value is as : "+ number.ToString("P", 171
I/O Operations
“Only for Private Circulation”
C# Programming CultureInfo.InvariantCulture));
}
}
NOTES
}
If you run above you should see the following command
The number is as : 0.2468013
The percent value is as : 24.68 %

6.4.2.5 f ixed-Point ("f ") f ormat s pecifier


The fixed-point ("F) Format Specifier converts a number to a string of the
form "-ddd.ddd…" where each "d" indicates a digit (0-9).
Example of Fixed-Point ("F") Format Specifier
namespace NumberFormatting
{
class Program
{
static void Main(string[] args)
{
int Number = 17843;
Console.WriteLine("The number is as :" + Number);
Console.WriteLine("The fixed point number is as :"+
Number.ToString("F",CultureInfo.InvariantCulture));
}
}
}
If you run above you should see the following command
The number is as : 17843
The fixed point number is as : 17843.00

6.4.3 c ustom Numeric f ormat


ou can use formatting characters to display custom numeric formats for
numeric values. These formats work with a variable’s ToString method as well
as with string.Format.

Managing Console
172 I/O Operations
“Only for Private Circulation”
c ustom Numeric f ormat s pecifiers C# Programming
Table 6.4: Custom Numeric Format Specifiers in C#

NOTES

6.5 Ma Na GiNG e r r Or s a ND e Xc e Pt iONs

An error is a conditon that is not intended in the system. Errors can be of


many types and may creep in any phase of system development. Trapping and
handling of runtime errors is one of the most crucial tasks ahead of any
programmer.
An Error is something that most of the time you cannot handle it. Errors are
unchecked exception and the developer is not required to do anything with these.
Errors normally tend to signal the end of your program, it typically cannot be
recovered from and should cause you exit from current program. It should not
be caught or handled.
All the Errors are Exceptions but the reverse is not true. In general Errors
are which nobody can control or guess when it happened, on the other hand
Exception can be guessed and can be handled

Managing Console
I/O Operations 173

“Only for Private Circulation”


C# Programming

6.6 t y Pe s Of e r r Or s
NOTES
Programming errors are mainly in three categories; Syntax Errors, Run time
Errors and Logic Errors.

6.6.1 s yntax e rrors


Syntax Errors, also known as Compilation errors are the most common type
of errors. Most Syntax errors are caused by mistakes that you make when writing
code. If you are using the coding environment like Visual Studio, it is able to
detect them as soon as you write them, also you can fix them easily as soon as
they occur. When you compile your application in the development environment,
the compiler would point out where the problem is so you can fix it instantly.

6.6.2 Logic e rrors


Your code may compile and run without any Syntax Errors or Run-time
Errors, but the output of an operation may produce unwanted or unexpected
results in response to user actions. These types of errors are called Logic Errors.
That means, Logic errors are those that appear once the application is in use.
These are generally the hardest type to fix, since it is not always clear where they
originate. Also the development environment does not see anything wrong in the
document and therefore cannot point out a problem.

6.6.3 r un-time e rrors


Run-time errors are those that appear only after you compile and run your
code. It will occur when your program attempts an operation that is impossible
to carry out. You can fix most run-time errors by rewriting the faulty code, and
then recompiling and running it.

6.7 e Xc e Pt iONs

An exception is a problem that arises during the execution of a program.


Exceptions are the occurrence of some conditions that changes the normal flow
of execution . Exceptions are occurred in situations like your program run out of
the memory , file does not exist in the given path , network connections are
dropped etc. More specifically for better understanding.
All exceptions the derived from System.Exception class. It is a runtime error
which can be handled. If we don't handle the exception, it prints exception
message and terminates the program. It is always better to write code that handles
exceptions.
Managing Console
174 I/O Operations
“Only for Private Circulation”
6.7.1 e xception c lasses in c # C# Programming
C# exceptions are represented by classes. The exception classes in C# are
mainly directly or indirectly derived from the System.Exception class. Some of
the exception classes derived from the System.Exception class are the NOTES
System.ApplicationException and System.SystemException classes.
The System.ApplicationException class supports exceptions generated by
application programs. Hence the exceptions defined by the programmers should
derive from this class.
The System.SystemException class is the base class for all predefined
system exception.
The following table provides some of the predefined exception classes
derived from the Sytem.SystemException class :
Table 6.5: Important Exception Classes in C#

Managing Console
I/O Operations 175

“Only for Private Circulation”


C# Programming

6.8 e Xc e Pt iON Ha NDLiNG


NOTES
C# provides a structured solution to the exception handling in the form of
try and catch blocks. Using these blocks the core program statements are
separated from the error-handling statements.
These error handling blocks are implemented using the try, catch, finally,
and throw keyword
• try − A try block identifies a block of code for which particular exceptions
is activated. It is followed by one or more catch blocks.
• catch − A program catches an exception with an exception handler at the
place in a program where you want to handle the problem. The catch
keyword indicates the catching of an exception.
• finally − The finally block is used to execute a given set of statements,
whether an exception is thrown or not thrown. For example, if you open
a file, it must be closed whether an exception is raised or not.
• throw − A program throws an exception when a problem shows up. This
is done using a throw keyword.

6.8.1 s yntax of e xception Handling c ode


Assuming a block raises an exception, a method catches an exception using
a combination of the try and catch keywords. A try/catch block is placed around
the code that might generate an exception. Code within a try/catch block is
referred to as protected code, and the syntax for using try/catch looks like the
following –

t ry
{
// statements causing exception
} catch( ExceptionName e1 )
{
// error handling code
} catch( ExceptionName e2 )
{
// error handling code
} catch( ExceptionName eN )
{
Managing Console
176 I/O Operations // error handling code

“Only for Private Circulation”


} finally { C# Programming
// statements to be executed
}
NOTES

e xample of exception handling using try, catch and finaly block:


using System;
namespace ErrorHandlingApplication
{
class DivNumbers
{
int result;
DivNumbers()
{
result = 0;
}
public void division(int num1, int num2)
{
try
{
result = num1 / num2;
}
catch (DivideByZeroException e)
{
Console.WriteLine("Exception caught: {0}", e);
}
Finally
{
Console.WriteLine("Result: {0}", result);
}
}
static void Main(string[] args)
{
DivNumbers d = new DivNumbers();
Managing Console
d.division(25, 0); I/O Operations 177

“Only for Private Circulation”


C# Programming Console.ReadKey();
}
}
NOTES
}
When the above code is compiled and executed, it produces the following
result –
Exception caught: System.DivideByZeroException: Attempted to divide by
zero.at ...
Result: 0

6.9 Mu Lt iPLe c at c H s t at e Me Nt

It is possible to use multiple catch statement in C#. User can write a more
than one catch block for a single try block. The main purpose of the catch block
is to handle the exception raised in the try block. This block is only going to
execute when the exception raised in the program.

In C#, You can use more than one catch block with the try block. Generally,
multiple catch block is used to handle different types of exceptions means each
catch block is used to handle different type of exception. If you use multiple
catch blocks for the same type of exception, then it will give you a compile-time
error because C# does not allow you to use multiple catch block for the same
type of exception. A catch block is always preceded by the try block.

s yntax
try
{
// Your code
}
// 1st catch block
catch(Exception_Name)
{
// Code
}
// 2nd catch block
Managing Console catch(Exception_Name)
178 I/O Operations
“Only for Private Circulation”
{ C# Programming
// Code
}
NOTES
.
.

e xample of Multiple c atch s tatements


namespace ExceptionHandlingDemo
{
class Program
{
static void Main(string[] args)
{
int a, b, c;
Console.WriteLine("ENTER ANY TWO NUBERS");
try
{
a = int.Parse(Console.ReadLine());
b = int.Parse(Console.ReadLine());
c = a / b;
Console.WriteLine("C VALUE = " + c);
}
catch (DivideByZeroException dbze)
{
Console.WriteLine("second number should not be zero");
}
catch (FormatException fe)
{
Console.WriteLine("enter only integer numbers");
}
Console.ReadKey();
}
}
Managing Console
} I/O Operations 179

“Only for Private Circulation”


C# Programming When the above code is compiled and executed, it produces the following
result –

NOTES Output
ENTER ANY TWO NUBERS
5
0
second number should not be zero

6.10 t He e Xc e Pt iON Hie r a r c Hy

In C#, all the exceptions are derived from the base class Exception which
gets further divided into two branches as ApplicationException and another one
is SystemException. SystemException is a base class for all CLR or program
code generated errors. ApplicationException is a base class for all application
related exceptions. All the exception classes are directly or indirectly derived
from the Exception class. In case of ApplicationException, the user may create
its own exception types and classes. But SystemException contains all the known
exception types such as DivideByZeroException or NullReferenceException etc.
Fig 6.1: The Exception Hierarchy

Managing Console
180 I/O Operations
“Only for Private Circulation”
6.10.1 b uilt-in e xception c lasses C# Programming
The following table lists important built-in exception classes in .NET.
Table 6.6: Built-in Exception Classes in C#
NOTES

Managing Console
I/O Operations 181

“Only for Private Circulation”


C# Programming

6.11 Ge Ne r a L c at c H Ha NDLe r
NOTES
A catch block which will catch any exception is called a general catch
handler. A general catch handler does not specify any parameter and can be
written as

try
{
// Statement which causes an exception
}

catch //No parameters


{
//Handles any type of exception
}
catch(Exception e) can handle all the exceptions thrown by the C# code and
therefore can be used as a general catch handler.
If the program uses libraries written in other languages, then there may be
an exception that is not derived from the class Exception. Such exceptions can
be handled by the parameter-less catch statement.
This handler is always placed at the end. Since there is no parameter, it does
not catch any information about the exception and therefore we do not know
what went wrong.

6.12 u s iNG f iNa LLy s t at e Me Nt


Sometimes an exception may cause an error which ends the current method.
However, that method might have opened a file or a network that needs to be
closed. So, to overcome such types of problem, C# provides a special keyword
named as finally keyword. It is a reserved keyword in C#.
The finally block will execute when the try/catch block leaves the execution,
no matter what condition cause it. It always executes whether the try block
terminates normally or terminates due to an exception. The main purpose of
finally block is to release the system resources. The finally block follows
try/catch block.
• In C#, multiple finally blocks in the same program are not allowed.
• The finally block does not contain any return, continue, break statements
Managing Console because it does not allow controls to leave the finally block.
182 I/O Operations
“Only for Private Circulation”
• You can also use finally block only with a try block means without a C# Programming
catch block but in this situation, no exceptions are handled.
• The finally block will be executed after the try and catch blocks, but
before control transfers back to its origin. NOTES

s yntax
try
{
// code...
}
// this is optional
catch
{
// code..
}
finally
{
// code..
}

e xample of finally block


using System;
class Temp
{
static void A()
{
try {
Console.WriteLine("Inside A");
throw new Exception("Throwing Exception");
}
finally
{
Console.WriteLine("A's finally");
}
} Managing Console
I/O Operations 183

“Only for Private Circulation”


C# Programming static void B()
{
Try
NOTES
{
Console.WriteLine("Inside B");
return;
}
finally
{
Console.WriteLine("B's finally");
}
}
// Main Method
public static void Main(String[] args)
{
Try
{
A();
}
catch (Exception)
{
Console.WriteLine("Exception Caught");
}
B();
}
}

Output
Inside A
A's finally
Exception Caught
Inside B
B's finally
Managing Console
184 I/O Operations
“Only for Private Circulation”
Example Using finally block with Handled Exception C# Programming
sing System;
public class Temp
NOTES
{
static public void Main()
{
int number = 4;
int divisor = 0;
try {
int output = number / divisor;
}
catch (DivideByZeroException) {
Console.WriteLine("Not possible to divide by zero!");
}
finally
{
Console.WriteLine("Finally Block!");
}
}
}

Output
Not possible to divide by zero!
Finally Block!

6.13 Ne s t e D t r y b LOc k s

The nesting of the try & catch block is allowed in C#. The nesting of try
block means one try block can be nested into another try block. If an exception
raises in the inner try block that is not caught by the catch block associated with
the try block, then the exception is promoted to the outer try block.
Generally, nested try blocks are used to permit different groups of the error
to be handled in different ways. It is a necessary condition that a try block must
be followed by a catch or finally blocks because if you use a try block without a
catch or finally then you will tend to a compile-time error. Managing Console
I/O Operations 185

“Only for Private Circulation”


C# Programming s yntax
// outer try block
try
NOTES
{
// inner try block
try
{
// code...
}
// inner catch block
catch
{
// code...
}
}
// outer catch block
catch
{
// code...
}

e xample of nested try-catch blocks


using System;
class MultipleCatch2
{
public static void Main(String[] stArr)
{
//Outer try block
try
{
int a = 100, b = 10;
int total = a + b;
try
Managing Console
186 I/O Operations {

“Only for Private Circulation”


int[] arr = {1,2,3,4}; C# Programming
Console.WriteLine("Value ="+arr[5]);
}
NOTES
catch(IndexOutOfRangeException exp)
{
Console.WriteLine("Exception Caught - "+ exp);
}
}
catch(IndexOutOfRangeException exp)
{
Console.WriteLine(exp);
}
}
}

Output
Exception Caught - System.IndexOutOfRangeException: Index was outside
the bounds of the array.
at MultipleCatch2.Main(String[] stArr)

6.14 t Hr Ow iNG Ou r Ow N e Xc e Pt iONs

C# allows us to create user-defined or custom exception. It is used to make


the meaningful exception. To do this, we need to inherit Exception class.
class Program
{
static void Main(string[] args)
{
Student newStudent = null;
try
{
newStudent = new Student();
newStudent.StudentName = "Raj007";
ValidateStudent(newStudent); Managing Console
I/O Operations 187

“Only for Private Circulation”


C# Programming }
catch(InvalidStudentNameException ex)
{
NOTES
Console.WriteLine(ex.Message );
}
Console.ReadKey();
}
private static void ValidateStudent(Student std)
{
Regex regex = new Regex("^[a-zA-Z]+$");
if (!regex.IsMatch(std.StudentName))
throw new InvalidStudentNameException(std.StudentName);
}
}

Output
Invalid Student Name: Raj000

6.15 c He c k e D a ND u Nc He c k e D OPe r at Or s

C# provides checked and unchecked keyword to handle integral type


exceptions. Checked and unchecked keywords specify checked context and
unchecked context respectively. In checked context, arithmetic overflow raises
an exception whereas, in an unchecked context, arithmetic overflow is ignored
and result is truncated.

6.15.1 c # c hecked k eyword


The checked keyword is used to explicitly check overflow and conversion
of integral type values at compile time.
Let's first see an example that does not use checked keyword.
using System;
namespace CSharpProgram
{
class Program
{
Managing Console
188 I/O Operations
“Only for Private Circulation”
static void Main(string[] args) C# Programming
{
int val = int.MaxValue;
NOTES
Console.WriteLine(val + 2);
}
}
}

Output
- 2147483647
The above program produces the wrong result and does not throw any
overflow exception.
Now see, C# Checked Example using checked keyword
using System;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
checked
{
int val = int.MaxValue;
Console.WriteLine(val + 2);
}
}
}
}

Output
Unhandled Exception: System.OverflowException: Arithmetic operation
resulted in an overflow.

6.15.2 c # u nchecked k eyword


The Unchecked keyword ignores the integral type arithmetic exceptions. It
does not check explicitly and produce result that may be truncated or wrong. Managing Console
I/O Operations 189

“Only for Private Circulation”


C# Programming using System;
namespace CSharpProgram
{
NOTES class Program
{
static void Main(string[] args)
{
unchecked
{
int val = int.MaxValue;
Console.WriteLine(val + 2);
}
}
}
}

Output
-2147483647

6.16 u s iNG e Xc e Pt iONs f Or De b u GGiNG

When an exception is thrown while debugging, Visual Studio might or


might not break at this point to show you the exception details. This depends on
your settings in the Exception Settings Window available from Debug | Windows
| Exceptions Setting.

Managing Console Fig 6.2: Exception Settings


190 I/O Operations
“Only for Private Circulation”
• Visual Studio always breaks on second-chance exceptions, even when C# Programming
the CLR Exceptions checkbox is unchecked.
• When the CLR Exceptions checkbox is unchecked, Visual Studio will
break only on second-chance exceptions. NOTES

• When the CLR Exceptions checkbox is checked, Visual Studio will break
on all first-chance exceptions.
• You can expand the CLR Exceptions checkbox to select which first-
chance exceptions Visual Studio should break on:

Fig 6.3: Exception Settings Break-on


In the above case, Visual Studio will not break on System. Application
Exception.
The exception settings window is one of the most important debugging
windows. You should always be aware whether you are currently breaking on
exceptions or not. If you’re experiencing a strange behavior or bug, it’s very
likely exceptions are thrown and you’re just not aware of this because your CLR
exceptions checkbox is off.

e xercise
Q.1 What is use of Console Class? Write important properties and methods
of Console class in c#.
Q.2 What are the input methods in C#? Explain with example.
Q.3 How to read numeric values in C#? Explain with example.
Q.4 What are the input methods in C#? Explain with example.
Q.5 Explain the concept of formatted output with example. Managing Console
I/O Operations 191

“Only for Private Circulation”


C# Programming Q.6 What are the Common Numeric Formatting Options in C#? Explain.
Q.7 Explain various Standard Numeric Format Specifiers used in C#.
Q.8 What are the Custom Numeric Formatting Options in C#? Explain.
NOTES
Q.9 What is Error? Write various types of errors.
Q.10 Define Exception. Write various exception classes used in C#.
Q.11 What blocks are used to handle exceptions in C#? Explain with
example.
Q.12 How to use multiple catch statements in C#? Explain with example.
Q.13 Describe the exception class hierarchy with diagram.
Q.14 Explain the concept of general catch handler.
Q.15 What is use of finally in exception handling? Explain with example.
Q.16 Explain the concept of nested try block with example.
Q.17 What is use of checked and Uncheck keywords in exception handling?
Explain with example.
Q.18 How debugging is done in exception handling? Explain.

*****

Managing Console
192 I/O Operations
“Only for Private Circulation”

You might also like