Event Driven Programming Module - Final
Event Driven Programming Module - Final
Event Driven Programming Module - Final
Developed By:
1. Aderajew Kassie (MSc in Information Technology, Lecturer)
2. Betelhem Zewdu (MSc in Information Technology, Lecturer)
3. Tsegay Mullu (MSc in Information Technology, Lecturer)
Reviewed By:
1. Fikadu Weyessa (MSc in Information Technology, Lecturer)
2. Wubetu Barud (MSc in Information Technology, Assistant Professor)
In chapter two, Introduction to .NET and the .NET Platform and Its Architecture, Framework
libraries, Uses of .NET Platform in Application Development, SDI and MDI Forms, have been
studied weeks 3-4.
In chapter three, you have been studied about Object - Oriented Fundamentals in C#.NET,
Identifiers, C# | Data Types, C# | Variables, C# | Literals, C# | Operators, Control statement, C# |
Class and Object, C# | Constructors, Inheritance, Encapsulation, Abstraction, were studied within
week 5-8.
In chapter four, the overview of Exception Handling, Exception Classes in C#, Handling
Exceptions and types of Exception Handling, In the end, the sample applications, are well studied
within weeks 9-11.
Chapter five is about Manipulating Files, C# I/O Classes and more with examples were studied
within weeks 12-13.
Chapter six is overview of Database Programming, connection of database with graphical user
interface, ADO.NET Architecture, LINQ Architecture, ADO.NET Data Providers, Finally, the
ODBC .NET Data Provider have been discussed within week 14-16
Table of Contents
List of Table ................................................................................................................................................. iii
List of Figure................................................................................................................................................ iv
i
3.6. C# | Operators ............................................................................................................................ 81
3.7. Control statement ....................................................................................................................... 94
3.7.1. C# Decision Making............................................................................................................ 94
3.7.2. Loops in C# ....................................................................................................................... 103
3.8. C# | Class and Object ................................................................................................................ 110
3.8.1. Objects .............................................................................................................................. 111
3.9. C# | Constructors ...................................................................................................................... 114
3.9.1. Types of Constructor ........................................................................................................ 115
3.10. Inheritance................................................................................................................................. 121
ii
List of Table
Table 2. 1 .NET Framework and its compatibility with the different Windows version ............. 35
Table 2. 2 C# key words ............................................................................................................... 37
iii
List of Figure
iv
Chapter 1: Introduction to Software Development
1.1. Overview
Software Development Life Cycle (SDLC) is a process used by the software industry to design, develop
and test high quality software’s. The SDLC aims to produce high-quality software that meets or exceeds
customer expectations, reaches completion within times and cost estimates.
SDLC is a framework defining tasks performed at each step in the software development process.
ISO/IEC 12207 is an international standard for software life-cycle processes. It aims to be the
standard that defines all the tasks required for developing and maintaining software.
What is SDLC?
SDLC is a process followed for a software project, within a software organization. It consists of a detailed
plan describing how to develop, maintain, replace and alter or enhance specific software. The life cycle
defines a methodology for improving the quality of software and the overall development process.
The following figure is a graphical representation of the various stages of a typical SDLC.
Requirement analysis is the most important and fundamental stage in SDLC. It is performed by the senior
members of the team with inputs from the customer, the sales department, market surveys and domain
1
experts in the industry. This information is then used to plan the basic project approach and to conduct
product feasibility study in the economical, operational and technical areas.
Planning for the quality assurance requirements and identification of the risks associated with the project
is also done in the planning stage. The outcome of the technical feasibility study is to define the various
technical approaches that can be followed to implement the project successfully with minimum risks.
Once the requirement analysis is done the next step is to clearly define and document the product
requirements and get them approved from the customer or the market analysts. This is done through
an SRS (Software Requirement Specification) document which consists of all the product
requirements to be designed and developed during the project life cycle.
SRS is the reference for product architects to come out with the best architecture for the product to be
developed. Based on the requirements specified in SRS, usually more than one design approach for the
product architecture is proposed and documented in a DDS - Design Document Specification.
This DDS is reviewed by all the important stakeholders and based on various parameters as risk
assessment, product robustness, design modularity, budget and time constraints, the best design approach
is selected for the product.
A design approach clearly defines all the architectural modules of the product along with its
communication and data flow representation with the external and third party modules (if any). The
internal design of all the modules of the proposed architecture should be clearly defined with the minutest
of the details in DDS.
In this stage of SDLC the actual development starts and the product is built. The programming code is
generated as per DDS during this stage. If the design is performed in a detailed and organized manner,
code generation can be accomplished without much hassle.
Developers must follow the coding guidelines defined by their organization and programming tools like
compilers, interpreters, debuggers, etc. are used to generate the code. Different high level programming
2
languages such as C, C++, Pascal, Java and PHP are used for coding. The programming language is
chosen with respect to the type of software being developed.
This stage is usually a subset of all the stages as in the modern SDLC models, the testing activities are
mostly involved in all the stages of SDLC. However, this stage refers to the testing only stage of the
product where product defects are reported, tracked, fixed and retested, until the product reaches the
quality standards defined in the SRS.
Once the product is tested and ready to be deployed it is released formally in the appropriate market.
Sometimes product deployment happens in stages as per the business strategy of that organization. The
product may first be released in a limited segment and tested in the real business environment (UAT-
User acceptance testing).
Then based on the feedback, the product may be released as it is or with suggested enhancements in the
targeting market segment. After the product is released in the market, its maintenance is done for the
existing customer base.
There are various software development life cycle models defined and designed which are followed
during the software development process. These models are also referred as Software Development
Process Models". Each process model follows a Series of steps unique to its type to ensure success in the
process of software development.
Following are the most important and popular SDLC models followed in the industry −
Waterfall Model
Iterative Model
Spiral Model
V-Model
3
Other related methodologies are Agile Model, RAD Model, Rapid Application Development and
Prototyping Models.
The Waterfall Model was the first Process Model to be introduced. It is also referred to as a linear-
sequential life cycle model. It is very simple to understand and use. In a waterfall model, each phase
must be completed before the next phase can begin and there is no overlapping in the phases.
The Waterfall model is the earliest SDLC approach that was used for software development.
The waterfall Model illustrates the software development process in a linear sequential flow. This means
that any phase in the development process begins only if the previous phase is complete. In this waterfall
model, the phases do not overlap.
Waterfall approach was first SDLC Model to be used widely in Software Engineering to ensure success
of the project. In "The Waterfall" approach, the whole process of software development is divided into
separate phases. In this Waterfall model, typically, the outcome of one phase acts as the input for the next
phase sequentially.
The following illustration is a representation of the different phases of the Waterfall Model.
4
Figure 1. 2 The sequential phases in Waterfall model
Requirement Gathering and analysis − All possible requirements of the system to be developed
are captured in this phase and documented in a requirement specification document.
System Design − the requirement specifications from first phase are studied in this phase and the
system design is prepared. This system design helps in specifying hardware and system
requirements and helps in defining the overall system architecture.
Implementation − with inputs from the system design, the system is first developed in small
programs called units, which are integrated in the next phase. Each unit is developed and tested
for its functionality, which is referred to as Unit Testing.
Integration and Testing − All the units developed in the implementation phase are integrated
into a system after testing of each unit. Post integration the entire system is tested for any faults
and failures.
Deployment of system − Once the functional and non-functional testing is done; the product is
deployed in the customer environment or released into the market.
5
Maintenance − There are some issues which come up in the client environment. To fix those
issues, patches are released. Also to enhance the product some better versions are released.
Maintenance is done to deliver these changes in the customer environment.
All these phases are cascaded to each other in which progress is seen as flowing steadily downwards (like
a waterfall) through the phases. The next phase is started only after the defined set of goals are achieved
for previous phase and it is signed off, so the name "Waterfall Model". In this model, phases do not
overlap.
Ample resources with required expertise are available to support the product.
Easy to manage due to the rigidity of the model. Each phase has specific deliverables and a review
process.
6
Phases are processed and completed one at a time.
Works well for smaller projects where requirements are very well understood.
Not suitable for the projects where requirements are at a moderate to high risk of changing. So,
risk and uncertainty is high with this process model.
Integration is done as a "big-bang. at the very end, which doesn't allow identifying any
technological or business bottleneck or challenges early.
In the Iterative model, iterative process starts with a simple implementation of a small set of the
software requirements and iteratively enhances the evolving versions until the complete system is
implemented and ready to be deployed.
7
An iterative life cycle model does not attempt to start with a full specification of requirements.
Instead, development begins by specifying and implementing just part of the software, which is
then reviewed to identify further requirements. This process is then repeated, producing a new
version of the software at the end of each iteration of the model.
Iterative and Incremental development is a combination of both iterative design or iterative method and
incremental build model for development. "During software development, more than one iteration of the
software development cycle may be in progress at the same time." This process may be described as an
"evolutionary acquisition" or "incremental build" approach."
In this incremental model, the whole requirement is divided into various builds. During each iteration,
the development module goes through the requirements, design, implementation and testing phases. Each
8
subsequent release of the module adds function to the previous release. The process continues till the
complete system is ready as per the requirement.
The key to a successful use of an iterative software development lifecycle is rigorous validation of
requirements, and verification & testing of each version of the software against those requirements within
each cycle of the model. As the software evolves through successive cycles, tests must be repeated and
extended to verify each version of the software
Like other SDLC models, Iterative and incremental development has some specific applications in the
software industry. This model is most often used in the following scenarios −
A new technology is being used and is being learnt by the development team while working on
the project.
Resources with needed skill sets are not available and are planned to be used on contract basis for
specific iterations.
There are some high-risk features and goals which may change in the future.
The advantage of this model is that there is a working model of the system at a very early stage of
development, which makes it easier to find functional or design flaws. Finding issues at an early stage of
development enables to take corrective measures in a limited budget.
The disadvantage with this SDLC model is that it is applicable only to large and bulky software
development projects. This is because it is hard to break a small software system into further small
serviceable increments/modules.
The advantages of the Iterative and Incremental SDLC Model are as follows −
Some working functionality can be developed quickly and early in the life cycle.
9
Results are obtained early and periodically.
Risks are identified and resolved during iteration; and each iteration is an easily managed
milestone.
Issues, challenges and risks identified from each increment can be utilized/applied to the next
increment.
During the life cycle, software is produced early which facilitates customer evaluation and
feedback.
The disadvantages of the Iterative and Incremental SDLC Model are as follows −
Although cost of change is lesser, but it is not very suitable for changing requirements.
System architecture or design issues may arise because not all requirements are gathered in the
beginning of the entire life cycle.
10
Management complexity is more.
The spiral model combines the idea of iterative development with the systematic, controlled aspects of
the waterfall model. This Spiral model is a combination of iterative development process model and
sequential linear development model i.e. the waterfall model with a very high emphasis on risk analysis.
It allows incremental releases of the product or incremental refinement through each iteration around the
spiral.
The spiral model has four phases. A software project repeatedly passes through these phases in iterations
called Spirals.
Identification
This phase starts with gathering the business requirements in the baseline spiral. In the subsequent spirals
as the product matures, identification of system requirements, subsystem requirements and unit
requirements are all done in this phase.
This phase also includes understanding the system requirements by continuous communication between
the customer and the system analyst. At the end of the spiral, the product is deployed in the identified
market.
Design
The Design phase starts with the conceptual design in the baseline spiral and involves architectural design,
logical design of modules, physical product design and the final design in the subsequent spirals.
Construct or Build
The Construct phase refers to production of the actual software product at every spiral. In the baseline
spiral, when the product is just thought of and the design is being developed a POC (Proof of Concept) is
developed in this phase to get customer feedback.
11
Then in the subsequent spirals with higher clarity on requirements and design details a working model of
the software called build is produced with a version number. These builds are sent to the customer for
feedback.
Risk Analysis includes identifying, estimating and monitoring the technical feasibility and management
risks, such as schedule slippage and cost overrun. After testing the build, at the end of first iteration, the
customer evaluates the software and provides feedback.
The following illustration is a representation of the Spiral Model, listing the activities in each
phase.
12
When there is a budget constraint and risk evaluation is important.
New product line which should be released in phases to get enough customer feedback.
Significant changes are expected in the product during the development cycle.
This method is consistent with approaches that have multiple software builds and releases which allows
making an orderly transition to a maintenance activity. Another positive aspect of this method is that the
spiral model forces an early user involvement in the system development effort.
On the other side, it takes a very strict management to complete such products and there is a risk of
running the spiral in an indefinite loop. So, the discipline of change and the extent of taking change
requests is very important to develop and deploy the product successfully.
Development can be divided into smaller parts and the risky parts can be developed earlier which
helps in better risk management.
Not suitable for small or low risk projects and could be expensive for small projects.
Process is complex
The V-model is an SDLC model where execution of processes happens in a sequential manner in a V-
shape. It is also known as Verification and Validation model.
The V-Model is an extension of the waterfall model and is based on the association of a testing phase for
each corresponding development stage. This means that for every single phase in the development cycle,
there is a directly associated testing phase. This is a highly-disciplined model and the next phase starts
only after completion of the previous phase.
V-Model - Design
Under the V-Model, the corresponding testing phase of the development phase is planned in parallel. So,
there are Verification phases on one side of the ‘V’ and Validation phases on the other side. The Coding
Phase joins the two sides of the V-Model.
The following illustration depicts the different phases in a V-Model of the SDLC.
14
Figure 1. 5 V-Model of the SDLC
There are several Verification phases in the V-Model, each of these are explained in detail below.
This is the first phase in the development cycle where the product requirements are understood from the
customer’s perspective. This phase involves detailed communication with the customer to understand his
expectations and exact requirement. This is a very important activity and needs to be managed well, as
most of the customers are not sure about what exactly they need. The acceptance test design planning is
done at this stage as business requirements can be used as an input for acceptance testing.
System Design
Once you have the clear and detailed product requirements, it is time to design the complete system. The
system design will have the understanding and detailing the complete hardware and communication setup
for the product under development. The system test plan is developed based on the system design. Doing
this at an earlier stage leaves more time for the actual test execution later.
15
Architectural Design
Architectural specifications are understood and designed in this phase. Usually more than one technical
approach is proposed and based on the technical and financial feasibility the final decision is taken. The
system design is broken down further into modules taking up different functionality. This is also referred
to as High Level Design (HLD).
The data transfer and communication between the internal modules and with the outside world (other
systems) is clearly understood and defined in this stage. With this information, integration tests can be
designed and documented during this stage.
Module Design
In this phase, the detailed internal design for all the system modules is specified, referred to as Low Level
Design (LLD). It is important that the design is compatible with the other modules in the system
architecture and the other external systems. The unit tests are an essential part of any development process
and helps eliminate the maximum faults and errors at a very early stage. These unit tests can be designed
at this stage based on the internal module designs.
Coding Phase
The actual coding of the system modules designed in the design phase is taken up in the Coding phase.
The best suitable programming language is decided based on the system and architectural requirements.
The coding is performed based on the coding guidelines and standards. The code goes through numerous
code reviews and is optimized for best performance before the final build is checked into the repository.
Validation Phases
Unit Testing
Unit tests designed in the module design phase are executed on the code during this validation phase.
Unit testing is the testing at code level and helps eliminate bugs at an early stage, though all defects
cannot be uncovered by unit testing.
Integration Testing
16
Integration testing is associated with the architectural design phase. Integration tests are performed to
test the coexistence and communication of the internal modules within the system.
System Testing
System testing is directly associated with the system design phase. System tests check the entire system
functionality and the communication of the system under development with external systems. Most of
the software and hardware compatibility issues can be uncovered during this system test execution.
Acceptance Testing
Acceptance testing is associated with the business requirement analysis phase and involves testing the
product in user environment. Acceptance tests uncover the compatibility issues with the other systems
available in the user environment. It also discovers the non-functional issues such as load and
performance defects in the actual user environment.
V- Model ─ Application
V- Model application is almost the same as the waterfall model, as both the models are of sequential
type. Requirements have to be very clear before the project starts, because it is usually expensive to go
back and make changes. This model is used in the medical development field, as it is strictly a disciplined
domain.
The following pointers are some of the most suitable scenarios to use the V-Model application.
Requirements are well defined, clearly documented and fixed.
Product definition is stable.
Technology is not dynamic and is well understood by the project team.
There are no ambiguous or undefined requirements.
The project is short.
The advantage of the V-Model method is that it is very easy to understand and apply. The simplicity of
this model also makes it easier to manage. The disadvantage is that the model is not flexible to changes
and just in case there is a requirement change, which is very common in today’s dynamic world, it
becomes very expensive to make the change.
17
This is a highly-disciplined model and Phases are completed one at a time.
Works well for smaller projects where requirements are very well understood.
Easy to manage due to the rigidity of the model. Each phase has specific deliverables and a review
process.
Not suitable for the projects where requirements are at a moderate to high risk of changing.
Once an application is in the testing stage, it is difficult to go back and change functionality.
The Big Bang model is an SDLC model where we do not follow any specific process. The development
just starts with the required money and efforts as the input, and the output is the software developed
which may or may not be as per customer requirement. This Big Bang Model does not follow a
process/procedure and there is a very little planning required. Even the customer is not sure about what
exactly he wants and the requirements are implemented on the fly without much analysis.
Usually this model is followed for small projects where the development teams are very small.
The Big Bang Model comprises of focusing all the possible resources in the software development and
coding, with very little or no planning. The requirements are understood and implemented as they come.
Any changes required may or may not need to revamp the complete software.
This model is ideal for small projects with one or two developers working together and is also useful for
academic or practice projects. It is an ideal model for the product where requirements are not well
understood and the final release date is not given.
18
Big Bang Model - Pros and Cons
The advantage of this Big Bang Model is that it is very simple and requires very little or no planning.
Easy to manage and no formal procedure are required.
However, the Big Bang Model is a very high risk model and changes in the requirements or
misunderstood requirements may even lead to complete reversal or scraping of the project. It is ideal for
repetitive or small projects with minimum risks.
Agile SDLC model is a combination of iterative and incremental process models with focus on process
adaptability and customer satisfaction by rapid delivery of working software product. Agile Methods
break the product into small incremental builds. These builds are provided in iterations. Each iteration
typically lasts from about one to three weeks. Every iteration involves cross functional teams working
simultaneously on various areas like −
Planning
Requirements Analysis
Design
Coding
19
Unit Testing and
Acceptance Testing.
At the end of the iteration, a working product is displayed to the customer and important stakeholders.
What is Agile?
Agile model believes that every project needs to be handled differently and the existing methods need to
be tailored to best suit the project requirements. In Agile, the tasks are divided to time boxes (small time
frames) to deliver specific features for a release.
Iterative approach is taken and working software build is delivered after each iteration. Each build is
incremental in terms of features; the final build holds all the features required by the customer.
The most popular agile methods include Rational Unified Process (1994), Scrum (1995), Crystal Clear,
Extreme Programming (1996), Adaptive Software Development, Feature Driven Development, and
Dynamic Systems Development Method (DSDM) (1995). These are now collectively referred to as Agile
Methodologies, after the Agile Manifesto was published in 2001.
20
Following are the Agile Manifesto principles −
Working software − Demo working software is considered the best means of communication
with the customers to understand their requirements, instead of just depending on documentation.
Agile is based on the adaptive software development methods, whereas the traditional SDLC models
like the waterfall model is based on a predictive approach. Predictive teams in the traditional SDLC
models usually work with detailed planning and have a complete forecast of the exact tasks and features
to be delivered in the next few months or during the product life cycle.
Predictive methods entirely depend on the requirement analysis and planning done in the beginning
of cycle. Any changes to be incorporated go through a strict change control management and
prioritization.
Agile uses an adaptive approach where there is no detailed planning and there is clarity on future tasks
only in respect of what features need to be developed. There is feature driven development and the team
adapts to the changing product requirements dynamically. The product is tested very frequently, through
the release iterations, minimizing the risk of any major failures in future.
Customer Interaction is the backbone of this Agile methodology, and open communication with
minimum documentation are the typical features of Agile development environment. The agile teams
work in close collaboration with each other and are most often located in the same geographical location.
Agile methods are being widely accepted in the software world recently. However, this method may not
always be suitable for all products. Here are some pros and cons of the Agile model.
21
The advantages of the Agile Model are as follows −
Easy to manage.
An overall plan, an agile leader and agile PM practice is a must without which it will not work.
Strict delivery management dictates the scope, functionality to be delivered, and adjustments to
meet the deadlines.
Depends heavily on customer interaction, so if customer is not clear, team can be driven in the
wrong direction.
There is a very high individual dependency, since there is minimum documentation generated.
Transfer of technology to new team members may be quite challenging due to lack of
documentation.
22
1.1.7. SDLC - RAD Model
The RAD (Rapid Application Development) model is based on prototyping and iterative development
with no specific planning involved. The process of writing the software itself involves the planning
required for developing the product.
What is RAD?
Rapid application development is a software development methodology that uses minimal planning in
favor of rapid prototyping. A prototype is a working model that is functionally equivalent to a component
of the product.
In the RAD model, the functional modules are developed in parallel as prototypes and are integrated to
make the complete product for faster product delivery. Since there is no detailed preplanning, it makes it
easier to incorporate the changes within the development process.
RAD projects follow iterative and incremental model and have small teams comprising of developers,
domain experts, customer representatives and other IT resources working progressively on their
component or prototype.
The most important aspect for this model to be successful is to make sure that the prototypes developed
are reusable.
RAD model distributes the analysis, design, build and test phases into a series of short, iterative
development cycles.
Business Modeling
23
The business model for the product under development is designed in terms of flow of information and
the distribution of information between various business channels. A complete business analysis is
performed to find the vital information for business, how it can be obtained, how and when is the
information processed and what are the factors driving successful flow of information.
Data Modeling
The information gathered in the Business Modeling phase is reviewed and analyzed to form sets of data
objects vital for the business. The attributes of all data sets is identified and defined. The relation between
these data objects are established and defined in detail in relevance to the business model.
Process Modeling
The data object sets defined in the Data Modeling phase are converted to establish the business
information flow needed to achieve specific business objectives as per the business model. The process
model for any changes or enhancements to the data object sets is defined in this phase. Process
descriptions for adding, deleting, retrieving or modifying a data object are given.
Application Generation
The actual system is built and coding is done by using automation tools to convert process and data
models into actual prototypes.
The overall testing time is reduced in the RAD model as the prototypes are independently tested during
every iteration. However, the data flow and the interfaces between all the components need to be
thoroughly tested with complete test coverage. Since most of the programming components have already
been tested, it reduces the risk of any major issues.
24
Figure 1. 7 RAD Model
The traditional SDLC follows a rigid process models with high emphasis on requirement analysis and
gathering before the coding starts. It puts pressure on the customer to sign off the requirements before
the project starts and the customer doesn’t get the feel of the product as there is no working build available
for a long time.
The customer may need some changes after he gets to see the software. However, the change process is
quite rigid and it may not be feasible to incorporate major changes in the product in the traditional SDLC.
The RAD model focuses on iterative and incremental delivery of working models to the customer. This
results in rapid delivery to the customer and customer involvement during the complete development
cycle of product reducing the risk of non-conformance with the actual user requirements.
RAD model can be applied successfully to the projects in which clear modularization is possible. If the
project cannot be broken into modules, RAD may fail.
25
The following pointers describe the typical scenarios where RAD can be used −
RAD should be used only when a system can be modularized to be delivered in an incremental
manner.
It should be used only if the budget permits use of automated code generating tools.
RAD SDLC model should be chosen only if domain experts are available with relevant business
knowledge.
Should be used where the requirements change during the project and working prototypes are to
be presented to customer in small iterations of 2-3 months.
RAD model enables rapid delivery as it reduces the overall development time due to the reusability of
the components and parallel development. RAD works well only if high skilled engineers are available
and the customer is also committed to achieve the targeted prototype in the given time frame. If there is
commitment lacking on either side the model may fail.
26
Dependency on technically strong team members for identifying business requirements.
Inapplicable to cheaper projects as cost of Modelling and automated code generation is very high.
The Software Prototyping refers to building software application prototypes which displays the
functionality of the product under development, but may not actually hold the exact logic of the original
software.
Prototype is a working model of software with some limited functionality. The prototype does not always
hold the exact logic used in the actual software application and is an extra effort to be considered under
effort estimation.
Prototyping is used to allow the users evaluate developer proposals and try them out before
implementation. It also helps understand the requirements which are user specific and may not have been
considered by the developer during product design.
27
This step involves understanding the very basics product requirements especially in terms of user
interface. The more intricate details of the internal design and external aspects like performance and
security can be ignored at this stage.
The initial Prototype is developed in this stage, where the very basic requirements are showcased and
user interfaces are provided. These features may not exactly work in the same manner internally in the
actual software developed. While, the workarounds are used to give the same look and feel to the
customer in the prototype developed.
The prototype developed is then presented to the customer and the other important stakeholders in the
project. The feedback is collected in an organized manner and used for further enhancements in the
product under development.
The feedback and the review comments are discussed during this stage and some negotiations happen
with the customer based on factors like – time and budget constraints and technical feasibility of the
actual implementation. The changes accepted are again incorporated in the new Prototype developed and
the cycle repeats until the customer expectations are met.
Prototypes can have horizontal or vertical dimensions. A Horizontal prototype displays the user interface
for the product and gives a broader view of the entire system, without concentrating on internal functions.
A Vertical prototype on the other side is a detailed elaboration of a specific function or a sub system in
the product.
The purpose of both horizontal and vertical prototype is different. Horizontal prototypes are used to get
more information on the user interface level and the business requirements. It can even be presented in
the sales demos to get business in the market. Vertical prototypes are technical in nature and are used to
get details of the exact functioning of the sub systems. For example, database requirements, interaction
and data processing loads in a given sub system.
There are different types of software prototypes used in the industry. Following are the major software
prototyping types used widely −
28
Throwaway/Rapid Prototyping
Throwaway prototyping is also called as rapid or close ended prototyping. This type of prototyping uses
very little efforts with minimum requirement analysis to build a prototype. Once the actual requirements
are understood, the prototype is discarded and the actual system is developed with a much clear
understanding of user requirements.
Evolutionary Prototyping
Evolutionary prototyping also called as breadboard prototyping is based on building actual functional
prototypes with minimal functionality in the beginning. The prototype developed forms the heart of the
future prototypes on top of which the entire system is built. By using evolutionary prototyping, the well-
understood requirements are included in the prototype and the requirements are added as and when they
are understood.
Incremental Prototyping
Incremental prototyping refers to building multiple functional prototypes of the various sub-systems and
then integrating all the available prototypes to form a complete system.
Extreme Prototyping
Extreme prototyping is used in the web development domain. It consists of three sequential phases. First,
a basic prototype with all the existing pages is presented in the HTML format. Then the data processing
is simulated using a prototype services layer. Finally, the services are implemented and integrated to the
final prototype. This process is called Extreme Prototyping used to draw attention to the second phase of
the process, where a fully functional UI is developed with very little regard to the actual services.
Software Prototyping is most useful in development of systems having high level of user interactions
such as online systems. Systems which need users to fill out forms or go through various screens before
data is processed can use prototyping very effectively to give the exact look and feel even before the
actual software is developed.
Software that involves too much of data processing and most of the functionality is internal with very
little user interface does not usually benefit from prototyping. Prototype development could be an extra
overhead in such projects and may need lot of extra efforts.
Since a working model of the system is displayed, the users get a better understanding of the
system being developed.
Reduces time and cost as the defects can be detected much earlier.
Risk of insufficient requirement analysis owing to too much dependency on the prototype.
Practically, this methodology may increase the complexity of the system as scope of the system
may expand beyond original plans.
Developers may try to reuse the existing prototypes to build the actual system, even when it is not
technically feasible.
The effort invested in building prototypes may be too much if it is not monitored properly.
30
Chapter One Review Questions
31
Chapter 2: Introduction to .NET
2.1. Introduction
.NET is a software framework which is designed and developed by Microsoft. The first version of
.Net framework was 1.0 which came in the year 2002. In easy words, it is a virtual machine for compiling
and executing programs written in different languages like C#, 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 are. It is used to
build applications for Windows, phone, web etc. It provides a lot of functionalities and also supports
industry standards.
.NET is a software framework which is designed and developed by Microsoft. The first versi on of .Net
framework was 1.0 which came in the year 2002. In easy words, it is a virtual machine for compiling
and executing programs written in different languages like C#, VB.Net etc.
It is used to develop Form-based applications, Web-based applications and Web services. There is a
32
variety of programming languages available on the .Net platform, VB.Net and C# being the most
common ones are. It is used to build applications for Windows, phone, web etc. It provides a lot of
functionalities and also supports industry standards.
The first three components from bottom are considered as the basic architecture of .Net framework
which came in the year 2005 and after this more components were added by Microsoft in the .Net
Framework as following:
33
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.
Framework Class Library (FCL): It is the collection of reusable, object-oriented class libraries and
methods etc. that can be integrated with CLR. Also called the Assemblies. It is just like the header
files in C/C++ and packages in the java. Installing .NET framework basically is the installation of
CLR and FCL into the system. Below is the overview of .NET Framework
Types of Applications : Mainly the applications which are built in .Net framework is divided into
the following three categories :
WinForms: Form – Based applications are considered under this category. In simple terms, we
can say client based applications which read and writes the file system comes under this
category.
ASP .NET : Web-Based applications come under this category. ASP.Net is a framework for
web and it provides the awesome integration of HTML, CSS and JavaScript which makes it
useful to develop the web applications, websites and web services. Web services were added
in .Net Framework 2.0 and considered as a part of ASP.NET web applications.
ADO .NET : It includes the application which are developed to communicate with the database
like MS SQL Server, Oracle etc. comes. It mainly consists of classes that can be used to connect,
retrieve, insert and delete data.
WPF (Windows Presentation Foundation) : Windows Presentation Foundation (WPF) is a
graphical subsystem given by Microsoft which uses DirectX and is used in Windows-based
applications for rendering UI (User Interface). WPF was initially released as part of .NET
Framework 3.0 in 2006 and previously known as “Avalon”.
WCF (Windows Communication Foundation) : It is a framework for building connected and
service-oriented applications used to transmit the data as asynchronous from one service endpoint
to another service point. It was previously known as the Indigo.
WF (Windows Workflow Foundation): It is a technology given by Microsoft which provides a
platform for building workflows within .Net applications.
Card Space: It is a Microsoft .NET Framework software client which is designed to let users
provide their digital identity to online services in a secure, simple and trusted way.
34
LINQ (Language Integrated Query): It is introduced in .Net framework version 3.5. Basically, it
is a query language used to make the query for data sources with VB or C# programming languages.
Entity Framework: It is open–source ORM (Object Relational Mapping) based framework which
comes into .Net Framework version 3.5. It enables the .Net developer to work with database using
.Net objects. Before entity framework, .Net developers have performed a lot of things related
database. Like to open a connection to the database, developers have to create a Data Set to fetch or
submit the data to the database, convert data from the Data Set to .NET objects or vice-versa. It
creates the difficulties for developers and also it was the error-prone process, then “Entity
Framework” comes to automate all these database related activities for the application. So, Entity
Framework allows the developers to work at a higher level of abstraction.
Note : REST (Representational State Transfer) and AJAX were added in .Net Framework 3.5 as
an extension and services of ASP.NET for enhancing web services of .NET Framework.
Parallel LINQ (Language Integrated Query) : It comes in .Net Framework version 4.0 and also
termed as PLINQ. It provides a concurrent query execution engine for LINQ. It executes
the LINQ in parallel such that it tries to use as much processing power system on which it is
executing.
TPL (Task Parallel Library): It is a set of public types and APIs. It allows the developers to be
more productive by simplifying the process of adding concurrency and parallelism to .Net
applications.
.NET API for Store/UWP Apps: In 2012, Microsoft added some APIs for creating UWP
(Universal Windows Platform) apps for Windows using C# or VB.
Task-Based Asynchronous Model: It is model used to describe the asynchronous operations and
tasks in .Net Framework.
Is .NET application platform dependent or platform independent?
The combination of Operating System Architecture and CPU Architecture is known as the platform.
Platform dependent means the programming language code will run only on particular Operating System.
A .NET application is platform dependent because of the .NET framework which is only able to run on
the Windows-based operating system. The .Net application is platform independent also because of Mono
framework. Using Mono framework the .Net application can run on any Operating System including
windows. Mono framework is a third party software developed by Novell Company which is now a part
of Micro Focus Company. It is a paid framework.
Table 2. 1 .NET Framework and its compatibility with the different Windows version
35
.NET Version CLR Version Development tool Windows Support
Important Points:
Visual Studio is the development tool which is used to design and develop the .NET applications. For
using Visual Studio, the user has to first install the .NET framework on the system.
In the older version of Windows OS like XP SP1, SP2 or SP3, .NET framework was integrated with the
installation media.
36
Windows 8, 8.1 or 10 do not provide a pre-installed version 3.5 or later of .NET Framework. Therefore,
a version higher than 3.5 must be installed either from a Windows installation media or from the Internet
on demand. Windows update will give recommendations to install the .NET framework.
.NET has an expansive standard set of class libraries, referred to as either the base class libraries (core
set) or framework class libraries (complete set). These libraries provide implementations for many general
and app-specific types, algorithms, and utility functionality. Both commercial and community libraries
build on top of the framework class libraries, providing easy to use, off-the-shelf libraries for a wide set
of computing tasks.
A subset of these libraries are provided with each .NET implementation. Base class library (BCL) APIs
are expected with any .NET implementation, both because developers will want them and because popular
libraries will need them to run. App-specific libraries above the BCL, such as ASP.NET, will not be
available on all .NET implementations.
The BCL provides the most foundational types and utility functionality and is the base of all other .NET
class libraries. The BCL aims to provide general implementations without bias to any workload.
Performance is an important consideration, since apps might prefer a particular policy, such as low-latency
to high-throughput or low-memory to low-CPU usage. The BCL is intended to be high-performance
generally, and take a middle-ground approach according to these various performance concerns. For most
apps, this approach has been quite successful.
.NET includes a set of basic types that are used (to varying degrees) in all programs. These types contain
data, such as numbers, strings, bytes, and arbitrary objects. The C# language includes keywords for these
types. A sample set of these types is listed below, with the matching C# keywords.
37
Type C# Description
keyword
System.Object object The ultimate base class in the CLR type system. It is the root of the type
hierarchy.
System.Int16 short A 16-bit signed integer type. The unsigned UInt16 also exists.
System.Int32 int A 32-bit signed integer type. The unsigned UInt32 also exists.
System.String string Represents a series of characters. Different than a char [], but enables
indexing into each individual char in the string.
CLR is the basic and Virtual Machine component of the .NET Framework. It is the run-time
environment in the .NET Framework that runs the codes and helps in making the development
process easier by providing the various services. Basically, it is responsible for managing the execution
of .NET programs regardless of any .NET programming language. Internally, CLR implements
the VES(Virtual Execution System) which is defined in the Microsoft’s implementation of
the CLI(Common Language Infrastructure). The code that runs under the Common Language Runtime
is termed as the Managed Code. In other words, you can say that CLR provides a managed execution
environment for the .NET programs by improving the security, including the cross language integration
and a rich set of class libraries, etc. CLR is present in every .NET framework version. Below table
illustrate the CLR version in .NET framework.
Below diagram illustrate how CLR is associated with the operating system/hardware along with the
class libraries. Here, the runtime is actually CLR.
38
Figure 2. 2 Role of CLR in the execution of a C# program
Suppose you have written a C# program and save it in a file which is known as the Source Code.
Language specific compiler compiles the source code into the MSIL (Microsoft Intermediate
Language) which is also known as the CIL (Common Intermediate Language) or IL (Intermediate
Language) along with its metadata. Metadata includes all the types, actual implementation of each
function of the program. MSIL is machine-independent code.
Now CLR comes into existence. CLR provides the services and runtime environment to the MSIL
code. Internally CLR includes the JIT (Just-In-Time) compiler which converts the MSIL code to
machine code which further executed by CPU. CLR also uses the .NET Framework class libraries.
Metadata provides information about the programming language, environment, version, and class
libraries to the CLR by which CLR handles the MSIL code. As CLR is common so it allows an
39
instance of a class that written in a different language to call a method of the class which written in
another language.
As the word specify, Common means CLR provides a common runtime or execution environment as
there are more than 60 .NET programming languages.
Common Language Specification (CLS): It is responsible for converting the different .NET
programming language syntactical rules and regulations into CLR understandable format. Basically, it
provides Language Interoperability. Language Interoperability means providing execution support to
other programming languages also in .NET framework.
Language Interoperability can be achieved in two ways:
1. Managed Code: The MSIL code which is managed by the CLR is known as the Managed Code.
For managed code CLR provides three .NET facilities:
2. Unmanaged Code: Before .NET development, programming languages like.COM Components &
Win32 API do not generate the MSIL code. So these are not managed by CLR rather managed by
Operating System
40
Common Type System (CTS): Every programming language has its own data type system, so CTS is
responsible for understanding all the data type systems of .NET programming languages and converting
them into CLR understandable format which will be a common format.
There are 2 Types of CTS that every .NET programming language have:
1. Value Types: Value Types will store the value directly into the memory location. These types work
with stack mechanisms only. CLR allows memory for these at Compile Time.
2. Reference Types: Reference Types will contain a memory address of value because the reference
types won’t store the variable value directly in memory. These types work with Heap mechanism.
CLR allot memory for these at Runtime.
Garbage Collector: It is used to provide the Automatic Memory Management feature. If there was no
garbage collector, programmers would have to write the memory management codes which will be a
kind of overhead on programmers.
JIT (Just In Time Compiler): It is responsible for converting the CIL(Common Intermediate
Language) into machine code or native code using the Common Language Runtime environment.
Benefits of CLR:
It improves the performance by providing a rich interact between programs at run time.
Enhance portability by removing the need of recompiling a program on any operating system that
supports it.
Security also increases as it analyzes the MSIL instructions whether they are safe or unsafe. Also,
the use of delegates in place of function pointers enhance the type safety and security.
Support automatic memory management with the help of Garbage Collector.
Provides cross-language integration because CTS inside CLR provides a common standard that
activates the different languages to extend and share each other’s libraries.
Provides support to use the components that developed in other .NET programming languages.
Provide language, platform, and architecture independence.
It allows easy creation of scalable and multithreaded applications, as the developer has no need to
think about memory management and security issues.
.Net framework architecture consists of Common language infrastructure (CLI), Common language
runtime (CLR), Assemblies, Class library and app Models. It was developed by Microsoft and it was first
released in the year 2002. It mainly supports C#, VB, J#, etc. The code written in .net framework is
41
referred to as managed code. Microsoft has also provided some other implementations or framework for
developing the applications like.Net Microframework, .Net core, etc. Microsoft Visual Studio is used as
IDE for developing the .Net framework applications.
Architecture: .net is having multi-tiered software architecture. It helps in separating the functions
for presentation, processing of application and data management. It is being used for developing
flexible applications. It also provides the advantage of working adding or editing the layers without
being disturbing the whole application.
Gaming: As uses of .net are extremely versatile, it helps the development of gaming applications.
Because of the .net framework responsiveness and having great performance, gaming applications
are better developed in this and remain longer.
Applications: It really helps in the creation of web applications and websites. The applications
are getting mainly developed which can be used in a computer, laptop or mobile easily and with
great performance. It helps in creating the interoperable application which can be used in multiple
platforms. Uses of .Net provide the great features which help the developers or programmers to
develop the application which remains in sync with all the platforms. It is also being used for
developing desktop applications. Many organizations preferred to work on .net because of this
only
Managed: uses of .net provide the managed code, it means whatever the code has been written by
the developers or programmers that is mainly managed code. Outside code written from the .net
framework is referred to as unmanaged code. In .Net code is easy to maintain and simple to write.
The source code and HTML are together in .net is one of the best use and makes the programming
easy.
Performance: uses of .Net provide great performance for each application that is being
developed. It helps in saving the time and effort a lot. It provides the feature because of which
code can be reused and need not write the same code again which helps in the saving the time a
lot and make the application shortened or less heavy, which helps in increasing the performance
and easy to do the deployment and testing for testers as well.
Monitoring and rich features: .net is also used because of its automatic monitoring and other
rich features. DotNet framework keep a regular check from time to time to notice any kind of
issues like leakage of memory, infinite loops, etc. It also helps in destroying these issues atomically
42
and restarts it. There are many features that are being used to develop the applications of .net which
is being provided by the .net framework only. An example is a toolbox, which helps you to drag
and drop and use that element for your application of .net. Any type of database can be used while
developing the application like old, odbc or SQL server. It provides the full freedom to develop
the application the way you want with features like customized elements like a custom grid, the
way you want you can customize the grid.
Consistency and Integrate: uses of the .Net framework also makes sure of providing
consistency to the data by managing and monitoring the processes. The .net framework makes the
application integrated easily across the platforms. It is one of the most popular platforms used for
emails and chat. It makes communication easier and secured across the application.
Community: .Net is having a large community to help regarding the issues and having many
online forums to help out for any queries. There are many companies involved at the small,
medium or large context for .net. There are many resources available that can help to get it started
really fast. The beginners who are currently new to the .Net framework can get the online courses
and many other ways of learning the .net framework because of its wide use across the
organizations and resources availability.
Scalability: .Net framework provides the great scalability for developing the small and large
applications It has been found a great platform for redesigning the small applications in order to
make it with the growing needs of an organization or to make it large as per the client requirements.
43
In some cases, an SDI can also have a toolbar and/or a status bar. Here is an example from Microsoft
Works Spreadsheet:
All these features are left to the programmer to add and configure.
Although Notepad is text-based, an SDI can be any type of application, text, graphics, spreadsheet,
anything. Therefore, to create an SDI, start from a normal form, add a menu to it, and configure it to do
what you want.
To create a document using an SDI, the user launches the application. The SDI then presents a rectangular
window with one frame and the inside is the document the user will use. In most cases, the application
itself creates the document. The user can work on it and do whatever the application allows. To create
another document of the same type, the user must open another instance of the application.
7. From the Dialogs section of the Toolbox, click the OpenFileDialog button and click the form
8. In the Properties window, change its characteristics as follows:
(Name): dlgFileOpen
DefaultExt: rtf
44
Filter: Rich Text Format (*.rtf)|*.rtf|Text Files (*.txt)|*.txt|All Files| Multiselect:True
Title: Open File
9. From the Menus & Toolbars section of the Toolbox, click the MenuStrip button and click the
form
10. In the Properties window, change its (Name) to mnuMain
11. On the form, right-click the menu strip and click Insert Standard Items
12. Under the form, click mnuMain. In the Properties window, click Items and click its browse button
13. Change the names of the items as follows:
15. From the Menus & Toolbars section of the Toolbox, click ToolStrip and click the form
16. While the tool strip is still selected, in the Properties window, change its Name to tbrStandard
17. On the form, right-click the tool strip and click Insert Standard Items
18. Under the form, click tbrStandard. Under the Properties window, click Edit Items
19. Change the names of the items as follows:
newToolStripButton tbrStandardNew
openToolStripButton tbrStandardOpen
saveToolStripButton tbrStandardSave
printToolStripButton tbrStandardPrint
Separator
cutToolStripButton tbrStandardCut
copyToolStripButton tbrStandardCopy
pasteToolStripButton tbrStandardPaste
Separator
helpToolStripButton tbrStandardHelp
20. Click OK
21. From the Menus & Toolbars section of the Toolbox, click StatusStrip and click the form
22. While the tool strip is still selected, in the Properties window, change its Name to stbAppStatus
23. Click the + button of Size and change the Width to 28
24. On the form, to create a section, click the button that displays
46
25. While the new label is still selected, in the Properties window, change the following
characteristics:
(Name):pnlMessage
AutoSize:False
BorderSides:All
BorderStyle:Sunken
DisplayStyle:None
Size -> Width: 200
26. On the form, click the new button on the right side of the previous label
27. While the new label is still selected, in the Properties window, change the following
characteristics:
(Name):pnlStatus
AutoSize:False
BorderSides:All
BorderStyle:Raised
DisplayStyle:None
Size -> Width: 150
28. On the form, click the new button on the right side of the previous label
29. While the new label is still selected, in the Properties window, change the following
characteristics:
(Name):pnlZoom
BorderSides:All
BorderStyle:SunkenOuter
DisplayStyle:None
Spring: True
MDI Fundamentals
A multiple-document interface, MDI, is an application that primarily has a form and a menu. Some,
if not most MDIs also have one or more toolbars and/or a status bar. Here is an example:
47
Like a normal application, to use an MDI, the user must launch it. In some cases, when the application
starts, it is empty; that is, no document is created and the title bar displays a caption, usually the name of
the application.
Usually, there are steps the user must follow to create a document. In some other cases, when the
application is launched, it automatically creates a document. A document resides inside the parent frame
of the application. That is, a child document can use only the area reserved for it. The child document has
its own system icon, its own title bar, and its system buttons (Minimize, Maximize/Restore, and Close).
To use the whole area, the user can maximize the child document. When this is done, the child merges its
title bar with the parent's. The new caption of the title bar becomes made of the text of the parent, followed
by -, and followed by the caption the child window was using. The system buttons of the child document
display under those of the parent frame:
48
Once a document has been created, the user can use it. Normalement, the application must give the user
the ability to create other documents while still using the application. If many documents have been
created, all of them are confined in the frame of the application:
The user can maximize the child forms. If so, the document that was in front occupies the whole area
devoted to child documents. The other child forms stay in the back but become invisible.
One of the differences between an SDI and an MDI is that, because the document and the application don't
share a frame, the user can close the document and keep the application open.
As mentioned already, there is nothing magical with creating an SDI. You start with a form, add a menu
to it, and specify what the application should allow a user to do with a document. As we will see, an MDI
requires more steps.
You start an MDI application with a normal form. You can create a Windows Forms Application using
Microsoft Visual Studio or derive a class from Form. Here is an example:
using System;
using System.Drawing;
using System.Windows.Forms;
49
{
public CommonParent()
{
InitializeComponent();
}
void InitializeComponent()
{
}
[STAThread]
public static int Main()
{
Application.Run(new CommonParent());
return 0;
}
}
The primary form of an MDI application is referred to as the parent or MDI container. It provides the
frame inside of which the documents will reside. To provide this functionality, the Form class is equipped
with a Boolean property named IsMdiContainer. Therefore, after creating the first form of your
application, to indicate that it acts as the main frame, set this property to true. You can do this in the
Properties window if you are visually creating your application, or programmatically. Here is an example:
using System;
using System.Drawing;
using System.Windows.Forms;
50
The primary characteristic of an MDI is that it contains other forms. These forms must be created and
made available to the parent. Each form can be created using a predefined form or you can
programmatically create one by declaring an object of type Form. To allow you to specify that a form has
a parent and will act as a child, the Form class is equipped with a property named MdiParent. This is a
read-write property. The set accessor indicates what form acts as this one's parent. To provide this
information, assign the main form this form's MdiParent. After doing this, you can display the form when
you are ready, by calling its Show() method. Here is an example:
using System;
using System.Drawing;
using System.Windows.Forms;
51
Application: Creating an MDI Application
52
3. To add a new form, on the main menu, click Project -> Add Windows Form...
4. Set the Name to Single Document
5. Click Add
6. From the Common Controls section of the Toolbox, click Rich Textbox and click the form
7. In the Properties window, change the following characteristics:
(Name): rtbNotice
Dock:Fill
Modifiers: Public
8. On the form, click File and double-click New
9. Implement the event as follows:
MDI Characteristics
When you create an MDI application, you must make sure you provide your users with the ability
to create documents. In fact, probably one of your first assignments is to make sure the user can
create as many documents as necessary. As the documents are created, you need a way to
programmatically keep track of the child forms. For example, you can store the documents in a
collection. To assist you with this, the Form class is equipped with a property
named MdiChildren, which is a read-only array. Each element of the MdiChildren [] array is of
type Form. Therefore, to access a child form of an MDI applications, you can pass an index to this
property.
The operating system allows the user to choose among different arrangements. For example, you can
position the documents as vertical columns, as horizontal rows, or as tiles. To support this, the Form class
is equipped with a method named LayoutMdi. Its syntax is:
1. Make sure the Notice form is displaying. Under the form, click mnuMain
2. Under the Properties window, click Edit Items...
3. In the Select Item And Add To List Below, make sure MenuItem is selected and click Add
4. Change its Text to &Window and its (Name) to mnuWindow
55
5. Use the up button to move and position it just above mnuHelp
6. In the Select Item And Add To List Below, make sure MenuItem is selected and click
Add
7. Change its Text to &Window and its (Name) to mnuWindow
8. While mnuWindow is selected, in the right list, click DropDownItems and click its
button
9. Use the same button to create items with the following characteristics:
Text (Name)
&Arrange mnuWindowArrange
&Cascade mnuWindowCascade
Tile &Horizontal mnuWindowTileHorizontal
Tile &Vertical mnuWindowTileVertical
10. Click OK
11. Click OK
12. On the form, click Window and double-click Arrange
13. Implement the event as follows:
56
14. Return to the form
15. Double-click Cascade
16. Implement the event as follows:
Activating a Child
In most MDI applications, a user can create as many documents as necessary. This also means that the
application can hold many child forms. To access a child form, the user can click its title bar. You can
also provide options on a menu item named Window that would display a list of open documents.
The document that is currently active as a brighter title bar. To document this document, the form has a
property named ActiveMdiChild. This read-only property allows you to know what document is the
57
current active one. This property is of type Form, which means its produces a Form object. When you
enquire about this property, if its value is null, it means there is no current active document.
If the value of theActiveMdiChild property is not null, a document is active and you can use it. If you
want to access the objects (Windows controls) that are positioned on a child form, remember that the child
form is somehow foreign. Therefore, you should set the Modifiers property of its hosted controls
appropriately. For example, if you want the parent frame to access a control on the child frame, set the
Modifiers of that control to Public.
9. Click OK
10. On the form, click File and double-click Close
11. Implement the event as follows:
58
private void mnuFileClose_Click(object sender, EventArgs e)
{
SingleDocument document = (SingleDocument)ActiveMdiChild;
In an MDI application, if the user doesn't want to display a document but doesn't want to close it, he can
minimize the window. In the same way, the user can minimize as many child forms as necessary. When a
child form has been minimized, it shows a button in the lower part of the parent. The buttons of the other
minimized child forms are usually positioned next to each other:
59
A user can also close the child form using the Close button of its minimized button. At one time the
minimized buttons may display as a "mess". To let you rearrange them, call the the LayoutMdi method
of the Form class and pass the argument as ArrangeIcons. When you do this, the application will visit
all buttons, if any, that represent minimized child documents, and position them from the left to the right,
adjacently.
2.6. Conclusion
.Net framework is being used widely and most popular among the developers and programmers. It is used
as a first programming language after learning the oops concept. There are a lot of opportunities available
for .net developers and gives a great career path and growth. There are many organizations that used .net
for developing cross-platform applications, which is more powerful and flexible. Its framework is more
robust and rich-featured. It also provides the user-friendly user interface which makes the .net framework
stronger and one of the best product to use.
60
Chapter Two Review Questions
1. What is the .NET framework?
2. What is CLR?
3. What do you know about JIT?
4. What is BCL?
5. What are the different types of constructors in c#?
6. What is caching?
7. What is the application domain?
8. What is a cross-page posting?
9. What are ASP.NET security controls?
10. What are EXE and DLL?
61
Chapter 3: Object - Oriented Fundamentals in C#.NET
3.1. Introduction
Object-oriented programming (OOP) is the core ingredient of the .NET framework. OOP is so important
that, before embarking on the road to .NET, you must understand its basic principles and terminology to
write even a simple program. The fundamental idea behind OOP is to combine into a single unit both data
and the methods that operate on that data; such units are called an object. All OOP languages provide
mechanisms that help you implement the object-oriented model. They are encapsulation, inheritance,
polymorphism and reusability. Let's now take a brief look at these concepts.
3.2. Identifiers
In programming languages, identifiers are used for identification purposes. Or in other words, identifiers
are the user-defined name of the program components. In C#, an identifier can be a class name, method
name, variable name or label.
Example:
62
The only allowed characters for identifiers are all alphanumeric characters ([A-Z], [a-z], [0-9]),
‘_‘(underscore). For example “geek@” is not a valid C# identifier as it contain ‘@’ – special
character.
Identifiers should not start with digits([0-9]). For example “123geeks” is a not a valid in C#
identifier.
Identifiers should not contain white spaces.
Identifiers are not allowed to use as keyword unless they include @ as a prefix. For example, @as is
a valid identifier, but “as” is not because it is a keyword.
C# identifiers allow Unicode Characters.
C# identifiers are case-sensitive.
C# identifiers cannot contain more than 512 characters.
Identifiers does not contain two consecutive underscores in its name because such types of identifiers
are used for the implementation.
Example:
// Simple C# program to illustrate identifiers
using System;
class GFG {
// Main Method
static public void Main()
{
// variable
int a = 10;
int b = 39;
int c;
// simple addition
c = a + b;
Console.WriteLine("The sum of two number is: {0}", c);
}
}
Output:
Below table shows the identifiers and keywords present in the above example:
63
Keywords Identifiers
using GFG
public Main
static a
void b
int c
Signed & Unsigned Integral Types: There are 8 integral types which provide support for 8-bit, 16-
bit, 32-bit, and 64-bit values in signed or unsigned form.
Table 3. 1 Signed & Unsigned Integral Types
64
Type Size( Default
Alias Name Type bits) Range Value
-
32768
System.I signed to
short nt16 integer 16 32767 0
-
sign 263
ed to
System.I signed -231 to System.I inte 6 263 0
Int nt32 integer 32 231-1 0 long nt64 ger 4 -1 L
unsi 0
gne to
unsign d 65
System. ed 0 to ushor System. inte 1 53
byte byte integer 8 255 0 t UInt16 ger 6 5 0
unsi
gne 0
unsign d to
System. ed 0 to System. inte 6 26
uint UInt32 integer 32 232 0 ulong UInt64 ger 4 3 0
Floating Point Types: There are 2 floating point data types which contain the decimal point.
Float: It is 32-bit single-precision floating point type. It has 7 digit Precision. To initialize
a float variable, use the suffix f or F. Like, float x = 3.5F;. If the suffix F or f will not use
then it is treated as double.
Double:It is 64-bit double-precision floating point type. It has 14 – 15 digit Precision. To
initialize a double variable, use the suffix d or D. But it is not mandatory to use suffix because
by default floating data types are the double type.
65
Alias Type name Size(bits) Range (aprox) Default Value
Decimal Types : The decimal type is a 128-bit data type suitable for financial and monetary
calculations. It has 28-29 digit Precision. To initialize a decimal variable, use the suffix m or M. Like
as, decimal x = 300.5m;. If the suffix m or M will not use then it is treated as double.
Character Types : The character types represents a UTF-16 code unit or represents the 16-bit Unicode
character.
// C# program to demonstrate
// the above data types
using System;
namespace ValueTypeTest {
class GeeksforGeeks {
// Main function
static void Main()
{
// declaring character
char a = 'G';
// Integer data type is generally
// used for numeric values
int i = 89;
short s = 56;
66
// long uses Integer values which
// may signed or unsigned
long l = 4564;
ushort us = 76;
// this will give error as number is
// larger than short range
// ulong data type is generally
// used for unsigned integer values
ulong ul = 3624573;
Output :
char: G
integer: 89
short: 56
67
long: 4564
float: 3.733064
double: 8.358674532
decimal: 389.5
Unsinged integer: 95
Unsinged short: 76
Unsinged long: 3624573
Example :
// C# program to demonstrate the Sbyte
// signed integral data type
using System;
namespace ValueTypeTest {
class GeeksforGeeks {
// Main function
static void Main()
{
sbyte a = 126;
// sbyte is 8 bit
// singned value
Console.WriteLine(a);
a++;
Console.WriteLine(a);
Output :
126
127
-128
-127
68
Example :
// C# program to demonstrate
// the byte data type
using System;
namespace ValueTypeTest {
class GeeksforGeeks {
// Main function
static void Main()
{
byte a = 0;
// byte is 8 bit
// unsigned value
Console.WriteLine(a);
a++;
Console.WriteLine(a);
a = 254;
Output :
0
1
255
0
Boolean Types: It has to be assigned either true or false value. Values of type bool are not converted
implicitly or explicitly (with casts) to any other type. But the programmer can easily write conversion
code.
69
Alias Type name Values
Example :
// C# program to demonstrate the
// boolean data type
using System;
namespace ValueTypeTest {
class GeeksforGeeks {
// Main function
static void Main()
{
// boolean data type
bool b = true;
if (b == true)
Console.WriteLine("Hi Geek");
}
}
}
Output:
Hi Geek
Reference Data Types : The Reference Data Types will contain a memory address of variable value
because the reference types won’t store the variable value directly in memory. The built-in reference
types are string, object.
String: It represents a sequence of Unicode characters and its type name is System. String. So,
string and String are equivalent.
Example:
string s1 = "hello"; // creating through string keyword
String s2 = "welcome"; // creating through String class
Object: In C#, all types, predefined and user-defined, reference types and value types, inherit directly
or indirectly from Object. So basically it is the base class for all the data types in C#. Before assigning
values, it needs type conversion. When a variable of a value type is converted to object, it’s
called boxing. When a variable of type object is converted to a value type, it’s called unboxing. Its type
name is System.Object.
Example:
// C# program to demonstrate
70
// the Reference data types
using System;
namespace ValueTypeTest {
class GeeksforGeeks {
// Main Function
static void Main()
{
// declaring string
string a = "Geeks";
//append in a
a+="for";
a = a+"Geeks";
Console.WriteLine(a);
Output :
GeeksforGeeks
20
System.Int32
Pointer Data Type : The Pointer Data Types will contain a memory address of the variable value.
To get the pointer details we have a two symbols ampersand (&) and asterisk (*).
ampersand (&): It is Known as Address Operator. It is used to determine the address of a variable.
asterisk (*): It also known as Indirection Operator. It is used to access the value of an address.
Syntax :
type* identifier;
Example :
int* p1, p; // Valid syntax
int *p1, *p; // Invalid
// Note: This program will not work on
// online compiler
// Error: Unsafe code requires the `unsafe'
// command line option to be specified
// For its solution:
// Go to your project properties page and
// check under Build the checkbox Allow
// unsafe code.
71
using System;
namespace Pointerprogram {
class GFG {
// Main function
static void Main()
{
unsafe
{
// declare variable
int n = 10;
// store variable n address
// location in pointer variable p
int* p = &n;
Console.WriteLine("Value :{0}", n);
Console.WriteLine("Address :{0}", (int)p);
}
}
}
}
3.4. C# | Variables
A typical program uses various values that may change during its execution. For example, a program
that performs some operations on the values entered by the user. The values entered by one user may
differ from those entered by another user. Hence this makes it necessary to use variables as another user
may not use the same values. When a user enters a new value that will be used in the process of
operation, can store temporarily in the Random Access Memory of computer and these values in this
part of memory vary throughout the execution and hence another term for this came which is known
as Variables. So basically, a Variable is a placeholder of the information which can be changed at
runtime. And variables allows to Retrieve and manipulate the stored information.
Syntax:
type variable_name = value;
or
type variable_names;
Example:
char var = 'h'; // Declaring and Initializing character variable
int a, b, c; // Declaring variables a, b and c of int type
Characteristics of Variables:
name : It must be a valid identifier. In above example, var is a valid identifier.
type : It defines the types of information which is to be stored into the variable. In above example
char is a type.
72
value : It is the actual data which is to be stored in the variable. In above example ‘h’ is the value.
Rules for Naming Variables
Variable names can contain the letters ‘a-z’ or ’A-Z’ or digits 0-9 as well as the character ‘_’.
The name of the variables cannot be started with a digit.
The name of the variable cannot be any C# keyword say int, float, null, String, etc.
Examples:
Initializing Variables
The term initializing means to assign some value to the variable. Basically, the actual use of variables
comes under the initialization part. In C# each data type has some default value which is used when
there is no explicitly set value for a given variable. Initialization can be done separately or may be with
declaration.
Example :
int y = 7; // Declaring and initializing the variable at same time
int x; // Declaring variable x
x = 5; // initializing x with value 5
Two Ways for Initialization:
73
2. Run time initialization
It means to provide the value to the variable during the compilation of the program. If the
programmer didn’t provide any value then the compiler will provide some default value to the
variables in some cases. Generally, this type of initialization helpful when the programmer wants
to provide some default value.
Example :
// C# program to demonstrate the
// Compile Time Initialization
using System;
class Geeks {
// Main Method
public static void Main(String []args)
{
Output :
Value of x is 32
Value of y is 0
74
In this, the user has to enter the value and that value is copied to the required variable. In this
type of initialization, there is one more possibility in which value is assigned to variable after
completion of a function call.
Example:
Input : 45
Output : Value of num is 45
Input : 27
Output : Value of num is 27
// C# program to demonstrate the
// Run Time Initialization
using System;
class Geeks {
// Main Method
public static void Main(String []args)
{
// Value will be taken from user
// input and assigned to variable
// num
int num = Convert.ToInt32(Console.ReadLine());
Output :
Value of num is 45
Note: Here the Console.ReadLine() method asks the user to enter the value and later on it puts the same
value in the “num” variable. Hence the value will be displayed according to the user input.
3.5. C# | Literals
The fixed values are called as Literal. Literal is a value that is used by the variables. Values can be
either an integer, float or string, etc.
75
Integer Literals
Floating-point Literals
Character Literals
String Literals
Null Literals
Boolean Literals
Integer Literals: A literal of integer type is known as the integer literal. It can be octal, decimal, binary,
or hexadecimal constant. No prefix is required for the decimal numbers. A suffix can also be used with
the integer literals like U or u are used for unsigned numbers while l or L are used for long numbers. By
default, every literal is of int type. For Integral data types (byte, short, int, long), we can specify literals
in the ways:
Decimal literals (Base 10): In this form, the allowed digits are 0-9.
int x = 101;
Octal literals (Base 8): In this form, the allowed digits are 0-7.
// The octal number should be prefix with 0.
int x = 0146;
Hexa-decimal literals (Base 16): In this form, the allowed digits are 0-9 and characters are a-f. We
can use both uppercase and lowercase characters. As we know that c# is a case-sensitive
programming language but here c# is not case-sensitive.
// The hexa-decimal number should be prefix
// with 0X or 0x.
int x = 0X123Face;
Binary literals (Base 2): In this form, the allowed digits are only 1’s and 0’s.
class Geeks{
// Main method
public static void Main(String[] args)
{
// decimal-form literal
int a = 101;
// octal-form literal
int b = 0145;
// binary-form literal
int x = 0b101;
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Console.WriteLine(x);
}
}
Output
101
145
64206
5
77
Floating-point Literals: The literal which has an integer part, a decimal point, a fractional part, and an
exponent part is known as the floating-point literal. These can be represented either in decimal form or
exponential form.
Examples:
Double d = 3.14145 // Valid
Double d = 312569E-5 // Valid
Double d = 125E // invalid: Incomplete exponent
Double d = 784f // valid
Double d = .e45 // invalid: missing integer or fraction
Program:
class Geeks {
// Main Method
public static void Main(String[] args)
{
// decimal-form literal
double a = 101.230;
Console.WriteLine(a);
Console.WriteLine(b);
}
}
Output:
101.23
123.222
Note: By default, every floating-point literal is of double type and hence we can’t assign directly to
float variable. But we can specify floating-point literal as float type by suffixed with f or F. We can
specify explicitly floating-point literal as the double type by suffixed with d or D, of course, this
convention is not required.
Character Literals: For character data types we can specify literals in 3 ways:
78
Single quote: We can specify literal to char data type as single character within single quote.
char ch = 'a';
Unicode Representation: We can specify char literals in Unicode representation ‘\uxxxx’.
Here xxxx represents 4 hexadecimal numbers.
Char ch = '\n';
\\ \ character
\’ ‘ character
\? ? character
\” ” character
\b Backspace
\a Alert or Bell
\n New Line
\f Form Feed
\r Carriage Return
\v Vertical Tab
Example:
79
// C# program to illustrate the use of char literals
using System;
class Geeks {
// Main Method
public static void Main(String[] args)
{
// character literal within single quote
char ch = 'a';
// Unicode representation
char c = '\u0061';
Console.WriteLine(ch);
Console.WriteLine(c);
a
a
Hello
Geeks!
String Literals: Literals which are enclosed in double quotes(“”) or starts with @”” are known as the
String literals.
Examples:
String s1 = "Hello Geeks!";
String s2 = @"Hello Geeks!";
Program:
// C# program to illustrate the use of String literals
using System;
class Geeks {
// Main Method
public static void Main(String[] args)
{
Output:
Hello Geeks!
Hello Geeks!
Boolean Literals: Only two values are allowed for Boolean literals i.e. true and false.
Example:
bool b = true;
bool c = false;
Program:
// C# program to illustrate the use
// of boolean literals
using System;
class Geeks {
// Main Method
public static void Main(String[] args)
{
bool b = true;
bool c = false;
Console.WriteLine(b);
Console.WriteLine(c);
}
}
Output:
True
False
3.6. C# | Operators
81
Operators are the foundation of any programming language. Thus the functionality of C# language is
incomplete without the use of operators. Operators allow us to perform different kinds of operations
on operands. In C#, operators can be categorized based upon their different functionality:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Conditional Operator
In C#, Operators can also categorized based upon Number of Operands:
Unary Operator: Operator that takes one operand to perform the operation.
Binary Operator: Operator that takes two operands to perform the operation.
Ternary Operator: Operator that takes three operands to perform the operation.
Arithmetic Operators
Modulus: The ‘%’ operator returns the remainder when first operand is divided by the second. For
example, x%y.
Example:
// Main Function
82
static void Main(string[] args)
{
int result;
int x = 10, y = 5;
// Addition
result = (x + y);
Console.WriteLine("Addition Operator: " + result);
// Subtraction
result = (x - y);
Console.WriteLine("Subtraction Operator: " + result);
// Multiplication
result = (x * y);
Console.WriteLine("Multiplication Operator: "+ result);
// Division
result = (x / y);
Console.WriteLine("Division Operator: " + result);
// Modulo
result = (x % y);
Console.WriteLine("Modulo Operator: " + result);
}
}
}
Output:
Addition Operator: 15
Subtraction Operator: 5
Multiplication Operator: 50
Division Operator: 2
Modulo Operator: 0
// post-increment example:
// res is assigned 10 only,
// a is not updated yet
res = a++;
// post-decrement example:
// res is assigned 11 only, a is not updated yet
res = a--;
//a becomes 10 now
Console.WriteLine("a is {0} and res is {1}", a, res);
// pre-increment example:
// res is assigned 11 now since a
// is updated here itself
res = ++a;
// a and res have same values = 11
Console.WriteLine("a is {0} and res is {1}", a, res);
// pre-decrement example:
// res is assigned 10 only since
// a is updated here itself
res = --a;
Output:
a is 11 and res is 10
a is 10 and res is 11
a is 11 and res is 11
84
a is 10 and res is 10
Relational Operators
Relational operators are used for comparison of two values. Let’s see them one by one:
‘=='(Equal To) operator checks whether the two given operands are equal or not. If so, it returns
true. Otherwise it returns false. For example, 5==5 will return true.
‘!='(Not Equal To) operator checks whether the two given operands are equal or not. If not, it
returns true. Otherwise it returns false. It is the exact boolean complement of the ‘==’ operator. For
example, 5!=5 will return false.
‘>'(Greater Than) operator checks whether the first operand is greater than the second operand. If
so, it returns true. Otherwise it returns false. For example, 6>5 will return true.
‘<‘(Less Than) operator checks whether the first operand is lesser than the second operand. If so, it
returns true. Otherwise it returns false. For example, 6<5 will return false.
‘>='(Greater Than Equal To) operator checks whether the first operand is greater than or equal to
the second operand. If so, it returns true. Otherwise it returns false. For example, 5>=5 will return
true.
‘<='(Less Than Equal To) operator checks whether the first operand is lesser than or equal to the
second operand. If so, it returns true. Otherwise it returns false. For example, 5<=5 will also return
true.
Example:
// C# program to demonstrate the working
// of Relational Operators
using System;
namespace Relational {
class GFG {
// Main Function
static void Main(string[] args)
{
bool result;
int x = 5, y = 10;
// Equal to Operator
result = (x == y);
Console.WriteLine("Equal to Operator: " + result);
Output:
Equal to Operator: False
Greater than Operator: False
Less than Operator: True
Greater than or Equal to: False
Lesser than or Equal to: True
Not Equal to Operator: True
Logical Operators
They are used to combine two or more conditions/constraints or to complement the evaluation of the
original condition in consideration. They are described below:
Logical AND: The ‘&&’ operator returns true when both the conditions in consideration are
satisfied. Otherwise it returns false. For example, a && b returns true when both a and b are true
(i.e. non-zero).
Logical OR: The ‘||’ operator returns true when one (or both) of the conditions in consideration is
satisfied. Otherwise it returns false. For example, a || b returns true if one of a or b is true (i.e. non-
zero). Of course, it returns true when both a and b are true.
86
Logical NOT: The ‘!’ operator returns true the condition in consideration is not satisfied. Otherwise
it returns false. For example, !a returns true if a is false, i.e. when a=0.
Example:
// C# program to demonstrate the working
// of Logical Operators
using System;
namespace Logical {
class GFG {
// Main Function
static void Main(string[] args)
{
bool a = true,b = false, result;
// AND operator
result = a && b;
Console.WriteLine("AND Operator: " + result);
// OR operator
result = a || b;
Console.WriteLine("OR Operator: " + result);
// NOT operator
result = !a;
Console.WriteLine("NOT Operator: " + result);
}
}
}
Output:
AND Operator: False
OR Operator: True
NOT Operator: False
Bitwise Operators
In C#, there are 6 bitwise operators which work at bit level or used to perform bit by bit operations.
Following are the bitwise operators:
& (bitwise AND) Takes two numbers as operands and does AND on every bit of two numbers. The
result of AND is 1 only if both bits are 1.
| (bitwise OR) Takes two numbers as operands and does OR on every bit of two numbers. The result
of OR is 1 any of the two bits is 1.
87
^ (bitwise XOR) Takes two numbers as operands and does XOR on every bit of two numbers. The
result of XOR is 1 if the two bits are different.
<< (left shift) Takes two numbers, left shifts the bits of the first operand, the second operand decides
the number of places to shift.
>> (right shift) Takes two numbers, right shifts the bits of the first operand, the second operand
decides the number of places to shift.
Example:
// C# program to demonstrate the working
// of Bitwise Operators
using System;
namespace Bitwise {
class GFG {
// Main Function
static void Main(string[] args)
{
int x = 5, y = 10, result;
// Bitwise OR Operator
result = x | y;
Console.WriteLine("Bitwise OR: " + result);
}
}
}
88
Output:
Bitwise AND: 0
Bitwise OR: 15
Bitwise XOR: 15
Bitwise Complement: -6
Bitwise Left Shift: 20
Bitwise Right Shift: 1
Assignment Operators
Assignment operators are used to assigning a value to a variable. The left side operand of the assignment
operator is a variable and right side operand of the assignment operator is a value. The value on the right
side must be of the same data-type of the variable on the left side otherwise the compiler will raise an
error.
Example:
a = 10;
b = 20;
ch = 'y';
“+=”(Add Assignment): This operator is combination of ‘+’ and ‘=’ operators. This operator first
adds the current value of the variable on left to the value on the right and then assigns the result to
the variable on the left.
Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
“-=” (Subtract Assignment): This operator is combination of ‘-‘and ‘=’ operators. This operator
first subtracts the current value of the variable on left from the value on the right and then assigns
the result to the variable on the left.
Example:
(a -= b) can be written as (a = a - b)
89
If initially value stored in a is 8. Then (a -= 6) = 2.
“*=”(Multiply Assignment): This operator is combination of ‘*’ and ‘=’ operators. This operator
first multiplies the current value of the variable on left to the value on the right and then assigns the
result to the variable on the left.
Example:
(a *= b) can be written as (a = a * b)
“/=”(Division Assignment): This operator is combination of ‘/’ and ‘=’ operators. This operator
first divides the current value of the variable on left by the value on the right and then assigns the
result to the variable on the left.
Example:
(a /= b) can be written as (a = a / b)
If initially value stored in a is 6. Then (a /= 2) = 3 .
“%=”( Modulus Assignment): This operator is combination of ‘%’ and ‘=’ operators. This operator
first modulo the current value of the variable on left by the value on the right and then assigns the
result to the variable on the left.
Example:
(a %= b) can be written as (a = a % b)
If initially value stored in a is 6. Then (a %= 2) = 0.
“<<=”(Left Shift Assignment) : This operator is combination of ‘<<‘ and ‘=’ operators. This
operator first Left shift the current value of the variable on left by the value on the right and then
assigns the result to the variable on the left.
Example:
(a <<= 2) can be written as (a = a << 2)
If initially value stored in a is 6. Then (a <<= 2) = 24.
“>>=”(Right Shift Assignment) : This operator is combination of ‘>>’ and ‘=’ operators. This
operator first Right shift the current value of the variable on left by the value on the right and then
assigns the result to the variable on the left.
Example:
90
(a >>= 2) can be written as (a = a >> 2)
“&=”(Bitwise AND Assignment): This operator is combination of ‘&’ and ‘=’ operators. This
operator first “Bitwise AND” the current value of the variable on the left by the value on the right
and then assigns the result to the variable on the left.
Example:
(a &= 2) can be written as (a = a & 2)
“^=”(Bitwise Exclusive OR): This operator is combination of ‘^’ and ‘=’ operators. This operator
first “Bitwise Exclusive OR” the current value of the variable on left by the value on the right and
then assigns the result to the variable on the left.
Example:
(a ^= 2) can be written as (a = a ^ 2)
Example:
(a |= 2) can be written as (a = a | 2)
Example:
// C# program to demonstrate the working
// of Assignment Operators
using System;
namespace Assignment {
class GFG {
// Main Function
static void Main(string[] args)
{
// initialize variable x
// using Simple Assignment
// Operator "="
91
int x = 15;
// it means x = x + 10
x += 10;
Console.WriteLine("Add Assignment Operator: " + x);
92
// initialize variable x again
x = 12;
// it means x = x >> 4
x |= 4;
Console.WriteLine("Bitwise Inclusive OR Assignment Operator: " + x);
}
}
}
Output :
Conditional Operator
It is ternary operator which is a shorthand version of if-else statement. It has three operands and hence
the name ternary. It will return one of two values depending on the value of a Boolean expression.
Syntax:
condition ? first_expression : second_expression;
Explanation:
condition: It must be evaluated to true or false. If the condition is true first_expression is evaluated and
becomes the result. If the condition is false, second_expression is evaluated and becomes the result.
Example:
Output :
Result: 10
Result: 5
Decision making in programming is similar to decision making in real life. In programming too, a certain
block of code needs to be executed when some condition is fulfilled. A programming language uses
control statements to control the flow of execution of program based on certain conditions. These are
used to cause the flow of execution to advance and branch based on changes to the state of a program.
if
if-else
if-else-if
Nested if
Switch
94
Nested switch
IF Statement
The if statement checks the given condition. If the condition evaluates to be true then the block
of code/statements will execute otherwise not.
Syntax:
if(condition)
{
//code to be executed
}
Note: If the curly brackets { } are not used with if statements than the statement just next to it is only
considered associated with the if statement.
Example:
if (condition)
statement 1;
statement 2;
In this example, only statement 1 is considered to be associated with the if statement.
Figure 3. 1 If condition
Example:
// C# program to illustrate if statement
using System;
95
public class GFG {
GeeksForGeeks
IF – else Statement The if statement evaluates the code if the condition is true but what if the
condition is not true, here comes the else statement. It tells the code what to do when the if
condition is false.
Syntax:
if(condition)
{
// code if condition is true
}
else
{
// code if condition is false
}
Example:
96
// C# program to illustrate
// if-else statement
using System;
Output:
Geeks
The if-else-if ladder statement executes one condition from multiple statements. The execution starts
from top and checked for each if condition. The statement of if block will be executed which evaluates
to be true. If none of the if condition evaluates to be true then the last else block is evaluated.
Syntax:
if(condition1)
{
// code to be executed if condition1 is true
}
else if(condition2)
{
// code to be executed if condition2 is true
}
else if(condition3)
{
// code to be executed if condition3 is true
}
...
else
{
// code to be executed if all the conditions are false
}
97
Figure 3. 3 If – else – if statement
Example:
// C# program to illustrate
// if-else-if ladder
using System;
class GFG {
public static void Main(String[] args)
{
int i = 20;
if (i == 10)
Console.WriteLine("i is 10");
else if (i == 15)
Console.WriteLine("i is 15");
else if (i == 20)
Console.WriteLine("i is 20");
else
Console.WriteLine("i is not present");
}
}
Output:
i is 20
Nested – If Statement
if statement inside an if statement is known as nested if. if statement in this case is the target of another
if or else statement. When more then one condition needs to be true and one of the condition is the sub-
condition of parent condition, nested if can be used.
98
Syntax:
if (condition1)
{
// code to be executed
// if condition2 is true
if (condition2)
{
// code to be executed
// if condition2 is true
}
}
Example:
// C# program to illustrate
// nested-if statement
using System;
class GFG {
99
if (i == 10) {
// Nested - if statement
// Will only be executed if statement
// above it is true
if (i < 12)
Console.WriteLine("i is smaller than 12 too");
else
Console.WriteLine("i is greater than 15");
}
}
}
Output:
Switch Statement
Switch statement is an alternative to long if-else-if ladders. The expression is checked for different cases
and the one match is executed. break statement is used to move out of the switch. If the break is not
used, the control will flow to all cases below it until break is found or switch comes to an end. There
is default case (optional) at the end of switch, if none of the case matches then default case is executed.
Syntax:
switch (expression)
{
case value1: // statement sequence
break;
case value2: // statement sequence
break;
.
.
.
case valueN: // statement sequence
break;
default: // default statement sequence
}
100
Figure 3. 5 Flow Diagram of Switch – case
Example:
101
// C# example for switch case
using System;
Output:
case 30
Nested switch
Nested Switch case are allowed in C# . In this case, switch is present inside other switch cas e. Inner
switch is present in one of the cases in parent switch.
Example:
// C# example for nested switch case
using System;
switch (j)
{
case 5: Console.WriteLine(5);
switch (j - 1)
{
case 4: Console.WriteLine(4);
switch (j - 2)
{
102
case 3: Console.WriteLine(3);
break;
}
break;
}
break;
case 10: Console.WriteLine(10);
break;
case 15: Console.WriteLine(15);
break;
default: Console.WriteLine(100);
break;
}
}
}
Output:
5
4
3
3.7.2. Loops in C#
Looping in a programming language is a way to execute a statement or a set of statements multiple times
depending on the result of the condition to be evaluated to execute statements. The result condition
should be true to execute statements within loops.
Loops are mainly divided into two categories: Entry Controlled Loops: The loops in which condition
to be tested is present in beginning of loop body are known as Entry Controlled Loops. while
loop and for loop are entry controlled loops.
1. while loop
The test condition is given in the beginning of the loop and all statements are executed till the given
boolean condition satisfies when the condition becomes false, the control will be out from the while
loop.
103
Syntax:
while (boolean condition)
{
loop statements...
}
Example:
class whileLoopDemo
{
public static void Main()
{
int x = 1;
// Exit when x becomes greater than 4
while (x <= 4)
{
Console.WriteLine("GeeksforGeeks");
// Increment the value of x for
// next iteration
x++;
}
}
}
104
Output:
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
2. for loop
For loop has similar functionality as while loop but with different syntax. for loops are preferred when
the number of times loop statements are to be executed is known beforehand. The loop variable
initialization, condition to be tested, and increment/decrement of the loop variable is done in one line in
for loop thereby providing a shorter, easy to debug structure of looping.
class forLoopDemo
{
public static void Main()
{
// for loop begins when x=1
// and runs till x <=4
for (int x = 1; x <= 4; x++)
Console.WriteLine("GeeksforGeeks");
}
}
Output:
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
Exit Controlled Loops: The loops in which the testing condition is present at the end of loop body are
termed as Exit Controlled Loops. do-while is an exit controlled loop.
Note: In Exit Controlled Loops, loop body will be evaluated for at-least one time as the testing condition
is present at the end of loop body.
3. do-while loop
do while loop is similar to while loop with the only difference that it checks the condition after executing
the statements, i.e it will execute the loop body one time for sure because it checks the condition after
executing the statements.
Syntax :
do
{
106
statements..
}while (condition);
Example:
Output:
GeeksforGeeks
4. Infinite Loops:
The loops in which the test condition does not evaluate false ever tend to execute statements forever
until an external force is used to end it and thus they are known as infinite loops.
Example:
107
// C# program to demonstrate infinite loop
using System;
class infiniteLoop
{
public static void Main()
{
// The statement will be printed
// infinite times
for(;;)
Console.WriteLine("This is printed infinite times");
}
}
Output:
This is printed infinite times
This is printed infinite times
This is printed infinite times
This is printed infinite times
This is printed infinite times
This is printed infinite times
This is printed infinite times
..........
5. Nested Loops:
When loops are present inside the other loops, it is known as nested loops.
Example:
class nestedLoops
{
public static void Main()
{
// loop within loop printing GeeksforGeeks
for(int i = 2; i < 3; i++)
for(int j = 1; j < i; j++)
Console.WriteLine("GeeksforGeeks");
}
}
Output:
108
GeeksforGeeks
6. continue statement:
Continue statement is used to skip over the execution part of loop on a certain condition and move the
flow to next updating part.
class demoContinue
{
public static void Main()
{
// GeeksforGeeks is printed only 2 times
// because of continue statement
for(int i = 1; i < 3; i++)
{
if(i == 2)
Continue;
Console.WriteLine("GeeksforGeeks");
}
}
}
Output:
GeeksforGeeks
109
3.8. C# | Class and Object
Class and Object are the basic concepts of Object-Oriented Programming which revolve around the
real-life entities. A class is a user-defined blueprint or prototype from which objects are created.
Basically, a class combines the fields and methods (member function which defines actions) into a single
unit. In C#, classes support polymorphism, inheritance and also provide the concept of derived clas ses
and base classes.
Declaration of class
Generally, a class declaration contains only keyword class, followed by an identifier (name) of the
class. But there are some optional attributes that can be used with class declaration according to the
application requirement. In general, class declarations can include these components, in order:
Modifiers: A class can be public or internal etc. By default modifier of class is internal.
Keyword class: A class keyword is used to declare the type class.
Class Identifier: The variable of type class is provided. The identifier (or name of class) should
begin with a initial letter which should be capitalized by convention.
Base class or Super class: The name of the class’s parent (superclass), if any, preceded by the:
(colon). This is optional.
Interfaces: A comma-separated list of interfaces implemented by the class, if any, preceded by the:
(colon). A class can implement more than one interface. This is optional.
Body: The class body is surrounded by { } (curly braces).
Constructors in class are used for initializing new objects. Fields are variables that provide the state of
the class and its objects, and methods are used to implement the behavior of the class and its objects.
Example:
// declaring public class
public class Geeks
{
// field variable
public int a, b;
110
{
Console.WriteLine(“Class & Objects in C#”);
}
3.8.1. Objects
It is a basic unit of Object-Oriented Programming and represents the real-life entities. A typical C#
program creates many objects, which as you know, interact by invoking methods. An object consists of
:
Objects correspond to things found in the real world. For example, a graphics program may have objects
such as “circle”, “square”, “menu”. An online shopping system might have objects such as “shopping
cart”, “customer”, and “product”.
When an object of a class is created, the class is said to be instantiated. All the instances share the
attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for
each object. A single class may have any number of instances.
Example:
111
As we declare variables like (type name;). This notifies the compiler that we will use the name to refer
to data whose type is type. With a primitive variable, this declaration also reserves the proper amount
of memory for the variable. So for reference variable, type must be strictly a concrete class name.
Dog tuffy;
If we declare a reference variable(tuffy) like this, its value will be undetermined(null) until an object is
actually created and assigned to it. Simply declaring a reference variable does not create an object.
Initializing an object
The new operator instantiates a class by allocating memory for a new object and returning a reference
to that memory. The new operator also invokes the class constructor.
Example:
// C# program to illustrate the
// Initialization of an object
using System;
// Class Declaration
public class Dog {
// Instance Variables
String name;
String breed;
int age;
String color;
// Constructor Declaration of Class
public Dog(String name, String breed,
int age, String color)
{
112
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}
// Property 1
public String getName()
{
return name;
}
// Property 2
public String getBreed()
{
return breed;
}
// Property 3
public int getAge()
{
return age;
}
// Property 4
public String getColor()
{
return color;
}
// Method 1
public String toString()
{
return ("Hi my name is " + this.getName()
+ ".\nMy breed, age and color are " + this.getBreed()
+ ", " + this.getAge() + ", " + this.getColor());
}
// Main Method
public static void Main(String[] args) {
// Creating object
Dog tuffy = new Dog("tuffy", "papillon", 5, "white");
Console.WriteLine(tuffy.toString());
}
}
Output:
Hi my name is tuffy.
Explanation: This class contains a single constructor. We can recognize a constructor because its
declaration uses the same name as the class and it has no return type. The C# compiler differentiates the
constructors based on the number and the type of the arguments. The constructor in the Dog class takes
113
four arguments. The following statement provides “tuffy”, ”papillon”, 5, ”white” as values for those
arguments:
3.9. C# | Constructors
A constructor is a special method of the class which gets automatically invoked whenever an instance
of the class is created. Like methods, a constructor also contains the collection of instructions that are
executed at the time of Object creation. It is used to assign initial values to the data members of the
same class.
Example :
class Geek
{ .......
// Constructor
public Geek() {}
.......
}
// an object is created of Geek class,
// So above constructor is called
114
Geek obj = new Geek ();
Important points to Remember about Constructors
Constructor of a class must have the same name as the class name in which it resides.
A constructor cannot be abstract, final, and synchronized.
Within a class, you can create only one static constructor.
A constructor doesn’t have any return type, not even void.
A static constructor cannot be a parameterized constructor.
A class can have any number of constructors.
Access modifiers can be used in constructor declaration to control its access i.e which other class
can call the constructor.
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
4. Private Constructor
5. Static Constructor
1. Default Constructor
A constructor with no parameters is called a default constructor. A 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 .
Example:
// C# Program to illustrate calling
// a Default constructor
using System;
namespace DefaultConstructorExample {
class Geek {
int num;
string name;
// this would be invoked while the
// object of that class created.
Geek()
{
Console.WriteLine("Constructor Called");
115
}
// Main Method
public static void Main()
{
// this would invoke default
// constructor.
Geek geek1 = new Geek();
// Default constructor provides
// the default values to the
// int and object as 0, null
// Note:
// It Give Warning because
// Fields are not assign
Console.WriteLine(geek1.name);
Console.WriteLine(geek1.num);
}
}
}
Output :
Constructor Called
0
Note : This will also show some warnings as follows:
prog.cs(8, 6): warning CS0649: Field `DefaultConstructorExample.Geek.num' is never assigned to, and
will always have its default value `0'
2. Parameterized Constructor
A constructor having at least one parameter is called as parameterized constructor. It can initialize each
instance of the class to different values.
Example:
class Geek {
// data members of the class.
116
String name;
int id;
// parameterized constructor would
// initialized data members with
// the values of passed arguments
// while object of that class created.
Geek(String name, int id)
{
this.name = name;
this.id = id;
}
// Main Method
public static void Main()
{
// This will invoke parameterized
// constructor.
Geek geek1 = new Geek("GFG", 1);
Console.WriteLine("GeekName = " + geek1.name +
" and GeekId = " + geek1.id);
}
}
}
Output :
GeekName = GFG and GeekId = 1
3. Copy Constructor
This constructor creates an object by copying variables from another object. Its main use is to initialize
a new instance to the values of an existing instance.
Example :
// C# Program to illustrate calling
// a Copy constructor
using System;
namespace copyConstructorExample {
class Geeks {
private string month;
private int year;
// declaring Copy constructor
public Geeks(Geeks s)
{
month = s.month;
year = s.year;
}
117
// Instance constructor
public Geeks(string month, int year)
{
this.month = month;
this.year = year;
}
// Get details of Geeks
public string Details
{
get
{
return "Month: " + month.ToString() +
"\nYear: " + year.ToString();
}
}
// Main Method
public static void Main()
{
// Create a new Geeks object.
Geeks g1 = new Geeks("June", 2018);
// here is g1 details is copied to g2.
Geeks g2 = new Geeks(g1);
Console.WriteLine(g2.Details);
}
}
}
Output :
Month: June
Year: 2018
4. Private Constructor
If a constructor is created with private specifier is known as Private Constructor. It is not possible for
other classes to derive from this class and also it’s not possible to create an instance of this class.
Points To Remember:
It is the implementation of a singleton class pattern.
Use private constructor when we have only static members.
Using private constructor, prevents the creation of the instances of that class.
Example :
118
// C# Program to illustrate calling
// a Private constructor
using System;
namespace privateConstructorExample {
public class Geeks {
// declare private Constructor
private Geeks()
{
}
// declare static variable field
public static int count_geeks;
// declare static method
public static int geeks_Count()
{
return ++count_geeks;
}
/ Main Method
public static void Main()
{
// If you uncomment the following
// statement, it will generate
// an error because the constructor
// is unaccessible:
// Geeks s = new Geeks(); // Error
Geeks.count_geeks = 99;
// Accessing without any
// instance of the class
Geeks.geeks_Count();
Console.WriteLine(Geeks.count_geeks);
// Accessing without any
// instance of the class
Geeks.geeks_Count();
Console.WriteLine(Geeks.count_geeks);
}
}
}
Output :
100
101
5. Static Constructor
119
Static Constructor has to be invoked only once in the class and it has been invoked during the creation
of the first reference to a static member in the class. A static constructor is initialized static fields or
data of the class and to be executed only once.
Points To Remember :
It can’t be called directly.
When it is executing then the user has no control.
It does not take access modifiers or any parameters.
It is called automatically to initialize the class before the first instance created.
Example :
// C# Program to illustrate calling
// a Static constructor
using System;
namespace staticConstructorExample {
class geeks {
// It is invoked before the first
// instance constructor is run.
static geeks()
{
// The following statement produces
// the first line of output,
// and the line occurs only once.
Console.WriteLine("Static Constructor");
}
// Instance constructor.
public geeks(int i)
{
Console.WriteLine("Instance Constructor " + i);
}
// Instance method.
public string geeks_detail(string name, int id)
{
return "Name:" + name + " id:" + id;
}
// Main Method
public static void Main()
{
// Here Both Static and instance
// constructors are invoked for
120
// first instance
geeks obj = new geeks(1);
Console.WriteLine(obj.geeks_detail("GFG", 1));
// Here only instance constructor
// will be invoked
geeks obj1 = new geeks(2);
Console.WriteLine(obj1.geeks_detail("GeeksforGeeks", 2));
}
}
}
Output :
Static Constructor
Instance Constructor 1
Name:GFG id:1
Instance Constructor 2
Name:GeeksforGeeks id:2
3.10. Inheritance
Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in C# by
which one class is allowed to inherit the features(fields and methods) of another class.
Important terminology:
Super Class: The class whose features are inherited is known as super class(or a base class or a
parent class).
Sub Class: The class that inherits the other class is known as subclass(or a derived class, extended
class, or child class). The subclass can add its own fields and methods in addition to the superclass
fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new
class and there is already a class that includes some of the code that we want, we can derive our new
class from the existing class. By doing this, we are reusing the fields and methods of the existing
class.
How to use inheritance
121
Syntax:
122
static void Main(string[] args)
{
// creating object of derived class
GeeksforGeeks g = new GeeksforGeeks();
// calling the method of base class
// using the derived class object
g.readers("Kirti", "C#");
}
}
}
Output:
GeeksforGeeks
Myself: Kirti
Below are the different types of inheritance which is supported by C# in different combinations.
Single Inheritance: In single inheritance, subclasses inherit the features of one superclass. In image
below, the class A serves as a base class for the derived class B.
123
Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base class and as
well as the derived class also act as the base class to other class. In below image, class A serves as a
base class for the derived class B, which in turn serves as a base class for the derived class C.
124
Multiple Inheritance (Through Interfaces): In Multiple inheritance, one class can have more than one
superclass and inherit features from all parent classes. Please note that C# does not support multiple
inheritance with classes. In C#, we can achieve multiple inheritance only through Interfaces. In the
image below, Class C is derived from interface A and B.
125
Figure 3. 14 Hybrid Inheritance diagram
Private member inheritance: A subclass does not inherit the private members of its parent class.
However, if the superclass has properties (get and set methods) for accessing its private fields, then
a subclass can inherit.
3.11. Encapsulation
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds
together code and the data it manipulates. In a different way, encapsulation is a protective shield that
prevents the data from being accessed by the code outside this shield.
Technically in encapsulation, the variables or data of a class are hidden from any other class and can
be accessed only through any member function of own class in which they are declared.
As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-
hiding.
Encapsulation can be achieved by: Declaring all the variables in the class as private and using C#
Properties in the class to set and get the values of variables.
126
Figure 3. 15 Encapsulation Inheritance diagram
Example:
127
// Driver Class
class GFG {
// Main Method
static public void Main()
{
// creating object
DemoEncap obj = new DemoEncap();
// calls set accessor of the property Name,
// and pass "Ankita" as value of the
// standard field 'value'
obj.Name = "Ankita";
// calls set accessor of the property Age,
// and pass "21" as value of the
// standard field 'value'
obj.Age = 21;
// Displaying values of the variables
Console.WriteLine("Name: " + obj.Name);
Console.WriteLine("Age: " + obj.Age);
}
}
Output:
Name: Ankita
Age: 21
Advantages of Encapsulation:
Data Hiding: The user will have no idea about the inner implementation of the class. It will not be
visible to the user that how the class is stored values in the variables. He only knows that we are
passing the values to accessors and variables are getting initialized to that value.
Increased Flexibility: We can make the variables of the class as read-only or write-only depending
on our requirement. If we wish to make the variables as read-only then we have to only use Get
Accessor in the code. If we wish to make the variables as write-only then we have to only use Set
Accessor.
128
Reusability: Encapsulation also improves the re-usability and easy to change with new
requirements.
Testing code is easy: Encapsulated code is easy to test for unit testing.
3.12. Abstraction
Data Abstraction is the property by virtue of which only the essential details are exhibited to the user.
The trivial or the non-essentials units aren’t exhibited to the user. Data Abstraction may also be defined
as the process of identifying only the required characteristics of an object ignoring the irrelevant details.
The properties and behaviors of an object differentiate it from other objects of similar type and also help
in classifying/grouping the objects.
Example: Consider a real-life scenario of withdrawing money from ATM. The user only knows that in
ATM machine first enter ATM card, then enter the pin code of ATM card, and then enter the amount
which he/she wants to withdraw and at last, he/she gets their money. The user does not know about the
inner mechanism of the ATM or the implementation of withdrawing money etc. The user just simply
knows how to operate the ATM machine, this is called abstraction.
In C# abstraction is achieved with the help of Abstract classes.
Abstract Classes
An abstract class is declared with the help of abstract keyword.
In C#, you are not allowed to create objects of the abstract class. Or in other words, you cannot use
the abstract class directly with the new operator.
Class that contains the abstract keyword with some of its methods (not all abstract method) is known
as an Abstract Base Class.
Class that contains the abstract keyword with all of its methods is known as pure Abstract Base
Class.
You are not allowed to declare the abstract methods outside the abstract class.
You are not allowed to declare an abstract class as Sealed Class.
Example:
// C# program to calculate the area
// of a square using the concept of
// data abstraction
using System;
namespace Demoabstraction {
// abstract class
abstract class Shape {
// abstract method
public abstract int area();
}
// square class inheriting
// the Shape class
class Square : Shape {
// private data member
private int side;
// method of square class
public Square(int x = 0)
{
side = x;
}
// overriding of the abstract method of Shape
// class using the override keyword
public override int area()
{
Console.Write("Area of Square: ");
return (side * side);
}
}
// Driver Class
class GFG {
// Main Method
static void Main(string[] args)
{
// creating reference of Shape class
// which refer to Square class instance
Shape sh = new Square(4);
// calling the method
double result = sh.area();
Console.Write("{0}", result);
130
}
}
}
Output:
Area of Square: 16
131
1. What are Events?
2. List down the differences between Public, Static and void keywords?
3. Define C# and list the features.
4. List down the reason behind the usage of C# language.
5. What are the advantages of using C#?
6. What are the different types of comments in C#?
7. Illustrate the process of code compilation in C#?
8. List down the access modifiers available in C#.
9. List down the different IDE’s Provided by Microsoft for C# Development.
10. Distinguish between Continue and Break Statement?
11. What are the different approaches of passing parameters to a method?
12. Distinguish between finally and finalize blocks?
13. What is Managed or Unmanaged Code?
14. What is an Object?
15. What is a Class?
16. Define an abstract class?
17. Define sealed classes in C#?
18. Define a Partial class?
19. List down the fundamental OOP concepts?
20. Explain the process of inheriting a class into another class?
21. Define method overloading in C#?
22. List the differences between method overriding and method overloading?
23. Define an array?
132
Chapter 4: Exception Handling
4.1. Introduction
An exception is a problem that arises during the execution of a program. A C# exception is a response to
an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. C# exception
handling is built upon four keywords: try, catch, finally, and throw.
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.
Syntax
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 −
try {
// statements causing exception
} catch( ExceptionName e1 ) {
// error handling code
} catch( ExceptionName e2 ) {
// error handling code
} catch( ExceptionName eN ) {
// error handling code
} finally {
133
// statements to be executed
}
You can list down multiple catch statements to catch different type of exceptions in case your try block
raises more than one exception in different situations.
try block: Any suspected code that may raise exceptions should be put inside a try{ } block. During
the execution, if an exception occurs, the flow of the control jumps to the first matching catch block.
catch block: The catch block is an exception handler block where you can perform some action such
as logging and auditing an exception. The catch block takes a parameter of an exception type using
which you can get the details of an exception.
finally block: The finally block will always be executed whether an exception raised or not. Usually,
a finally block should be used to release resources, e.g., to close any stream or file objects that were
opened in the try block.
Example: C# Program
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number: ");
To handle the possible exceptions in the above example, wrap the code inside a try block and handle
the exception in the catch block, as shown below.
class Program
{
134
static void Main(string[] args)
{
try
{
Console.WriteLine("Enter a number: ");
In the above example, we wrapped this code inside a try block. If an exception occurs inside
a try block, then the program will jump to the catch block. Inside a catch block, we display a message
to instruct the user about his mistake, and in the finally block, we display a message about what to do
after running a program.
Note
A try block must be followed by catch or finally or both blocks. The try block without
a catch or finally block will give a compile-time error.
Ideally, a catch block should include a parameter of a built-in or custom exception class to get an error
detail. The following includes the Exception type parameter that catches all types of exceptions.
Exception Filters
You can use multiple catch blocks with the different exception type parameters. This is called
exception filters. Exception filters are useful when you want to handle different types of exceptions
in different ways.
try
{
int num = int.Parse(Console.ReadLine());
In the above example, we have specified multiple catch blocks with different exception types. We can
display an appropriate message to the user, depending upon the error, so the user does not repeat the
same mistake again.
Note:
Multiple catch blocks with the same exception type are not allowed. A catch block with the base
Exception type must be the last block.
Also, parameterless catch block catch{ } or general catch block catch(Exception ex){ } must be the
last block. The compiler will give an error if you have other catch blocks after a catch{
} or catch(Exception ex) block.
Finally Block
The finally block is an optional block and should come after a try or catch block. The finally block will
always be executed whether or not an exception occurred. The finally block generally used for
cleaning-up code e.g., disposing of unmanaged objects.
try
{
Console.Write("Enter a file name to write: ");
string fileName = Console.ReadLine();
file = new FileInfo(fileName);
file.AppendText("Hello World!")
}
catch(Exception ex)
{
Console.WriteLine("Error occurred: {0}", ex.Message );
}
finally
{
// clean up file object here;
file = null;
}
}
Note:
138
Multiple finally blocks are not allowed. Also, the finally block cannot have the return, continue, or break
keywords. It doesn't let control to leave the finally block.
Nested try-catch
C# allows nested try-catch blocks. When using nested try-catch blocks, an exception will be caught in
the first matching catch block that follows the try block where an exception occurred.
try
{
try
{
var result = 100/divider;
}
catch
{
Console.WriteLine("Inner catch");
}
}
catch
{
Console.WriteLine("Outer catch");
}
}
Output:
Inner catch
An inner catch block will be executed in the above example because it is the first catch block that
handles all exception types.
If there isn't an inner catch block that matches with raised exception type, then the control will flow to
the outer catch block until it finds an appropriate exception filter. Consider the following example.
try
{
try
{
var result = 100/divider;
}
catch(NullReferenceException ex)
{
Console.WriteLine("Inner catch");
}
}
catch
{
Console.WriteLine("Outer catch");
}
}
Output:
Outer catch
C# - throw keyword
We have seen in the previous section how to handle exceptions which are automatically raised by CLR.
Here, we will see how to raise an exception manually.
An exception can be raised manually by using the throw keyword. Any type of exceptions which is
derived from Exception class can be raised using the throw keyword.
140
try
{
PrintStudentName(std);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message );
}
Console.ReadKey();
}
Console.WriteLine(std.StudentName);
}
Output:
Please notice that throw creates an object of any valid exception type using the new keyword. The
throw keyword cannot be used with any other type which does not derive from the Exception class.
Re-throwing an Exception
You can also re-throw an exception from the catch block to pass on to the caller and let the caller
handle it the way they want. The following example re-throws an exception.
In the above example, an exception occurs in Method2(). The catch block simply throws that exception
using only throw keyword (not throw e). This will be handled in catch block in Method1() where it
again re-throw the same exception and finally it is being handled in the Main() method. The stack trace
of this exception will give you the full detail of where exactly this exception occurred.
If you re-throw an exception using exception parameter then it will not preserve the original exception
and creates a new exception. The following example demonstrates this.
In the above example, exception caught in the Main() method will display stack trace from Method1
and Main method. It will not display Method1 in stack trace as we re-throw exception in Method1()
using throw ex. So, never throw an exception using throw <exception parameter>.
143
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 System.ApplicationException and System.SystemException classes.
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 −
1
System.IO.IOException
Handles I/O errors.
2
System.IndexOutOfRangeException
Handles errors generated when a method refers to an array index out of range.
3
System.ArrayTypeMismatchException
Handles errors generated when type is mismatched with the array type.
4
System.NullReferenceException
Handles errors generated from referencing a null object.
5
System.DivideByZeroException
Handles errors generated from dividing a dividend with zero.
6
System.InvalidCastException
Handles errors generated during typecasting.
7
System.OutOfMemoryException
Handles errors generated from insufficient free memory.
144
8
System.StackOverflowException
Handles errors generated from stack overflow.
These error handling blocks are implemented using the try, catch, and finally keywords. Following is
an example of throwing an exception when dividing by zero condition occurs −
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();
d.division(25, 0);
Console.ReadKey();
}
}
}
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
145
Creating User-Defined Exceptions
You can also define your own exception. User-defined exception classes are derived from
the Exception class. The following example demonstrates this −
using System;
namespace UserDefinedException {
class TestTemperature {
static void Main(string[] args) {
Temperature temp = new Temperature();
try {
temp.showTemp();
} catch(TempIsZeroException e) {
Console.WriteLine("TempIsZeroException: {0}", e.Message);
}
Console.ReadKey();
}
}
}
public class TempIsZeroException: Exception {
public TempIsZeroException(string message): base(message) {
}
}
public class Temperature {
int temperature = 0;
if(temperature == 0) {
throw (new TempIsZeroException("Zero Temperature found"));
} else {
Console.WriteLine("Temperature: {0}", temperature);
}
}
}
When the above code is compiled and executed, it produces the following result −
TempIsZeroException: Zero Temperature found
Throwing Objects
You can throw an object if it is either directly or indirectly derived from the System.Exception class.
You can use a throw statement in the catch block to throw the present object as −
Catch(Exception e) {
...
Throw e
146
}
1. System. OutOfMemoryException
The errors that are generated due to insufficient free memory is handled by this exception. Consider the
Example:
// a string variable is created and tried to store 2.1 billion characters and this causes an out of memory
exception
In the above program, a class called check is defined. Then the main method is called. a string variable
is created and tried to store 2.1 billion characters, and this causes an out of memory exception.
147
2. System. NullReferenceException
The errors that are generated from referencing a null object is handled by this exception. Consider the
Example:
using System;
class check
//the length of the value referencing to null is checked if it is equal to zero causing an exception
if (value.Length == 0)
Console.WriteLine(value);
148
In the above program, a class called check is defined. Then the main method is called. Then a string
variable is defined, and it is referencing to null. Then the length of the value referencing to null is
3. System. InvalidCastException
The errors that are generated during typecasting is handled by this exception. Consider the below
Example:
using System.IO;
using System.Text;
class check
// an instance of the string builder class is created which is then assigned to a new object through
implicit casting and then casting is tried explicitly to convert the instance of stringbuilder class to
streamreader class
149
}
In the above program, a class called check is defined. Then the main method is called. Then an instance
of the string builder class is created which is then assigned to a new object through implicit casting and
then casting is tried explicitly to convert the instance of stringbuilder class to streamreader class which
causes an exception.
4. System. ArrayTypeMismatchException
The errors that are generated when there is a mismatch of type with the array type is handled by this
Example:
class check
// a string is defined and assigned the values which is then assigned to object class array and then an
arr2[0] = 8;
150
}
In the above program, a class called check is defined. Then the main method is defined. Then a string is
defined and assigned the values which is then assigned to object class array and then an integer is tried
5. System. IndexOutOfRangeException
The errors that are generated when a method is referring to an array that is out of range is handled by
IndexOutOfRangeException.
Example:
class check
// an array is defined to store 100 integers but then an integer is tried to be stores at a position outside of
arr[0] = 10;
arr[10] = 20;
151
arr[20] = 30;
In the above program, a class called check is defined. Then the main method is called. Then an array is
defined to store 100 integers but then an integer is tried to be stored at a position outside of the size of
6. System. DivideByZeroException
The errors that are generated when a dividend is divided by zero is handled by this exception. Consider
Example:
using System;
class check
//an integer variable res is defined which is tried to divide by zero which causes an exception
Console.WriteLine(res);
152
}
In the above program, a class called check is defined. Then the main method is called. Then an integer
variable res is defined which is tried to divide by zero which causes an exception.
7. System. StackOverflowException
The errors that are generated from stack overflowing is handled by this exception. Consider the below
Example:
using System;
// a method called recurse is defined which takes a value as parameter and increases its value by one
// since we have written a recursive loop and 0 is passed as a parameter, it ends in an infinite loop
causing exception
Console.WriteLine(val);
Recurse(++val);
153
public static void Main()
Recurse(0);
In the above program, a class called check is defined. Then a method called recurse is defined which
takes a value as a parameter and increases its value by one. Then the main method is called in which the
infinite loop for recursion begins by passing zero as a parameter. Then since we have written a recursive
Example:
using System;
using System.IO;
class check
154
{
try
//a file is tried to open which do not exist and causes an exception
File.Open("D:\\ex.txt", FileMode.Open);
catch (IOException)
In the above program, a class called check is defined. Then the main method is called. Then a file is
155
Chapter Four Review Questions
1. What is an exception?
2. Explain exception handling mechanism in C#?
3. Explain the difference between error and exception in C# ?
4. Explain the hierarchy of exceptions in C#?
5. What is the main use of a finally block in exception handling?
6. What is custom exception and how to raise it in C#?
7. What is the base class from which all the exceptions are derived?
8. Does finally get executed if the code throws an error?
9. What is the difference between System exceptions and Application exceptions?
10. What is the difference between throw and throw ex ?
156
Chapter 5: Manipulating Files
5.1. Introduction
A file is a collection of data stored in a disk with a specific name and a directory path. When a file is
opened for reading or writing, it becomes a stream.
The stream is basically the sequence of bytes passing through the communication path. There are two
main streams: the input stream and the output stream. The input stream is used for reading data from
file (read operation) and the output stream is used for writing into the file (write operation).
The following table shows some commonly used non-abstract classes in the System.IO namespace –
1
BinaryReader
Reads primitive data from a binary stream.
2
BinaryWriter
Writes primitive data in binary format.
3
BufferedStream
A temporary storage for a stream of bytes.
4
Directory
Helps in manipulating a directory structure.
5
DirectoryInfo
Used for performing operations on directories.
157
6
DriveInfo
Provides information for the drives.
7
File
Helps in manipulating files.
8
FileInfo
Used for performing operations on files.
9
FileStream
Used to read from and write to any location in a file.
10
MemoryStream
Used for random access to streamed data stored in memory.
11
Path
Performs operations on path information.
12
StreamReader
Used for reading characters from a byte stream.
13
StreamWriter
Is used for writing characters to a stream.
14
StringReader
Is used for reading from a string buffer.
15
StringWriter
Is used for writing into a string buffer.
158
The FileStream Class
The FileStream class in the System.IO namespace helps in reading from, writing to and closing files.
This class derives from the abstract class Stream.
You need to create a FileStream object to create a new file or open an existing file. The syntax for
creating a FileStream object is as follows −
For example, we create a FileStream object F for reading a file named sample.txt as shown −
FileStream F = new FileStream("sample.txt", FileMode.Open, FileAccess.Read,
FileShare.Read);
1
FileMode
The FileMode enumerator defines various methods for opening files. The members of the
FileMode enumerator are −
Append − It opens an existing file and puts cursor at the end of file, or creates the
file, if the file does not exist.
Create − It creates a new file.
CreateNew − It specifies to the operating system, that it should create a new file.
Open − It opens an existing file.
OpenOrCreate − It specifies to the operating system that it should open a file if it
exists, otherwise it should create a new file.
Truncate − It opens an existing file and truncates its size to zero bytes.
2
FileAccess
FileAccess enumerators have members: Read, ReadWrite and Write.
3
FileShare
FileShare enumerators have the following members −
Inheritable − It allows a file handle to pass inheritance to the child processes
159
None − It declines sharing of the current file
Read − It allows opening the file for readin.
ReadWrite − It allows opening the file for reading and writing
Write − It allows opening the file for writing
Example
using System;
using System.IO;
namespace FileIOApplication {
class Program {
static void Main(string[] args) {
FileStream F = new FileStream("test.dat", FileMode.OpenOrCreate,
FileAccess.ReadWrite);
160
Sr.No. Topic & Description
Output
Successfully saved file with data: Hello File Handling!
Explanation
161
In the above program again I created object as fs of FileStrem class. Then Encoded a string into bytes
and kept into byte[] variable bdata and finally using Write() method of FileStream stored string into file.
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace FileStream_ReadFile
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. string data;
15. FileStream fsSource = new FileStream("D:\\csharpfile.txt", FileMode.Open,
FileAccess.Read);
16. using (StreamReader sr = new StreamReader(fsSource))
17. {
18. data = sr.ReadToEnd();
19. }
20. Console.WriteLine(data);
21. Console.ReadLine();
22. }
23. }
24. }
Output
Hello File Handling!
Explanation
In the above example I opened file in a Read permission and use StreamReader class to read file.
StreamWriter Class In C#
StreamWriter Class is more popular in File Handling and it is very helpful in writing text data in the file.
It is easy to use and provides a complete set of constructors and methods to work.
1. using System;
2. using System.Collections.Generic;
162
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace StreamWriter_Class
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. string file = @"D:\csharpfile.txt";
15. using (StreamWriter writer = new StreamWriter(file))
16. {
17. writer.Write("Hello");
18. writer.WriteLine("Hellow StreamWriter Class");
19. writer.WriteLine("How are you!");
20. }
21. Console.WriteLine("Data Saved Successfully!");
22. Console.ReadKey();
23. }
24. }
25. }
Several times you need to save variable data in a file. These variable data might be the output of your
program, log details, exception error etc. In the next programming, I will show you how can you save
variable data in a file using StreamWriter Class.
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace StreamWriter_VariableData
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. string file = @"D:\csharpfile.txt";
15. int a, b, result;
16. a = 5;
17. b = 10;
18. result = a + b;
19.
20. using (StreamWriter writer = new StreamWriter(file))
163
21. {
22. writer.Write("Sum of {0} + {1} = {2}", a, b, result);
23. }
24. Console.WriteLine("Saved");
25. Console.ReadKey();
26. }
27. }
28. }
Now open the D:\csharpfile.txt again and you will see the following text in a file.
Sum of 5 + 10 = 15
C# StreamReader Class
WHAT IS STREAMREADER CLASS?
StreamReader class allows you to read text files easily. Its implementation is easy and it is widely popular
among the programmer. However, there are dozens of way to read text file in C# file handling
but StreamReader Class is more popular in list.
1. Implements a TextReader that reads characters from a byte stream in a particular encoding.
2. StreamReader class uses UTF-8 Encoding by defaults.
3. StreamReader class is designed for character input in a particular encoding.
4. Use this class for reading standard text file.
5. By default, it is not thread safe.
As mentioned above it is very easy to read text file using StreamReader Class. Here I am going to write
a program that does following thing:
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
164
6. using System.IO;
7.
8. namespace StreamReader_Class
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. string file = @"D:\csharpfile.txt";
15.
16. //Writer data to text file
17. using (StreamWriter writer = new StreamWriter(file))
18. {
19. writer.WriteLine("This tutorial explains how to use StreamReader Class
in C# Programming");
20. writer.WriteLine("Good Luck!");
21. }
22.
23. //Reading text file using StreamReader Class
24. using (StreamReader reader = new StreamReader(file))
25. {
26. Console.WriteLine(reader.ReadToEnd());
27. }
28. Console.ReadKey();
29.
30. }
31. }
32. }
Output:
This tutorial explains how to use StreamReader Class in C# Programming
Good Luck!
C# TextWriter
The TextWriter class represents a writer that can write sequential series of characters. You can use this
class to write text in a file. It is an abstract base class of StreamWriter and StringWriter, which write
characters to streams and string respectively.
Example:
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace TextWriter_class
9. {
165
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. string file=@"D:\csharpfile.txt";
15. using (TextWriter writer = File.CreateText(file))
16. {
17. writer.WriteLine("Hello TextWriter!");
18. writer.WriteLine("File Handling Tutorial");
19. }
20. Console.WriteLine("Entry stored successfull!");
21. Console.ReadKey();
22. }
23. }
24. }
Output
Entry stored successfull!
C# TextReader Class
WHAT IS TEXTREADER CLASS?
TextReader Class represents a reader that can read a sequential series of Characters. It is abstract class
that means you cannot instantiate it. After finishing reading or writing file you must dispose or clean
memory directly or indirectly. To directly dispose, call Dispose Method in try/catch block and for
indirectly disposal write code inside using block.
Programming Examples:
In this programming Example I will open D:\csharpfile.txt using TextReader class, read file and print
output on console.
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace TextReader_class
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. string filepath = @"D:\csharpfile.txt";
15.
16. //Read One Line
17. using(TextReader tr=File.OpenText(filepath))
166
18. {
19. Console.WriteLine(tr.ReadLine());
20. }
21.
22. //Read 4 Characters
23. using (TextReader tr = File.OpenText(filepath))
24. {
25. char[] ch = new char[4];
26. tr.ReadBlock(ch, 0, 4);
27. Console.WriteLine(ch);
28. }
29.
30. //Read full file
31. using (TextReader tr = File.OpenText(filepath))
32. {
33. Console.WriteLine(tr.ReadToEnd());
34. }
35. Console.ReadKey();
36. }
37. }
38. }
Output
Hello File Handling!
Hell
Hello File Handling!
C# BinaryWriter Class
WHAT IS BINARYWRITER CLASS?
BinaryWriter class writes Primitive type data type as int, uint or char in binary to a stream. As its name
says BinaryWriter writes binary files that uses a specific data layout for its bytes.
NOTES:
1. BinaryWriter create binary file that is not human understandable but the machine can understand
it more smoothly.
2. It supports writing string in a specific encoding.
3. BinaryWriter class provides methods that simplify writing primitive data types to a stream.
4. If you don't provide types of encoding while creating object then default encoding UTF-8 will be
used.
167
BinaryWriter class makes easy to write Binary File in C#. It gives us great number of useful
methods that makes Binary operation easier. You’ll get more clear clarification by looking the
given program.
EXAMPLE:
Here, I am writing a program explaining BinaryWriter class. This program creates a new binary
file at location “D:\binaryfile.bin” and then stores error log information in it.
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace BinaryWriter_Class
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. using (BinaryWriter writer = new
BinaryWriter(File.Open("D:\\binaryfile.bin", FileMode.Create)))
15. {
16. //Writting Error Log
17. writer.Write("0x80234400");
18. writer.Write("Windows Explorer Has Stopped Working");
19. writer.Write(true);
20. }
21. Console.WriteLine("Binary File Created!");
22. Console.ReadKey();
23. }
24. }
25. }
C# BinaryReader
168
If you have bin file stored in your PC and you want to read them then BinaryReader may help you
lot. BinaryReader class is used to reading binary files. A binary file stored data in different layout that is
more efficient for machine but not convenient for human. BinaryReader makes this job simpler and show
you exact data stored in bin file.
Notes:
For reading binary file, you need to create binary file first using BinaryWriter Class.
Example
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace BinaryReader_Class
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. WriteBinaryFile();
15. ReadBinaryFile();
16. Console.ReadKey();
17. }
18. static void WriteBinaryFile()
19. {
20. using (BinaryWriter writer = new
BinaryWriter(File.Open("D:\\binaryfile.bin", FileMode.Create)))
21. {
22. //Writting Error Log
23. writer.Write("0x80234400");
24. writer.Write("Windows Explorer Has Stopped Working");
25. writer.Write(true);
26. }
169
27. }
28. static void ReadBinaryFile()
29. {
30. using (BinaryReader reader = new
BinaryReader(File.Open("D:\\binaryfile.bin", FileMode.Open)))
31. {
32. Console.WriteLine("Error Code : " + reader.ReadString());
33. Console.WriteLine("Message : " + reader.ReadString());
34. Console.WriteLine("Restart Explorer : " + reader.ReadBoolean());
35. }
36. }
37. }
38. }
Output
Error Code : 0x80234400
Message : Windows Explorer Has Stopped Working
Restart Explorer : true
EXPLANATION
C# String Writer
WHAT IS STRINGWRITER CLASS?
StringWriter class is derived from TextWriter class and it is mainly used to manipulate string rather
than files. StringWriter enables you to write to a string synchronously or asynchronously. You can write
a character with Write(Char) or WriteAsync(Char) method and writer string
with Write(String) or WriterAsync(String) method. The text or information written
by StringWriter class is stored inside a StringBuilder.
Note: StringWriter is not for writing files on local disk. It is used for manipulate string and
it saves information in StringBuilder.
170
HOW TO WRITE TEXT IN A FILE USING STRINGWRITER CLASS?
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace StringWriter_Class
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. string text = "Hello. This is Line 1 \n Hello. This is Line 2 \nHello This
is Line 3";
15. //Writing string into StringBuilder
16. StringBuilder sb = new StringBuilder();
17. StringWriter writer = new StringWriter(sb);
18. //Store Data on StringBuilder
19. writer.WriteLine(text);
20. writer.Flush();
21. writer.Close();
22.
23. //Read Entry
24. StringReader reader = new StringReader(sb.ToString());
25. //Check to End of File
26. while (reader.Peek() > -1)
27. {
28. Console.WriteLine(reader.ReadLine());
29. }
30. }
31. }
32. }
EXPLANATION
This example demonstrate well StringWriter() and StringReader() Class. String variable text stores a
string value and using StringWriter this string value gets stored in StringBuilder. Next
using StringReader the data gets displayed on console.
C# StringReader
WHAT IS STRINGREADER CLASS IN C#?
StringReader class implements TextReader class that reads string from string. It enables you to read a
string synchronously or asynchronously. You can read a character with Read() method and read a line
with ReadLine() method.
171
EXAMPLES
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace StringReader_Class
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. string text = @"You are reading
15. this article at
16. completecsharptutorial.com";
17.
18. using (StringReader reader = new StringReader(text))
19. {
20. int count = 0;
21. string line;
22. while ((line = reader.ReadLine()) != null)
23. {
24. count++;
25. Console.WriteLine("Line {0}: {1}", count, line);
26. }
27. }
28. Console.ReadKey();
29. }
30. }
31. }
Output
Line 1: You are reading
Line 2: this article at
Line 3: completecsharptutorial.com
EXPLANATION
In this program StringReader class reads a string from string variable and marks each line with count
number and shows display on the console.
C# DirectoryInfo
172
DirectoryInfo class allows you to work with directory and its make directory manipulation as create,
delete, info etc easy. It exposes instance methods for creating, moving, enumerating through directories
and subdirectories.
Notes
1. DirectoryInfo class is used for typical operations such as copying, moving, creating or deleting
directories.
2. This class cannot be inherited.
3. By default full read/write access to new directories is granted to all users.
The given example will demonstrate well DirectoryInfo class. This program check for a directory
"D:\csharp" and If directory will be there it will show information of directory else it will create a new
directory D:\csharp
EXAMPLES
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace DirectoryInfo_class
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. string path=@"D:\csharp1";
15. DirectoryInfo dir = new DirectoryInfo(path);
16. try
17. {
18. if (dir.Exists)
19. {
20. Console.WriteLine("{0} Directory is already exists", path);
21. Console.WriteLine("Directory Name : " + dir.Name);
22. Console.WriteLine("Path : " + dir.FullName);
23. Console.WriteLine("Directory is created on : " + dir.CreationTime);
24. Console.WriteLine("Directory is Last Accessed on " +
dir.LastAccessTime);
25. }
26. else
173
27. {
28. dir.Create();
29. Console.WriteLine(path + "Directory is created successfully");
30. }
31. //Delete this directory
32. Console.WriteLine("If you want to delete this directory press small y.
Press any key to exit.");
33. try
34. {
35. char ch = Convert.ToChar(Console.ReadLine());
36. if (ch == 'y')
37. {
38. if (dir.Exists)
39. {
40. dir.Delete();
41. Console.WriteLine(path + "Directory Deleted");
42. }
43. else
44. {
45. Console.WriteLine(path + "Directory Not Exists");
46. }
47. }
48. }
49. catch
50. {
51. Console.WriteLine("Press Enter to Exit");
52. }
53. Console.ReadKey();
54. }
55. catch(DirectoryNotFoundException d)
56. {
57. Console.WriteLine("Exception raised : " + d.Message);
58. }
59. }
60. }
61. }
Output
D:\csharp1Directory is created successfully
If you want to delete this directory press small y. Press any key to exit.
C# FileInfo Class
WHAT IS FILEINFO CLASS IN C#?
FileInfo class in c# is used for manipulating file as creating, deleting, removing, copying, opening and
getting information. It provides properties and instance methods that makes file manipulation easy.
174
NOTES
1. FileInfo class is used for typical operation like copying, moving, renaming, creating, opening,
deleting and appending the file.
2. By default, full read/write access to new files is granted to all users.
The following program demonstrates well the uses of FileInfo class. This program searches for
file D:\csharp\fileinfo.txt. If the file found then it displays the information of the file else create new file.
EXAMPLES
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace FileInfo_Class
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. string path = @"D:\csharp\fileinfo.txt";
15. FileInfo file = new FileInfo(path);
16. //Create File
17. using (StreamWriter sw = file.CreateText())
18. {
19. sw.WriteLine("Hello FileInfo");
20. }
21.
22. //Display File Info
23. Console.WriteLine("File Create on : " + file.CreationTime);
24. Console.WriteLine("Directory Name : " + file.DirectoryName);
25. Console.WriteLine("Full Name of File : " + file.FullName);
26. Console.WriteLine("File is Last Accessed on : " + file.LastAccessTime);
27.
28. //Deleting File
29. Console.WriteLine("Press small y for delete this file");
30. try
31. {
32. char ch = Convert.ToChar(Console.ReadLine());
33. if (ch == 'y')
34. {
35. if (file.Exists)
36. {
175
37. file.Delete();
38. Console.WriteLine(path + " Deleted Successfully");
39. }
40. else
41. {
42. Console.WriteLine("File doesn't exist");
43. }
44. }
45. }
46. catch
47. {
48. Console.WriteLine("Press Enter to Exit");
49. }
50. Console.ReadKey();
51. }
52. }
53. }
Output
File Create on : 13-08-2016 PM 12:49:36
Directory Name : D:\csharp
Full Name of File : D:\csharp\fileinfo.txt
File is Last Accessed on : 13-08-2016 PM 12:49:36
Press small y for delete this file_
1. FileStream Class
2. StreamWriter and StreamReader
3. TextWriter and TextReader
Qu 2. Make D:\csharp\example.dat file using BinaryWriter class, store current date and time and read
that text using BinaryReader class.
176
Qu 4. Create a Directory D:\example and then create a file in it D:\example\test.txt and store "Hello File
Handling" text in it. Then gather information of Directory and File and print them on console.
SUMMARY
In this chapter we have tried to teach you File Handling using programming examples and codes. I am
sure that your understanding of file handling would be increased.
177
Chapter 6: Database Programming
6.1. Overview
A Database is an organized collection of information that is divided into tables. Each table is further
divided into rows and columns; these columns store the actual information. You access a database using
Structured Query Language (SQL), which is a standard language supported by most database software
including SQL Server, Access, and Oracle. In this chapter, you'll see a C# program that connects to a SQL
Server database, retrieves and displays the contents stored in the columns of a row from a table, and then
disconnects from the database. You'll also see programs that connect to Access and Oracle databases.
You'll also learn about Microsoft's rapid application development (RAD) tool, Visual
Studio .NET (VS .NET). VS .NET enables you to develop, run, and debug programs in an integrated
development environment. This environment uses all the great features of Windows, such as the mouse
and intuitive menus, and increases your productivity as a programmer. In the final sections of this chapter,
you'll see how to use the extensive Microsoft documentation that comes with the .NET Software
Development Kit (SDK) and VS .NET. You'll find this documentation invaluable as you become an expert
with ADO.NET and C#. You'll also learn how to use the SQL Server documentation. Featured in this
chapter: Obtaining the required software
Developing your first ADO.NET program
Connecting to Access and Oracle databases
Introducing Visual Studio .NET
Using the .NET documentation
Using the SQL Server documentation
Chapter Learning Objectives
ADO.NET Architecture
Connection class
Command and Data Reader Class
DataAdapter and DataTable class
DataSet class
Provider Agnostic code
178
6.2. ADO.NET Architecture
ADO.NET uses a multilayer architecture that mainly has a few concepts, for instance Connection, Reader,
Command, Adapter and Dataset objects. ADO.NET introduced data providers that are a set of special
classes to access a specific database, execute SQL commands and retrieve data. The Data providers are
extensible. Developers can create their own providers for a proprietary data source. There are some
examples of data providers such as SQL Server providers, OLE DB and Oracle provider.
Connection-based: They are the data provider objects such as Connection, Command,
DataAdapter, and DataReader. They execute SQL statements and connect to a database.
Content-based: They are found in the System.Data namespace and includes DataSet,
DataColumn, DataRow, and DataRelation. They are completely independent of the type of data
source.
ADO.NET Namespaces
Namespaces Description
Contains the definition for columns,relations,tables,database,rows,views and
System.Data
constraints.
Contains the classes to connect to a Microsoft SQL Server database such as
System.Data.SqlClient
SqlCommand, SqlConnection, and SqlDataAdapter.
Contains classes required to connect to most ODBC drivers. These classes
System.Data.Odbc
include OdbcCommand and OdbcConnection.
Contains classes such as OracleConnection and OracleCommand required to
System.Data.OracleClient
connect to an Oracle database.
You need to establish a connection class object for inserting, updating, deleting and retrieving data from
a database. The Connection class allows you to establish a connection to the data source. The Connection
class object needs the necessary information to discover the data source and this information is provided
by a connection string.
179
Connection Strings
You need to supply a connection string in the Connection class object. The connection string is a series of
name/value settings separated by semicolons (;). A connection string requires a few pieces of information
such as the location of the database, the database name, and the database authentication mechanism.
This connection is used to connect to the Master database on the current computer using integrated security
(indicating the currently logged-in Windows user can access the database).
C# Code
In the case of integrated security, it is not supported and then the connection must indicate a valid user
name and password combination as in the following.
C# Code
If you use the OLE DB provider than your connection string will need some additional settings that
identify OLE DB drivers such as:
C# Code
You can specify the details of the connection strings in the global application settings file and then you
can retrieve your connection string by name from the ConfigurationManager as in the following.
App.Config
1. <configuration>
2. <connectionStrings>
3. <add name="Master" connectionString ="Data Source=localhost;Initial Catalog=Master;Int
egrated Security=SSPI" />
4. </connectionStrings>
5. </configuration>
180
Once you declare all the details in the App.config file that pertains to the Connection string then you can
use this definition in the code file also as in the following.
C# Code
Testing a Connection
Once you have configured the right connection string to establish connectivity with the specific data
source you simply use the Open () and Close () methods as in the following.
C# Code
You can also use the SqlConnectionStringBuilder class to configure a connection string rather than
specifying it in the App.Config file as in the following.
C# Code
181
1. SqlConnectionStringBuilder obj = new SqlConnectionStringBuilder();
2. obj.DataSource = "localhost";
3. obj.InitialCatalog = "Master";
4. obj.IntegratedSecurity = true;
5. SqlConnection Conn = new SqlConnection(obj.ConnectionString);
Important: Connections are a limited server resource so it is imperative to release the open connection as soon as
possible.
C# Code
Alternatively, you can pass the connection argument directly to the Command class as in the following.
C# Code
In the following example, we are creating a window application form with a Text Box control. We are establishing
a connection to the Customer table from the AdventureWorks database. Then, using the SqlDataReader class, we
will go through all the records of the table and display the FirstName and LastName in the TextBox control by
executing the While() loop as in the following.
C# Code
182
1. private void Form1_Load(object sender, EventArgs e)
2. {
3. //Connection String
4. SqlConnectionStringBuilder obj = new SqlConnectionStringBuilder();
5. obj.DataSource = "localhost";
6. obj.InitialCatalog = "AdventureWorksLT2008";
7. obj.IntegratedSecurity = true;
8.
9. // Add Connection string to SqlConnection
10. SqlConnection Conn = new SqlConnection(obj.ConnectionString);
11.
12. // Query to retrieve records from AdventureWorks Database
13. string query = "select FirstName,LastName from SalesLT.Customer";
14.
15. //Command Class definition
16. SqlCommand sc = new SqlCommand();
17. sc.Connection = Conn;
18. sc.CommandType = CommandType.Text;
19. sc.CommandText = query;
20.
21. SqlDataReader sdr = null;
22. try
23. {
24. //Open connection
25. Conn.Open();
26. sdr = sc.ExecuteReader();
27.
28. //Get all records
29. while(sdr.Read())
30. {
31. textBox1.AppendText(sdr.GetValue(0) + "\t" + sdr.GetValue(1));
32. textBox1.AppendText("\n");
33. }
34.
35. }
36. catch (Exception err)
37. {
38. textBox1.Text = err.Message;
39. }
40. finally
41. {
42. //Release reader and connection object
43. sdr.Close();
44. Conn.Close();
45. }
46. }
183
It is important to release the objects of the Reader class manually after the job is done or you can set the
CommandBehaviour Property to CloseConnection in the ExcuteReader() method to avoid the burden of
manually releasing the object as in the following.
C# Code
DataReader Class
The DataReader Class object allows you to read the data returned by a SELECT command by a simple forward-
only and read-only cursor. It requires a live connection with the data source and provides a very efficient way of
looping and consuming all parts of the result set. The object of the DataReader cannot be directly instantiated.
Instead you must call the ExecuteReader method of the Command object and close the connection when you are
done using the Data Reader, otherwise the connection remains alive until it is explicitly closed.
C# Code
1. //Open connection
2. Conn.Open();
3. sdr = sc.ExecuteReader(CommandBehavior.CloseConnection);
4.
5. //Get all records
6. while(sdr.Read())
7. {
8. textBox1.AppendText(sdr.GetValue(0) + "\t" + sdr.GetValue(1));
9. textBox1.AppendText("\n");
10. }
ExecuteScalar() Method
The ExecuteScalar() method returns the value stored in the first field of the first row of a result set
generated by the command's SELECT query. This method is usually used to count the total number of
rows in the table as in the following.
C# Code
ExecuteNonQuery() Method
The ExecuteNonQuery() method executes commands that don't return a result set, for instance INSERT,
UPDATE and DELETE. Here in this example we made a modification to a specific record in the Customer
table of the Adventure Works database.
C# Code
185
13. SqlCommand sc = new SqlCommand(query, Conn);
14. //Open connection
15. Conn.Open();
16. //Reflect changes into database
17. int CountCustomer = sc.ExecuteNonQuery();
18. //Result
19. MessageBox.Show("Record Update Successfully");
20. }
C# Code
These are the commonly used properties offered by the SqlDataAdapter class as in the following:
Table 6. 2 Data Adapter Properties
Property Description
186
SelectCommand This command executed to fill in a Data Table with the result set.
SelectCommand Example
C# Code
187
data via result set or output parameter. The following is the SQL code needed to create a procedure for extracting a
single something from the customer table on behalf of a specific CustomerID.
Sql.script
Next, you can create a SqlCommand to wrap the call to the Stored Procedure. This command takes one
parameter as input and returns the records. A parameterized command is basically something that uses a
placeholder in the SQL text. The placeholder indicates dynamically supplied values that are then sent
using a parameters collection of the Command object as in the following.
C# Code
This example uses a parameterized command that is supplied via a text box (Customer ID) and the result is
processed using the Stored Procedure in the code file and the result is displayed in the Data Grid View control as
in the following:
DataSet class
A DataSet is a disconnected architecture technology. It contains zero or more tables and relationships.
When you work with a dataset, the data in the data source is not touched at all. Instead, all the changes are
made locally to the dataset in memory. In the following example, you will see how to retrieve data from
a SQL Server table and use it to fill in a DataTable object in the DataSet.
C# Code
189
8. //Command Class definition
9. SqlCommand sc = new SqlCommand(query, Conn);
10. // Data Adapter definition
11. SqlDataAdapter sda = new SqlDataAdapter();
12. sda.SelectCommand = sc;
13. //data Set definition
14. DataSet ds = new DataSet();
15. // filling the result set in data table
16. sda.Fill(ds, "SalesLT.Customer");
17. //output in data grid
18. dataGridView1.DataSource = ds.Tables["SalesLT.Customer"];
19. }
Here you need to create an empty DataSet and use the SqlDataAdapter Fill() method to execute the query
and place the results in a new DataTable in the DataSet.
You can use a single factory object to create every other type of provider-specific object that you need.
You can then interact with these provider-specific objects in a completely generic way using a set of base
common classes.
Important: You need to import the System.Data.Common namespace in the C# code file for utilizing
provider general code functionality.
190
The first step is to set up the App.Config file with the connection string, provider name, and the query for
this example as in the following.
App.Config
C# Code
CreateDatabse:
192
Password varchar(50) NULL,
)
CreatestoredProcedure:
Create Proc [dbo].[SP_Registration]
(
@FName varchar(50),
@LName varchar(50),
@UName Varchar(50),
@Password varchar(50)
)
As
Begin
declare @Result int
if not exists(select UserName from tbl_Registration where UserName=@UName)
begin
insert into tbl_Registration(First_Name,Last_Name,UserName,Password)
values(@FName,@LName,@UName,@Password)
set @Result=1
return @Result
end
else
begin
set @Result=0
return @Result
end
End
193
Select ASP.NET Empty Website.
Go to the Solution Explorer, select the application, right-click select "Add new Item".
194
Give the name for the class "LinqWithThreeLayer" and click add.
Click Yes.
195
Select Microsoft SQL Server and click Continue.
Give Server name (Client-server) / Machine Name(1-tier), select SQL Server Authentication, give the
Database Name and click Test connection and finally Click OK.
Go to the Serve rExplorer and drag tables and drop in OR-Designer to left side window, and drag
stored procedures and drop to the right side window.
196
Then save OR-Designer window.
After Saving the OR-Designer window, automatically the Data Access Layer class was prepared.
And in the web.config file the Connectionstring is created.
<connectionStrings>
<add name="LINQ_WithThreeLayerConnectionString"
connectionString="Data Source=dotnet16;
Initial Catalog=LINQ_WithThreeLayer;
User ID=sa;
Password=123"
providerName="System.Data.SqlClient" />
</connectionStrings>
Go to Solution Explorer and select App Code; select New Folder. Folder name BAL.
197
Select BAL and right click; select Add New Item. Again we can select Class Template, and class
name is clsRegistration.
Select Class.
198
clsRegistration class code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for clsRegistration
/// </summary>
public class clsRegistration
{
}
public int InsertRegistrationDetails(string FName, string Lname, string UserName,string
Password)
{
int res = obj.SP_Registration(FName, Lname, UserName, Password);
return res;
}
Presentation Layer:
Go to the Solution Explorer and select application and right click and select Add New Folder. And give it the name PL
(Presentation layer).
199
Go to PL folder and select and right-click, select Add New Item, and select Webform template;
give it the name frmRegistration.
200
Code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
{
string Fname= Convert.ToString(txtFName.Text);
string Lname = Convert.ToString(txtLName.Text);
string Uname = Convert.ToString(txtUName.Text);
string Password = Convert.ToString(txtPassword.Text);
int res = obj.InsertRegistrationDetails(Fname, Lname, Uname, Password);
if (res > 0)
{
lblResult.Text = "Registration details are inserted Successfully!";
}
else
{
lblResult.Text = "Not inserted!";
}
}
}
201
6.4. ADO.NET Data Providers
The classes responsible for the movement of data between the disconnected data classes in the client
application and the data store are referred to as connected classes or provider classes.
OLEDB: The OLEDB provider, expressed through the System.Data.OleDb namespace. You can
use this provider to access SQL Server 6.5 and earlier, SyBase, DB2/400, and Microsoft Access.
ODBC: The ODBC provider, expressed through the System.Data.Odbc namespace. This provider
is typically used when no newer provider is available.
SQL Server: The Microsoft SQL Server provider, expressed through
the System.Data.SqlClient namespace. It Contains classes that provide functionality similar to the
generic OleDb provider. The difference is that these classes are tuned for SQL Server 7 and later
data access.
Prior to .NET Framework 4, Microsoft also included a functional Oracle provider with the .NET
Framework. However, its classes have been marked as deprecated and obsolete in .NET Framework 4.
Connection: Establishes a connection to a specific data source. The base class for
all Connection objects is the DbConnection class.
Command: Executes a command against a data source. Exposes Parameters and can execute in
the scope of a Transaction from a Connection. The base class for all Command objects is the
DbCommand class.
DataReader : Reads a forward-only, read-only stream of data from a data source. The base class
for all DataReader objects is the DbDataReader class.
DataAdapter : Populates a DataSet and resolves updates with the data source. The base class for
all DataAdapter objects is the DbDataAdapter class.
In addition to the core classes .NET Framework data provider also contains the
classes Transaction, CommandBuilder, ConnectionStringBuilder, Parameter, Exception, Error and Clie
ntPermission
202
6.5. ODBC .NET Data Provider
The ODBC .NET data provider provides access to ODBC data sources with the help of native ODBC
drivers in the same way that the OleDb .Net data provider accesses native OLE DB providers. One of the
best things about working with ADO.NET data providers is all data providers define the similar class
hierarchy. The only things you need to change are the classes and the connection string.
Unlike the Sql and OleDb data providers, the ODBC data provider is an add-on component to the .NET
Framework. If the ODBC .NET provider isn't installed on your system, you can download it from the
.NET Software Development Kit (SDK) and Visual Studio .NET. You can find the ODBC .NET data
provider on the Microsoft site (http://www.microsoft.com/data). If you don't find the ODBC .NET SDK
on Microsoft site, you can find latest links of the ODBC .NET SDK on C# Corner's Downloads section:
(http://www.c
sharpcorner.com/UsefulResources/Downloads.aspx?Type=0)
After installing ODBC .NET you need to customize the toolbox to add ODBC data components to it. You
can customize the toolbox by right-clicking on the toolbox's Data tab and selecting Customize Toolbox.
203
Note: Make sure the Data tab is selected when you select Customize Toolbox. Otherwise new components
will be added to the active tab.
Next, you click on the .NET Framework Components tab (not the default COM components) and look for
ODBC components. Check the appropriate boxes, and click the OK button .
Next, you need to add a reference to the Microsoft.Data.Odbc.dll assembly using the Project Ø Add
Reference. You can use Browse button to browse the directory. The Microsoft.Data.Odbc.dll resides in
the \Program Files\Microsoft.NET\Odbc.NET directory
Select the component and then click Opento add the reference to the Microsoft.Data.Odbc namespace.
The Add Reference dialog box will appear and now you'll see Microsoft.Odbc.dll listed in the Selected
Components list.
204
Figure 11-4. Adding reference to Microsoft.Data.Odbc.dll
Click OK here. Now you can see the Microsoft.Data.Odbc references is added to your project using
Solution Explorer and click on Project and then expand References node.
205
To make sure the ODBC data provider is installed and added to your project, you can also look at the
toolbox (see Figure 11-6). If the toolbox has the ODBC data components, that means the ODBC data
provider is installed on your system and the reference of data provider has been added to your project.
Note: The toolbox's Data tab is not available for console applications.
Now you can use ODBC components in a similar way that you've used the Sql and OleDb data provider
components.
The ODBC .NET data provider installation adds the Microsoft.Data.Odbc namespace to the namespace,
which defines the classes for ODBC data providers. To use the ODBC .NET data provider, you must add
a using statement for the Microsoft.Data.Odbc namespace to your application:
Using Microsoft.Data.Odbc;
You've seen how to use the SQL and OleDb data providers in previous chapters. Working with the ODBC
data provider is no different than the Sql and OleDb data providers. Unlike the Sql and OleDb data
206
providers, however, the ODBC data provider is defined in the Microsoft.Data.Odbc namespace. You must
add a reference to this namespace before you start using the ODBC data provider classes.
The ODBC data provider defines similar classes and a class hierarchy as the Sql and OleDb data providers.
Further, you can use the ODBC classes similarly to how you've used SQL and OleDb classes. Table 11-1
defines the ODBC .NET data provider classes (discussed in more detail in Chapter 5).
As you can see from Table 11-1, the ODBC data provider has connection, command, data adapter,
parameter, exception and errors, command builder, data reader, transaction, and other classes similar to
the Sql and OleDb data providers. To use the ODBC data provider classes, you create a connection object,
then fill data from the connection to a data adapter or a data reader, and they display the data.
Now I'll show you an example of how to access data from a data source using the ODBC data provider.
In this example, I'll use Access 2000 Northwind database as the data source.
Before creating a connection, the first thing you need to understand is the connection string. The
connection string for OdbcConnection contains a data source driver and the data source path with an
optional user ID and password. Optionally, you can also use an ODBC Data Source Name (DSN) as a
connection string. You create a DSN from the ODBC Administration.
The connection string for an Oracle database looks like following:
Driver={Microsoft ODBC for Oracle};Server=ORACLE8i7;UID=odbcuser;PWD=odbc$5xr
The connection string for a Microsoft Access database looks like following:
Driver={Microsoft Access Driver (*.mdb)};DBQ=c:\Northwind.mdb
The connection string for an Excel database looks like following:
207
Driver={Microsoft Excel Driver (*.xls)};DBQ=c:\bin\book1.xls
The connection string for a text database looks like following:
Driver={Microsoft Text Driver (*.txt; *.csv)};DBQ=c:\
You can use any data source name (DSN) by using the following connection string:
DSN=dsnname
The connection string for a SQL Server database looks like following:
"DRIVER={SQL Server};SERVER=MyServer;UID=sa;PWD=Qvr&77xk;DATABASE=northwind;";
Listing 11-1 reads data from Northwind database and shows the results on the console. In this sample, I
created a console application to test the code. As you can see from Listing 11-1, first I included
the Microsoft.Data.Odbc namespace. After that I created an OdbcConnection object with Microsoft
Access ODBC driver and the Northwind database. The next step was to create an OdbcCommand object
and call the ExecuteReader method, which returns OdbcDataReader. After that I read data from the data
reader and displayed the results on the console.
Listing 11-1. Reading data from Northwind using the ODBC data provider
using System;
using Microsoft.Data.Odbc;
namespace FirstODBCSamp
{
class Class1
{
static void Main(string[]args)
{
// Build a connection and SQL strings
string connectionString = @"Driver={Microsoft Access Driver (*.mdb)};DBQ=c:\Northwind.mdb";
string SQL = "SELECT * FROM Orders";
// create connection object
OdbcConnection conn = new OdbcConnection(connectionString);
// Create command object
OdbcCommand cmd = new OdbcCommand(SQL);
cmd.Connection = conn;
// Open connection
conn.Open();
// Call command's ExecuteReader
OdbcDataReader reader = cmd.ExecuteReader();
// Read the reader and display results on the console
208
while (reader.Read())
{
Console.Write("OrderID:"+reader.GetInt32(0).ToString() );
Console.Write(" ,");
Console.WriteLine("Customer:" + reader.GetString(1).ToString() );
}
// close reader and connection
reader.Close();
conn.Close();
}
}
}
Note:
In the next part of this chapter, you will learn how to access and manipulate MySQL server databases
using ODBC .NET data provider.
209
Summery
A Web service is a software component that you can call over the Web, and one of the key
features of .NET is the ability to easily create Web services. Companies can create Web
services to allow their customers to interact with them. Because Web services return and accept data in
the form of XML documents, Web services are truly platform independent. For example, you could have
a Web service written in C# communicate with another Web service written in Java, passing data in the
form of XML documents. In this chapter, you saw how to create a Web service using VS .NET and use it
in a Windows application. You also saw how to register a Web service so that other organizations can use
your service. I hope you found this book informative and useful, and I hope I've held your interest!
Database programming with C# is a very large subject, but armed with this book, I have every confidence
you will master it.
210