0% found this document useful (0 votes)
37 views98 pages

CS-20 Programming With C#Net - 240104 - 194116

Uploaded by

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

CS-20 Programming With C#Net - 240104 - 194116

Uploaded by

kotechas29
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 98

.

PROGRAMMING WITH C# .NET


Paper Code: CS-20

-: PREPARED BY :-
LT. M. J. KUNDALIYA ARTS, COMMERCE & COMPUTER SCIENCE MAHILA COLLEGE
Rashtriya Shala Compound, Vidhya nagar Main Road, Rajkot
Table of Contents
1.1INTRODUCTION TO VISUAL STUDIO 2015 .................................................................................. 1
1.2 ARCHITECTURE OF MICROSOFT .NET FRAMEWORK ......................................................... 1
1.3 FEATURES OF .NET ........................................................................................................................... 6
1.4 ASSEMBLY ........................................................................................................................................... 7
1.5 METADATA .......................................................................................................................................... 7
1.6 MANAGED CODE ............................................................................................................................... 8
1.7 UNMANAGED CODE.......................................................................................................................... 8
1.8 VISUAL STUDIO EDITIONS ............................................................................................................. 9
1.9 VISUAL STUDIO IDE ......................................................................................................................... 9
1.10 VARIABLES ...................................................................................................................................... 11
1.10.1 VARIABLE NAMING CONVENTION: ......................................................................................... 11
1.10.2 RESERVED KEYWORDS IN C#:................................................................................................ 11
1.10.3 CONTEXTUAL KEYWORDS IN C# ............................................................................................ 12
1.10.4 CONSTANTS ........................................................................................................................... 12
1.10.5 STRINGS ................................................................................................................................. 13
1.10.5.1 How to assign a string: ........................................................................................................... 13
1.10.5.2 Obtaining length of C# String: ............................................................................................... 13
1.10.5.3 Concatenating Strings in C#: ................................................................................................. 13
1.10.5.4 Comparing Strings in C#: ...................................................................................................... 14
1.10.5.5 Changing String Case in C#: .................................................................................................. 14
1.10.5.6 Splitting a C# String into Multiple Parts ................................................................................ 14
1.10.5.7 Trimming and Padding C# Strings......................................................................................... 15
1.10.5.8 C# String Replacement .......................................................................................................... 15
1.11 DATA TYPES .................................................................................................................................... 15
1.11.1 VALUE TYPES: ........................................................................................................................ 16
1.11.2 POINTER TYPES: ..................................................................................................................... 17
1.11.3 REFERENCE TYPES: ................................................................................................................ 18
1.12 BOXING AND UNBOXING ......................................................................................................... 21
1.13 OPERATORS ................................................................................................................................. 21
1.14 ARRAYS ......................................................................................................................................... 21
1.14.1 DEFINING ARRAYS OF DIFFERENT TYPES ................................................................................ 22
1.14.2 INITIALIZING ARRAYS ............................................................................................................ 22
1.14.3 ACCESSING ARRAYS .............................................................................................................. 22
1.14.4 ACCESSING AN ARRAY USING A FOREACH LOOP .................................................................... 22
1.14.5 ARRAY TYPES ........................................................................................................................ 23
1.14.5.1 Single Dimension Arrays: ...................................................................................................... 23
1.14.5.2 Multi-Dimensional Arrays: .................................................................................................... 23
1.14.5.3 Jagged Arrays:........................................................................................................................ 25
1.15 DECISION STATEMENTS ............................................................................................................. 26
1.15.1 IF STATEMENT: ....................................................................................................................... 26
1.15.2 SWITCH STATEMENT: ............................................................................................................. 28
1.16 LOOP STATEMENTS ..................................................................................................................... 29
1.16.1 FOR LOOP: ............................................................................................................................. 29
1.16.2 WHILE LOOP: ......................................................................................................................... 30
1.16.3 DO…WHILE LOOP: ................................................................................................................ 31
1.16.4 FOR EACH LOOP: .................................................................................................................... 31
1.17 EXCEPTION USING TRY-CATCH-FINALLY ........................................................................ 32
2.1 CLASS .................................................................................................................................................. 34
2.2 OBJECT ............................................................................................................................................... 35
2.3 ENCAPSULATION ............................................................................................................................ 35
2.4 INHERITING A CLASS .................................................................................................................... 36
2.4.1 SINGLE INHERITANCE: ............................................................................................................. 37
2.4.2 HIERARCHICAL INHERITANCE: ................................................................................................. 37
2.4.3 MULTI-LEVEL INHERITANCE: .................................................................................................. 37
2.4.4 HYBRID INHERITANCE: ............................................................................................................ 38
2.4.5 MULTIPLE INHERITANCE: ......................................................................................................... 38
2.4.6 FIELDS ..................................................................................................................................... 38
2.4.7 PROPERTIES ............................................................................................................................. 39
2.5 POLYMORPHISM ............................................................................................................................. 40
2.6 CREATING CLASS AND OBJECTS METHODS WITH “REF” AND “OUT” PARAMETERS
..................................................................................................................................................................... 40
2.7 STATIC AND NON-STATIC MEMBERS ....................................................................................... 42
2.8 CONSTRUCTORS .............................................................................................................................. 42
2.9 OVERLOADING CONSTRUCTOR, METHOD AND OPERATOR ........................................... 43
2.10 ABSTRACT CLASS ......................................................................................................................... 44
2.11 SEALED CLASS ............................................................................................................................... 46
2.12 OVERRIDING METHODS ............................................................................................................. 47
2.13 CREATING AN INTERFACE ........................................................................................................ 48
2.13.1 IMPLEMENTING AN INTERFACE .............................................................................................. 48
2.13.2 INHERITING AN INTERFACE .................................................................................................... 49
2.14 CREATING AND USING PROPERTY ......................................................................................... 50
2.15 CREATING AND USING AN INDEXER ...................................................................................... 50
2.16 POINTERS......................................................................................................................................... 52
2.16.1 POINTERS TO ARRAYS ........................................................................................................... 54
2.16.2 POINTERS TO STRUCTURES .................................................................................................... 54
2.17 DELEGATE ....................................................................................................................................... 55
2.17.1 DECLARING & INSTANTIATING DELEGATE ............................................................................ 55
2.17.2 MULTICAST DELEGATE .......................................................................................................... 56
2.18 EVENTS ............................................................................................................................................. 57
2.19 UNDERSTANDING COLLECTIONS ........................................................................................... 58
2.19.1 ARRAY LIST ........................................................................................................................... 59
2.19.2 HASHTABLE........................................................................................................................... 60
2.19.3 STACK .................................................................................................................................... 61
2.19.4 QUEUE ................................................................................................................................... 62
3.1 INTRODUCTION TO WINDOWS FORMS & WINDOWS APPLICATION ............................ 64
3.2 MESSAGE BOX .................................................................................................................................. 64
3.4 DIFFERENT WINDOWS CONTROLS ........................................................................................... 65
3.4.1 BUTTON CONTROL ................................................................................................................... 65
3.4.2 LABEL CONTROL...................................................................................................................... 65
3.4.3 TEXTBOX CONTROL ................................................................................................................ 65
3.4.4 RADIOBUTTON CONTROL ........................................................................................................ 66
3.4.5 CHECKBOX CONTROL .............................................................................................................. 67
3.4.6 LISTBOX, CHECKEDLISTBOX, COMBOBOX ............................................................................. 67
3.4.7 PICTUREBOX ............................................................................................................................ 68
3.4.8 SCROLLBAR ............................................................................................................................. 68
3.4.9 TREEVIEW ............................................................................................................................... 69
3.4.10 MENU .................................................................................................................................... 71
3.4.10.1 Menu Strip.............................................................................................................................. 71
3.4.10.2 Context Menu Strip ................................................................................................................ 71
3.4.11 TOOLTIP ................................................................................................................................. 72
3.4.12 TIMER .................................................................................................................................... 73
3.4.13 PANEL .................................................................................................................................... 73
3.4.14 GROUPBOX ............................................................................................................................ 74
3.4.15 NOTIFY ICON.......................................................................................................................... 74
3.4.16 PROGRESSBAR ....................................................................................................................... 75
3.5 DIALOG BOX ..................................................................................................................................... 75
3.5.1 COLOUR DIALOG ..................................................................................................................... 75
3.5.2 FONT DIALOG .......................................................................................................................... 76
3.5.3 SAVEFILE DIALOG ................................................................................................................... 76
3.5.4 OPEN FILE DIALOG .................................................................................................................. 76
3.6 MDI CONCEPT WITH MDI NOTEPAD ................................................................................... 76
4.1 INTRODUCTION TO ADO.NET ..................................................................................................... 79
4.2 ADO.NET ARCHITECTURE ........................................................................................................... 79
4.3 DATA PROVIDERS IN ADO.NET................................................................................................... 79
4.4 CONNECTION OBJECT .................................................................................................................. 80
4.5 CONNECTED ARCHITECTURE .................................................................................................... 81
4.5.1 THE COMMAND OBJECT: .......................................................................................................... 81
4.5.2 THE DATAREADER OBJECT: ..................................................................................................... 81
4.6 DISCONNECTED ARCHITECTURE ............................................................................................. 81
4.6.1 THE DATAADAPTER OBJECT: ................................................................................................... 81
4.6.2 DATA SET ................................................................................................................................ 81
4.6.3 DATATABLE ............................................................................................................................ 82
4.6.4 DATAROW ............................................................................................................................... 83
4.6.5 DATACOLUMNS ....................................................................................................................... 83
4.6.6 DATA RELATION ...................................................................................................................... 83
4.6.7 DATA VIEW ............................................................................................................................. 83
4.7 DATA BINDING ................................................................................................................................. 84
4.7.1 SIMPLE DATA BINDING ............................................................................................................. 84
4.7.2 COMPLEX DATA BINDING ........................................................................................................ 87
4.8 GRIDVIEW PROGRAMMING ........................................................................................................ 91
CS-20 : Programming with C# .Net
1.1 Introduction to Visual Studio 2015
 Microsoft Visual Studio is an integrated development environment (IDE) from Microsoft. An
IDE is a software application that contains facilities to aid developers in building
applications. It is used to develop console application and graphical user interface application. It
can also use to develop windows forms applications, web sites, web applications, etc. In other
words, it is a new framework for developing web-based and windows-based applications.
 Visual Studio is a major development tool to build .NET applications.
 The integrated debugger works both as a source-level debugger and a machine-level debugger.
Other built-in tools include:
 Form designer for building GUI applications
 Web designer,
 Class designer
 Database schema designer, etc.
 Visual Studio offers a very rich code-editing solution. It also offers an integrated
debugger, which allows you to place breakpoint in your source code to stop execution at
any given point, as well as step through the source line by line. Visual Studio supports
different programming languages by means of language services, which allow the code
editor and debugger to support nearly any programming language, provided a language-
specific service exists.
Different versions of Visual Studio .NET:
Version Release Date Visual Studio
1.0 13-2-2002 Visual Studio .NET
1.1 24-4-2003 Visual Studio .NET 2003
2.0 7-11-2005 Visual Studio 2005
3.0 6-11-2006
3.5 19-11-2007 Visual Studio 2008
4.0 12-4-2010 Visual Studio 2010
4.5 12-9-2012 Visual Studio 2012
5.1 17-10-2013 Visual Studio 2013
4.6.1 20-7-2015 Visual Studio 2015
4.7.2 7-3-2017 Visual Studio 2017
4.8 2-4-2019 Visual Studio 2019
4.8.1 8-11-2021 Visual Studio 2021

1.2 Architecture of Microsoft .NET Framework


 A programming infrastructure created by Microsoft for building, deploying, and
running applications and services that use .NET technologies, such as desktop applications
and Web services. It includes a large library and provides language interoperability (each
language can use code written in other languages) across several programming languages.

Page 1 of 98
CS-20 : Programming with C# .Net

Microsoft Intermediate Language (MSIL)(CIL)(IL)


 MSIL is also known as Intermediate Language (IL) or Common Intermediate Language (CIL).
Microsoft Intermediate Language is the Core of the .NET Framework. All .NET source codes
written in any .net supportive language (C#, VB.net etc), when compiled are converted to MSIL.
 Microsoft Intermediate Language (MSIL) is a CPU-independent set of instructions that can be
efficiently converted to the native code. During the runtime the Common Language
Runtime (CLR)'s Just In Time (JIT) compiler converts the Microsoft Intermediate Language
(MSIL) code into native code to the Operating System.
 When a compiler produces Microsoft Intermediate Language (MSIL), it also produces Metadata.
The Microsoft Intermediate Language (MSIL) and Metadata are contained in a portable
executable (PE) file.
 Microsoft Intermediate Language (MSIL) includes instructions for loading, storing, initializing,
and calling methods on objects, as well as instructions for arithmetic and logical operations,
control flow, direct memory access, exception handling, and other operations.
 Benefits:1. MSIL provides language interoperability as the code in any .NET language is
compiled into MSIL. 2. Same performance for all the .NET Languages.

Page 2 of 98
CS-20 : Programming with C# .Net
Common Language Runtime (CLR)
 CLR is the execution engine for .NET framework applications.
 CLR is a heart or backbone of the .NET.
 Central to the .NET Framework is its runtime execution environment, known as the Common
Language Runtime (CLR) or the .NET runtime. Code running under the control of the CLR is
often termed managed code whereas the code that cannot be directly executed by the CLR is
termed as unmanaged code.
 The CLR provides an infrastructure for run programs and allow them to communicate with other
parts of the .NET framework.
 CLR provides functionalities such as:
 Memory management
 Exception handling
 Debugging
 Security
 Thread exception
 Code execution
 Code safety
 Verification
 Compilation
 The CLR provides the interoperability between different .NET languages such as Visual C#,
Visual Basic, or Visual C++ by providing a common environment for the execution of code
written in any of these languages.
 When you run a .NET application, the language compiler first compiles the source code into an
intermediate code called Microsoft Intermediate language (MSIL) code. The MSIL code is then
used by the Just-In-Time (JIT) complier to convert the MSIL code into the native machine code,
which is final executable code.

Visual Basic Source MSIL code


Code
JIT complier
Native
C# Source Code Machine code

Other.NET languages
Source Code

 CLR uses the garbage collector to manage the allocation and release of memory for an
application.
JIT
 JIT stands for “Just In Time”.
 During the code execution time, the Managed Code compiled only when it is needed, that is it
converts the appropriate instructions to the native code for execution just before when each
function is called. This process is called Just In Time (JIT) compilation, also known as Dynamic
Page 3 of 98
CS-20 : Programming with C# .Net
Translation. Just In Time (JIT) compilation preserves memory and save time during application
initialization.
ADO.NET
 ADO.NET (ActiveX Data Objects for .NET) is a set of computer software components that
programmers can use to access data and data services.ADO.NET provides a rich set of
components for creating distributed, data-sharing applications. It is an integral part of the .NET
Framework, providing access to relational, XML, and application data. ADO.NET supports a
variety of development needs, including the creation of front-end database clients and middle-tier
business objects used by applications, tools, languages, or Internet browsers.
 User can use ADO.NET to connect to data sources for retrieving, manipulating, and updating
data. The most important feature of ADO.NET is disconnected architecture. In this architecture,
applications are connected to the databases only till data is retrieved or modified. Therefore,
applications do not require connecting to the database for processing each record. In addition, all
database operations are performed on the dataset instead of the database.
ASP.NET
 ASP.NET is a web application framework developed and marketed by Microsoft to allow
programmers to build dynamic Web sites, Web applications and Web services. It is a Web
development model, which is used to develop interactive, data-driven Web applications over the
internet.
 User can add controls such as Textbox, Button, and Label to a Web form, which is the basic UI
entity of a Web application. User can also specify the behaviour and add functionality for the
controls in the code of the Web application.
Windows Forms
 Windows Forms (WinForms) is the name given to the graphical application programming
interface (API) included as a part of Microsoft .NET Framework. To create a Windows desktop
application we use the library represented by System.Windows.Forms namespace.
 Windows Forms applications allow you to develop windows-based desktop applications that users
can install and run on their computers. The basic entity of a Windows Forms application is a
form, which is a rectangular area on which you can place various controls to design the UI of the
application.
 The .NET Framework provides you the facility to develop Windows Forms applications using a
.NET-compliant language. A Windows form can be used to accept input from a user or display
information to the user. User can add controls to a Windows form and develop responses to the
user actions, such as mouse click or key press.
.NET Framework Class Library (FCL) or Base Class Library
 The Base Class Library (BCL) is a standard library available to all languages using the .NET
framework. In C, <conio.h>, <stdio.h> etc. are header files. We add those header files in our
program to use inbuilt functions. Same here the .NET framework is collection of classes or
namespace that can be used to develop applications.
 The .NET Framework class library is a library of reusable classes, interfaces, and value types that
provide access to system functionality. It is the foundation on which .NET Framework
applications, components, and controls are built.

Page 4 of 98
CS-20 : Programming with C# .Net
 The .Net Framework class library (FCL) organized in a hierarchical tree structure and it is divided
into Namespaces. Namespaces is a logical grouping of types for the purpose of identification.
Framework class library (FCL) provides the consistent base types that are used across all .NET
enabled languages.
 The Classes are accessed by namespaces, which reside within Assemblies. The System
Namespace is the root for types in the .NET Framework. The .Net Framework class library
(FCL) classes are object oriented and easy to use in program developments.
 Example, the System.Data namespace contains the functionality for accessing databases. This
namespace is further broken down into other namespaces, such as System.Data.SqlClient, which
exposes functionality required to work with Structured Query Language (SQL) server databases.
Common Type System (CTS)
 Common Type System (CTS) describes a set of types that can be used in different. CTS is a
component of .NET framework provides support for multiple languages. It contains set of types
and operations, which are found in most of the programming languages. The Common Type
System (CTS) ensure that objects written in different .Net languages can interact with each other.
CLS provides cross language integration.
 The CTS supports two general category types:
i. Value Types:
Value types, which are mainly primitive types, inherit from System.ValueType and then
System.Object.The Value Types are passed by values and stored in the stack.
E.g., int a;
ii. Reference Types:
Reference types are derived from System.Object, either directly or indirectly. The Reference
Types are passed by references and stored in the heap. The lifetime of reference types is
controlled by the Garbage Collector.
E.g., SqlConnection con = new SqlConnection ()
 The Common Language Runtime (CLR) can load and execute the source code written in any .Net
language, only if the type is described in the Common Type System (CTS).
Common Language Specification (CLS)
 CLS includes basic languages features needed by almost all the applications. It serves as a guide
for library writers and compiler writers.
 The Common Language Specification (CLS) is a subset of the Common Type System (CTS).
The Common Language Specification (CLS), which is a set of basic language features needed by
many .Net applications to fully interact with other objects regardless of the language in which
they were implemented. The CLS represents the guidelines defined by for the .NET Framework.
These specifications are normally used by the compiler developers and are available for all
languages, which target the .NET Framework.
Namespace
 Namespaces are the way to organize .NET Framework Class Library into a logical grouping
according to their functionality, usability as well as category they should belong to, or we can say
Namespaces are logical grouping of types for the purpose of identification.
Page 5 of 98
CS-20 : Programming with C# .Net
 The .NET Framework Class Library (FCL) is a large collection of thousands of Classes. These
Classes are organized in a hierarchical tree. The System Namespaces is the root for types in the
.NET Framework. We can uniquely identify any Class in the .NET Framework Class Library
(FCL) by using the full Namespaces of the class.
 In .Net languages every program is created with a default Namespaces. Programmers can also
create their own Namespaces in .Net languages.
Garbage Collection (GC)
 Garbage collection is a mechanism that allows the computer to detect when an object can no
longer be accessed. The .Net Framework provides a new mechanism for releasing unreferenced
objects from the memory (that is we no longer needed that object in the program), this process is
called Garbage Collection (GC).
 The .NET Framework's garbage collector manages the allocation and release of memory for your
application. Each time you create a new object, the common language runtime allocates memory
for the object from the managed heap.
 When a program creates an Object, the Object takes up the memory. Later when the program has
no more references to that Object, the Object's memory becomes unreachable, but it is not
immediately freed.
 The Garbage Collection checks to see if there are any Objects in the heap that are no longer being
used by the application. If such Objects exist, then the memory used by these Objects can be
reclaimed.
 So these unreferenced Objects should be removed from memory, then the other new Objects you
create can find a place in the Heap. The reclaimed Objects have to be finalized later. Finalization
allows a resource to clean up after itself when it is being collected.
 This releasing of unreferenced Objects is happening automatically in .Net languages by the
Garbage Collector (GC). In .Net languages there is a facility that we can call Garbage Collector
(GC) explicitly in the program by calling System.GC.Collect.
1.3 Features of .NET
The following are major features of .NET:
1. Rich set of Classes: Visual Studio .NET contains hundreds of classes and namespaces that
provides variety of functionality in your application.For example to with Database we need to
include System.Data namespace.
2. Object Oriented Programming System: Visual Studio .NET provides a fully object-oriented
environment. Visual Studio .NET supports OOPs concepts.
3. In-built Memory Management: Visual Studio .NET supports handling memory on its own. The
garbage collector takes the responsibility for free up unused objects for regular intervals.
4. Multi-Language and Multi-Device support: Multi-Language provides extended support for
creating global applications with a user interface in multiple languages using Microsoft Visual
Studio .NET. The beauty of multi-language support lies in the fact that even though the syntax of
each language is different, the basic environment of developing software is same. Visual Studio
.NET also support multi-device. We can create Mobile or PDA etc. device supported software.
5. Fast and easy development of web applications: .NET offers an integrated support for Web
pages, using a new technology — ASP.NET. ASP.NET is useful for developing dynamic and
database related web applications. ASP.NET contains rich and faster development controls for web
applications.

Page 6 of 98
CS-20 : Programming with C# .Net
6. XML Support: Visual Studio .NET supports for writing, manipulating and transforming XML
documents.
7. Efficient data access: A set of .NET components, collectively known as ADO.NET, provides
efficient access to relational databases and a variety of data sources.
8. Web Designer, Editing and CSS Support: One feature that web developers will discover with VS
2008 is its drastically improved HTML designer, and the extensive CSS support made available.
Visual Studio 2008 brings along the Split view which allows us to view both the HTML source and the
Design View at the same-time, and easily make changes in any of the views. Also introduces a new tool
inside the IDE called "Manage Styles". This shows all of the CSS style sheets for the page. Manage
Styles tool can be activated by choosing Format -> CSS Styles -> Manage Styles from the menu.
1.4 Assembly
 In .NET every application is compiled into an assembly, which forms the unit of deployment,
versioning, code reuse and security of the application. Assemblies are the building blocks of .NET
Framework applications.
 An assembly is a collection of types and resources that are built to work together and form a
logical unit of functionality. An assembly provides the common language runtime with the
information it needs to be aware of type implementations.
 Assembly is a logical unit of code; it contains code that the Common Language Runtime (CLR)
executes. Assembly is really a collection of types and resource information that are built to work
together and form a logical unit of functionality.
 During the compile time Metadata is created, with Microsoft Intermediate Language (MSIL), and
stored in a file called a Manifest . Both Metadata and Microsoft Intermediate Language (MSIL)
together wrapped in a Portable Executable (PE) file. Manifest contains information about itself.
 This information is called Assembly Manifest, it contains information about the members, types,
references and all the other data that the runtime needs for execution.
 Every Assembly you create contains one or more program files and a Manifest. There are two
types’ program files: Process Assemblies (EXE) and Library Assemblies (DLL). Each Assembly
can have only one entry point.
 We can create two types of Assembly, Private Assembly and shared Assembly. A private
Assembly is used only by a single application, and usually it is stored in that application's install
directory. A shared Assembly is one that can be referenced by more than one application. If
multiple applications need to access an Assembly, we should add the Assembly to the Global
Assembly Cache (GAC).
1.5 Metadata
 Metadata is stored within the Assembly. Metadata means data about data.
 A metadata describes a program that is in the form of binary information stored in an assembly.
When compilation of the code takes place in a PE file, the metadata is inserted into one part of the
file, while your code is converted to Microsoft intermediate language (MSIL) and inserted into
another portion of the file.
 Every type and member defined and referenced in a module or assembly is described within
metadata. When code is executed, the runtime loads metadata into memory and references it to
discover information about your code's classes, members, inheritance, and so on.
 Metadata is a description of every namespace, class, method, property, etc. contained within the
PE file.
The CLR uses metadata to:

Page 7 of 98
CS-20 : Programming with C# .Net
 Locate classes
 Load classes
 Generate native code
 Provide security
1.6 Managed Code
 Code executing under the control of the runtime is called managed code. Managed code is code
that is written to target the services of the managed runtime execution environment (like Common
Language Runtime in .NET Framework).
 The managed code is always executed by a managed runtime execution environment. Managed
refers to a method of exchanging information between the program and the runtime environment.
Managed refers to a method of exchanging information between the program and the runtime
environment.
 Because the execution of code is governed by the runtime environment, the environment can
guarantee what the code is going to do and provide the necessary security checks before executing
any piece of code. Because of the same reason the managed code also gets different services from
the runtime environment like Garbage Collection, type checking, exception handling, bounds
checking, etc.
 This way managed code does not have to worry about memory allocations, type safety, etc.
Managed code is always compiled into an Intermediate Language (MSIL in case of .NET
Framework).
 The compiler used by .NET framework to compile managed code compiles it into Intermediate
Language and provides the necessary information (metadata), to allow the CLR to locate methods
encoded in assembly modules, store and retrieve security information, handle exceptions.
Applications written in Java, C#, VB.NET, etc target a runtime environment which manages the
execution and code written using these types of languages is known as Managed Code.
 Managed code also provides platform independence. When we compile the managed code, the
code gets compiled to an intermediate language (MSIL) and an executable is created. When a user
runs the executable the Just in Time Compiler of CLR compiles the intermediate language into
native code specific to the underlying architecture.
 Since this translation happens by the managed execution environment (CLR), the managed
execution environment can make guarantees about what the code is going to do, because it can
actually reason about it.
1.7 Unmanaged Code
 Code that runs outside the runtime is called unmanaged code. In other words, code that is directly
executed by the Operating System is known as un-managed code. Unmanaged code is one that is
run by windows operating system.
 Unmanaged code typically targets the processor architecture and is always dependent on the
computer architecture. Unmanaged code is always compiled to target a specific architecture and
will only run on the intended platform.
 This means that if you want to run the same code on different architecture then you will have to
recompile the code using that particular architecture. Applications written in VB 6.0, C++, C,
COM components, ActiveX components and Microsoft Win32 API functions are examples of
unmanaged code.
 Unmanaged code is always compiled to the native code which is architecture specific.
Unmanaged code does not get any services from the managed execution environment.

Page 8 of 98
CS-20 : Programming with C# .Net
 In unmanaged code the memory allocation, type safety, security, etc needs to be taken care of by
the developer. Unmanaged executable files are basically a binary image, x86 code, loaded into
memory.
1.8 Visual Studio Editions
There are various visual studio editions which are as below:
1. Visual studio express
2. Visual studio professional
3. Visual studio premium
4. Visual studio tools for office
5. Visual studio ultimate
6. Visual studio team system
1. Visual studio express: These are a set of free light weight individual ideas. It includes the
development tools for supported platforms like web, windows & supported languages like VB,
C#. It does not support full MSDN library but it supports MSDN essential library.
2. Visual studio professional: Earlier it was known as standard edition but then after it was
renamed to the professional edition. It provides IDE for all supported development languages. It
also supports MSDN essential or full MSDN library, which is up to license.
3. Visual studio premium: It includes all the tools of professional edition, additionally includes
some other functionality like MSSQL server integration which allow you to create database
within the studio. It also includes remote debugging which allow debugging a remote system.
4. Visual studio tools for office: As the name says something related to MS office. It includes
tools for the Microsoft office suite. These tools are SDK and add-in.
5. Visual studio ultimate: Ultimate edition provides set of software and database development
tools, collaboration, metrics, and architecture, testing and reporting tools in addition to the
features provided by visual studio premium.
6. Visual studio team system: Earlier to the MS visual studio 2010 the team system included
following role-specific editions:
 Architecture edition
 Database edition
 Development edition
 Team explorer
 Test edition
1.9 Visual Studio IDE
 IDE stands for Integrated Development Environment.
 The Visual Studio 2008 IDE is a comprehensive environment for the development and execution
of .NET applications. An integrated development environment (IDE), also known as integrated
design environment and integrated debugging environment, is a type of computer software that
assists computer programmers to develop software. It integrates many different functions such as
design, editing, compiling, and debugging within a common environment.
 Given below is the image of Visual Studio IDE:

Page 9 of 98
CS-20 : Programming with C# .Net

IDE contains large number of components using them we can develop rich applications.
Some important components are listed below:
1 Menu Bar: Menu bar is a collection of menus, each of which contains a logical set of options for
performing various tasks. Some of the common menus are File, Edit, View, Build, Debug, and Help
menus. Every menu provides options for performing a particular type of task for instance, the File
Menu provides options for performing file management tasks, such as creating, opening, saving, and
closing files/applications.
2 Tool Bar: By default, Standard toolbar is appeared on Visual Studio .NET screen. We can add other
toolbars from view menu or right click on toolbar itself. The toolbar appears just below the menu bar
and have buttons as shortcuts to most common menu options and other tasks. Some of the common
toolbars include the Debug, Help, Layout, Save, Undo, Cut, Copy, Paste, Run, Comment, etc.
3 Tool Box: The Toolbox is a window that contains icons for various items and controls that you can
add to an application for designing. The icons in the Toolbox are logically grouped under different
tabs, such as Common Controls, Menus, and Toolbars & Data tabs. The toolbox window is the
window that gives us access to all controls, components, etc. For example, the Data tab displays tools
for creating datasets and making data connections, the Windows Forms tab displays tools for adding
controls to forms. If the Toolbox is note visible, then you can open it by selecting the
ViewToolbox option on the menu bar by pressing the CTRL+ALT+X keys.
4 Solution Explorer: The Solution Explorer window gives an overview of the solution we are working
with and lists all the files in the project i.e., project files, forms, classes, namespaces, database etc.
that we include in our solution.
Solution Explorer has a toolbar with various buttons such as Properties, Show All Files, Refresh,
View Code, and View Designer that perform specific actions. The Show All Files button displays all
the files that are part of the solution. The View Code button allows you to switch from the designer to
the Code Editor and the View Designer button allows you to switch from the Code Editor to the
designer.
5 Property Window: The properties window allows us to set properties for various objects at design
time. For example, if you want to change the font, font size, back colour, name, text that appears on a
button, textbox etc., you can do that in this window. You can view the properties window by selecting

Page 10 of 98
CS-20 : Programming with C# .Net
ViewProperties Window from the main menu or by pressing F4 on the keyboard. Mostly we use
this window to view and change the design-time properties.
6 Form Designer View: The form window helps you in designing the application. We can drag and
drop controls in this view of the form. We can also see some type of preview of our form. We can
open form designer view by pressingShift+F7.
7 Code Editor Window: Code Editor helps in adding the code or functionality for the applications.
This is the window that opens when we double-click on a form or any control. Notice the two drop-
down list boxes at the top of the code window. The left box allows us to select the object's code we
are working with and the right box allows us to select the part of code that we want to work. We can
open Code Editor Window by pressingF7.
8 Server Explorer: Server Explorer is the window that you can use to connect to a database server and
other services on the computer. The Server Explorer allows you to create, modify and close
connections to databases.
9 Output Window: The output window displays the results of building and running applications.
1.10 Variables
 Variables represent storage locations. Every variable has a type that determines the values to be
stored in the variable. C# is a type-safe language and the C# compiler guarantees that values
stored in variables are always of the appropriate type. After specifying a meaningful name and
appropriate data type to a variable, the variable is declared in program so that the complier can
easily recognize that the variable is declared with a specific data type.
 Variable is something that is used in a program to store data in memory. Variables are values that
can change as much as needed during the execution of a program.
 The declaration of a variable does 3 things:
 It tells the complier the name of the variable
 It tells the about the type of data a variable hold.
 It decides the scope of the variable.
 In C# all variables must be declared before they are used. In the declaration you must specify a
data type and a name for the variable so that memory can be set aside for the variable.
Syntax:<visibility><data type><variablename> = <value>;
 The visibility determines the accessibility of the variable (public, local, private) and the default is
private. The data type specifies what kind of data the variable will hold. Optionally the variable
can be initialized to a specific value. All variables must be initialized before they are used in any
calculation. If the variables are not initialized, the compilation of the program will fail.
1.10.1 Variable naming convention:
 Variable name must be begun with a letter or _.
 Variable name must not begin with digit.
 Variable name should not be a keyword.
 White space is not allowed in declaring variable name.
1.10.2 Reserved Keywords in C#:
abstract as base bool break byte case
checked class const continue decimal default delegate
else enum event explicit extern false finally
for foreach goto if implicit in int
is lock long namespace new null object

Page 11 of 98
CS-20 : Programming with C# .Net
override params private protected public readonly ref
sealed short sizeof stackalloc static string struct
throw true try typeof uint ulong unchecked
using virtual volatile void while char double
internal out sbyte this ushort catch return
do fixed switch interface unsafe operator float
1.10.3 Contextual Keywords in C#
add ascending by descending dynamic equals from
get global group in into join let
on orderby partial remove select set value
var whereyield

Example:
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string firstName = "John";
string lastName = "Doe";
Console.WriteLine("Name: " + firstName + " " + lastName);
Console.WriteLine("Please enter a new first name:");
firstName = Console.ReadLine();
Console.WriteLine("New name: " + firstName + " " + lastName);
Console.ReadLine();
}
}
}
Explanation:
First of all, we declare a couple of variables of the string type. A string simply contains text, as you can
see, since we give them a value straight away. Next, we output a line of text to the console, where we use
the two variables. The string is made up by using the + characters to "collect" the different parts. Next,
we urge the user to enter a new first name, and then we use the ReadLine () method to read the user input
from the console and into the firstName variable. Once the user presses the Enter key, the new first name
is assigned to the variable, and in the next line we output the name presentation again, to show the
change. We have just used our first variable and the single most important feature of a variable: The
ability to change its value at runtime.
1.10.4 Constants
 Constants are values which are known at compile time and do not change. In other words, the
variables whose values do not change during the execution of program are known as constants.
“Const” keyword is used to make any variable constant. This keyword describes an entity that
cannot be changed at program runtime. Essentially, it allows you to pull constant values such as
strings or integral types into part of the program text that is easier for you to manage and edit.

Page 12 of 98
CS-20 : Programming with C# .Net
The value assigned to a constant variable (using the const keyword) must be known at the time
of compilation.
Syntax: const datatype constantname = value;
 User must declare and initialize a constant, just as done in the following case or else an error
occurs.
const float PI = 3.14;
const int count=4;
 So, these values cannot be changed during the execution of a program.
 A constant can also be initialized using an expression such as:
const int length = 10;
const int breadth = length * 4;
 User cannot use a non-constant value in as expression, which is used by a constant such as:
int length = 10;
const int breadth = length * 2;//This is illegal statement
1.10.5 Strings
 Strings are collections of characters that are grouped together to form words or sentences. Strings
consist of sequences of characters contained in a string object. String is a predefined reference
type in C#. We use it to declare string type object.
 When we declare a string using string type, we are actually declaring the object of system
(namespace).
 String which is a built-in type provided in .NET Framework.
1.10.5.1 How to assign a string:
String mystring; //declaring
String mystring=”Hello World”; //Assigning
1.10.5.2 Obtaining length of C# String:
 The length of a string is obtained by accessing Lengthproperty of the String Object.
String mystring=”Hello World”;
System.Console.WriteLine(“My String Length :” + mystring.Length);
1.10.5.3 Concatenating Strings in C#:
 Strings is concatenated (i.e., joined together) simply by adding them together using the addition
operator (+). Also, user can concatenate the existing string by creating a new string.
String mystring=” Hello”;
String mystring1=” World”;
System.Console.WriteLine(mystring + mystring1);
 Strings may also be concatenated using Concat() method. This method takes two strings to be
joined as arguments and returns a third string containing the union of the two strings.
String mystring=” Hello”;
String mystring1=” World”;
String mystring2;
mystring2=String.Concat(mystring, mystring1);

Page 13 of 98
CS-20 : Programming with C# .Net
1.10.5.4 Comparing Strings in C#:
 String may also be compared using Compare() method. By default, Compare() method performs a
case sensitive comparison.
String mystring1=” Hello World”;
String mystring1=” Hello World”;
if(String.Comapre(mystring1,mystring2) == 0)
{
System.Console.WriteLine(“They match”);
}
else
{
System.Console.WriteLine ("They do not match");
}
If the Compare() method is called with a third boolean argument it is possible to control whether
the comparison is case sensitive or not. A true argument tells Compare() to ignore case when
performing the comparison:
String myString1 = "Hello World";
String myString2 = "HELLO WORLD";
if (String.Compare (myString1, myString2, true) == 0)
{
System.Console.WriteLine ("They match");
}
else
{
System.Console.WriteLine ("They do not match");
}
1.10.5.5 Changing String Case in C#:
 The case of the characters in a string may be changed using the ToUpper and ToLower methods.
Both of these methods return a modified string rather than changing the actual string.
string myString = "Hello World";
string newString;
newString = myString.ToUpper();
System.Console.WriteLine (newString); // Displays HELLO WORLD
newString = myString.ToLower();
System.Console.WriteLine (newString); // Displays hello world
1.10.5.6 Splitting a C# String into Multiple Parts
 A string may be separated into multiple parts using the Split() method. Split() takes as an
argument the character to use as the delimiter to identify the points at which the string is to be
split. Returned from the method call is an array containing the individual parts of the string. For
example, the following code splits a string up using the comma character as the delimiter.
string myString = "Red, Green, Blue, Yellow, Pink, Purple";
string[] myColors = myString.Split(',');
foreach (string color in myColors)
{
System.Console.WriteLine (color);
}

Page 14 of 98
CS-20 : Programming with C# .Net
The results are placed in an array called myColors and a foreach loop then reads each item from
the array and displays it:
The resulting output will read:
Red
Green
Blue
Yellow
Pink
Purple
1.10.5.7 Trimming and Padding C# Strings
 Unwanted leading and trailing spaces can be removed from a string using the Trim() method.
When called, this method returns a modified version of the string with both leading and trailing
spaces removed.
string myString = " hello ";
System.Console.WriteLine ("[" + myString + "]");
System.Console.WriteLine ("[" + myString.Trim() + "]");
 The above code will result in the following output:
[ hello ]
[hello]
 In inverse of the Trim() method are the PadLeft() and PadRight() methods. These methods allow
leading or trailing characters to be added to a string. The methods take as arguments the total
number of characters to which the string is to be padded and the padding character.
string myString = "hello";
string newString;
newString = myString.PadLeft(10, ' ');
newString = newString.PadRight(20, '*');
System.Console.WriteLine ("[" + newString + "]"); //Outputs [ hello**********]
1.10.5.8 C# String Replacement
 Parts of a string may be replaced using the Replace() method. This method takes the part of the
string to be replaced and the string with which it is to be replaced as arguments and returns a new
string reflecting the change. The Replace() method will replace all instances of the string.
string myString = "Hello World";
string newString;
newString = myString.Replace("Hello", "Goodbye");
System.Console.WriteLine (newString);
1.11 Data types
 Data types are used everywhere in a programming language like C#. The data type in a
programming element refers to what kind of data it can hold and how that data is stored. C# is a
strongly typed language; therefore every variable and object must have a declared type.In the C#
programming language, types are divided in three categories:
1. Value types
2. Reference types
3. Pointer types
 In CSharp it is possible to convert a value of one type into a value of another type. The operation
of Converting a Value Type to a Reference Type is called Boxing and the reverse operation is
called Unboxing.
Page 15 of 98
CS-20 : Programming with C# .Net

Data
Types

Value Pointer Reference


Types Types Types

Pre-defined User-defined Pre-defined User-defined


Types Types Types Types

Classes
Struct Enumeration Object String
Types Types Type Type Interfa
Integral Types ces
Delega
Floating-Point tes
Types Array
Decimal Types

Boolean Types

Nullable Types

1.11.1 Value types:


 Value types are of fixed length. The value types hold actual values. These value types are stored
in “stack” memory and these value types are fixed in size. When value of one variable is assigned
to another variable, the value is actually copied. This means two identical copies of the value are
available in the memory. Value types have different default values. For example, Boolean default
value is false, decimal 0, string an empty string "".
1.11.1.1 Pre-defined Types:
1) Struct Types:
 Struct type is special form of classes having the features of Value types. Struct types are stored on
a stack, because stacks are the efficient and convenient means of storing and accessing the types.
Structs can also have constructors, methods, properties, operators, events, etc. Struct members
cannot be declared as protected. While declaring struct types, the fields can be initialized only
when they are declared as const or static. Struct types are created using struct keyword. When
user create struct object and assign it to a variable, the variable holds the complete value of the
struct object.
 Struct types are categorized into five categories:
 Integral types: C# uses a set of basic data types, which are known as the integral type. It
consists of sbyte, byte, ushort, int, uint, long, ulong, and char. Integral type hold whole
numbers. i.e. 123, -123, 3598.
 Floating Point: The floating-point types take the value in fractions, i.e. -123.56, 256.36.
The floating points are divided into two types: float and double.
 Decimal types: The decimal types are equivalent to a long integer that behaves as if it
were a floating-point number. Decimal values are intended to be used for the calculations
in which truncation beyond the decimal point is not desired.

Page 16 of 98
CS-20 : Programming with C# .Net
 Boolean types: Boolean types (bool) are used to test a particular condition during
execution of a program. Boolean Types takes only two values: True or False.
 Nullable types: The Nullable types are generally used with database or when a user does
not want to assign a value to a variable of any data type.
2) Enumeration Types:
 The enum keyword is used to declare an enumeration, a distinct type consisting of a set of
named constants called the enumerator list. Enumerations are the user-defined integer data types
that are declared using the enum keyword. The default underlying type of the enumeration
elements is int.By default, the first enumerator has the value 0, and the value of each successive
enumerator is increased by 1.
Example:
using System;
public class EnumTest {
enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
static void Main() {
int x = (int)Days.Sun;
int y = (int)Days.Fri;
Console.WriteLine("Sun = {0}", x);
Console.WriteLine("Fri = {0}", y);
}
}
Output:
Sun = 2
Fri = 7
1.11.2 Pointer types:
 The unsafe keyword is used to define an unsafe context where you are free to use the pointer.
Pointer types do not inherit from object and no conversions exist between pointer types and
object. Also, boxing and unboxing do not support pointers. However, you can convert between
different pointer types and between pointer types and integral types. A pointer variable is used to
store the address of another variable. A pointer cannot point to a reference or to a struct that
contains references because it is possible for an object reference to be garbage collected even if a
pointer is pointing to it. The GC does not keep track of whether an object is being pointed to by
any pointer types.
 The general form of declaring a pointer type is as shown below
type *variable_name;
For example, the following statement
int *x ;
 Declares a pointer variable x, which can hold the address of an int type. The reference operator
(&) can be used to get the memory address of a variable.
int x = 100;
 The &x gives the memory address of the variable x, which we can assign to a pointer variable.
int *ptr=&x;
Console.WriteLine((int)ptr)//Displays the memory address
Console.WriteLine(*ptr) // Displays the value at the memory address.

Page 17 of 98
CS-20 : Programming with C# .Net
1.11.3 Reference types:
 Reference types hold references to values stored somewhere in memory. Reference types are
stored in “heap” memory and these types are not fixed in size. When the value has to be assigned
between two reference variables, only the reference is copied and the actual value remains the
same in the memory location.
1.11.3.1 Pre-defined Types:
1) Object Type:
 The object type is an alias for Object in the .NET Framework. In the unified type system of C#,
all types, predefined and user-defined, reference types and value types, inherit directly or
indirectly from Object. You can assign values of any type to variables of type object. When a
variable of a value type is converted to object, it is said to be boxed. When a variable of type
object is converted to a value type, it is said to be unboxed.
 The following sample shows how variables of type object can accept values of any data type
and how variables of type object can use methods on Object from the .NET Framework.
class ObjectTest
{
public int i = 10;
}
class MainClass2
{
static void Main()
{
object a;
a = 1; // an example of boxing
Console.WriteLine(a);
Console.WriteLine(a.GetType());
Console.WriteLine(a.ToString());
a = new ObjectTest();
ObjectTest classRef;
classRef = (ObjectTest)a;
Console.WriteLine(classRef.i);
}
}
/* Output
1
System.Int32
1
* 10
*/
2) String Type:
 String type is used for creating and manipulating strings in C#. Various operations can be
performed on strings such as copying, comparing, and concatenating. Examples are discussed
above in String.
1.11.3.2 User-defined Types:
1) Classes:

Page 18 of 98
CS-20 : Programming with C# .Net
 C# is purely object-oriented language. Classes provide the best approach to group together the
logically related items and functions that work on them. Class is nothing but a collection of data
members and member functions.
Example:
using system;
Class student
{
int rno;
string nm;
public student()
{
rno=1;
nm=”Krishna”;
}
public void printdata()
{
Console.WriteLine(“Roll no={0} Name= {1}”, rno, nm ) ;
}
};
class mainprog()
{
student s1 = new student();
s1.printdata();
Console.Read();
}
2) Interfaces:
 Interfaces are a collection of members, such as methods, delegates, events and properties, which
are implemented by classes. An interface contains only the signatures of methods, delegates or
events. The implementation of the methods is done in the class that implements the interface.
Interfaces cannot be instantiated but user cannot use them to offer a set of functionalities that is
common to several different classes.
Example:
using system;
interface hello
{
void welcome();
}
class interfclass : hello
{
public void welcome()
{
Console.WriteLine(“Hello All Good Day”);
}
}
class mainclass()
{
static void Main()

Page 19 of 98
CS-20 : Programming with C# .Net
{
interfclass i1 = new interfclass();
i1.welcome();
Console.Read();
}
}
3) Delegate:
 Delegates are the objects that point towards a method which matches its signature to that
delegate. A delegate is a type-safe object that can point to another method in the application,
which can be invoked at later time. Any method that matches the delegate's signature, which
consists of the return type and parameters, can be assigned to the delegate.
 A delegate type maintains three important pieces of information:
1. The name of the method on which it makes calls.
2. Any argument (if any) of this method.
3. The return value (if any) of this method.
Example:
using System;
delegate void MyDelegate(string s);
class MyClass
{
public static void Hello(string s)
{
Console.WriteLine(" Hello, {0}!", s);
}
public static void Goodbye(string s)
{
Console.WriteLine(" Goodbye, {0}!", s);
}
public static void Main()
{
MyDelegate a, b, c, d;
// Create the delegate object a that references
// the method Hello:
a = new MyDelegate(Hello);
// Create the delegate object b that references
// the method Goodbye:
b = new MyDelegate(Goodbye);
// The two delegates, a and b, are composed to form c:
c = a + b;
Console.WriteLine("Invoking delegate a:");
a("A");
Console.WriteLine("Invoking delegate b:");
b("B");
Console.WriteLine("Invoking delegate c:");
c("C");
}

Page 20 of 98
CS-20 : Programming with C# .Net
}
Output:
Invoking delegate a:
Hello, A!
Invoking delegate b:
Goodbye, B!
Invoking delegate c:
Hello, C!
Goodbye, C!
1.12 Boxing and Unboxing

1.13 Operators

1.14 Arrays
 An array is a fixed collection of same-type data that are stored contiguously and that are
accessible by an index. Arrays in C# work similarly to how arrays work in most other popular
languages. C# arrays are zero indexed; that is, the array indexes start at zero. The position of the
last item on an array will total number of items - 1. So if an array has 10 items, the last 10th item
is at 9th position.
 In C#, arrays can be declared as fixed length or dynamic. A fixed length array can store a
predefined number of items. A dynamic array does not have a predefined size. The size of a
dynamic array increases as you add new items to the array.
 Arrays are declared much like variables, with a set of [] brackets after the datatype, like this:
Page 21 of 98
CS-20 : Programming with C# .Net
string[] names;
int[] intArray;
 You need to instantiate the array to use it, which is done like this:
string[] names = new string[2];
 Declares an array that can store 5 items starting from index 0 to 4:
int[] intArray;
intArray = new int[5];
1.14.1 Defining arrays of different types
 In C#, arrays are objects. That means that declaring an array doesn't create an array. After
declaring an array, you need to instantiate an array by using the "new" operator.
 The following code defines arrays of double, char, bool, and string data types.
double[] doubleArray = new double[5];
char[] charArray = new char[5];
bool[] boolArray = new bool[2];
string[] stringArray = new string[10];
1.14.2 Initializing Arrays
 Once an array is declared, the next step is to initialize an array. The initialization process of an
array includes adding actual data to the array.
 The following code creates an array of 3 items and values of these items are added when the array
is initialized.
// Initialize a fixed array
int[] staticIntArray = new int[3] {1, 3, 5};
OR
// Initialize a fixed array one item at a time
int[] staticIntArray = new int[3];
staticIntArray[0] = 1;
staticIntArray[1] = 3;
staticIntArray[2] = 5;
 The following code declares a dynamic array with string values.
// Initialize a dynamic array items during declaration
string[] strArray = new string[] { "Ajay", "Mike", "Goldie", "Saniya", "Nehwal" };
1.14.3 Accessing Arrays
 We can access an array item by passing the item index in the array. The following code creates an
array of three items and displays those items on the console.
// Initialize a fixed array one item at a time
int[] staticIntArray = new int[3];
staticIntArray[0] = 1;
staticIntArray[1] = 3;
staticIntArray[2] = 5;
// Read array items one by one
Console.WriteLine(staticIntArray[0]);
Console.WriteLine(staticIntArray[1]);
Console.WriteLine(staticIntArray[2]);
 This method is useful when you know what item you want to access from an array.
1.14.4 Accessing an array using a foreach Loop
 The foreach control statement (loop) is used to iterate through the items of an array. For example,
the following code uses foreach loop to read all items of an array of strings.

Page 22 of 98
CS-20 : Programming with C# .Net
// Initialize a dynamic array items during declaration
string[] strArray = new string[] { "Ajay", "Mike", "Goldie", "Saniya", "Nehwal" };
// Read array items using foreach loop
foreach (string str in strArray)
{
Console.WriteLine(str);
}
 This approach is used when you do not know the exact index of an item in an array and needs to
loop through all the items.
1.14.5 Array Types
 Arrays can be divided into the following categories:
1. Single-dimensional arrays
2. Multidimensional arrays or rectangular arrays
3. Jagged arrays
1.14.5.1 Single Dimension Arrays:
 Single-dimensional arrays are the simplest form of arrays. An array having only one dimension is
called a single dimension array. These types of arrays are used to store number of items of a
predefined type. All items in a single dimension array are stored contiguously starting from 0 to
the size of the array -1.
 The following code declares an integer array that can store 3 items.
int[] intArray;
intArray = new int[3];
 The following code declares and initializes an array of three items of integer type.
int[] staticIntArray = new int[3] {1, 3, 5};
 The following code declares and initializes an array of 5 string items.
string[] strArray = new string[5] { "Ajay", "Mike", "Goldie", "Saniya", "Nehwal" };
 User can even directly assign these values without using the new operator.
string[] strArray = { "Ajay", "Mike", "Goldie", "Saniya", "Nehwal" };
 You can initialize a dynamic length array as follows:
string[] strArray = new string[]{ "Ajay", "Mike", "Goldie", "Saniya", "Nehwal" };
1.14.5.2 Multi-Dimensional Arrays:
 Multidimensional arrays are available using a special syntax in the C# language. A multi-
dimensional array, also known as a rectangular array is an array with more than one dimension. A
multidimensional array is a series of arrays so that each array contains its own sub-array(s).
 User can create an array variable that represents various lists, and each list contains various
internal lists, and each internal list contains its own elements. This is referred to as a
multidimensional array. One of the rules user must follow is that, as always, all members of the
array must be of the same type.
 Declaring a multi-dimensional array
 A multi dimension array is declared as following:
string [,] mutliDimStringArray;
 A multi-dimensional array can be fixed-sized or dynamic sized.
 Initializing multi-dimensional arrays
int[,] numbers = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
string[,] names = new string[2, 2] { { "Rosy", "Amy" }, { "Peter", "Albert" } };
 The following code snippet creates two multi-dimensional arrays with no limit.

Page 23 of 98
CS-20 : Programming with C# .Net
int[,] numbers = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
string[,] names = new string[,] { { "Rosy", "Amy" }, { "Peter", "Albert" } };
 You can also omit the new operator as we did in single dimension arrays. You can assign these
values directly without using the new operator. For example:
int[,] numbers = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
string[,] names = { { "Rosy", "Amy" }, { "Peter", "Albert" } };
 We can also initialize the array items one item at a time. The following code is an example of
initializing array items one at a time.
int[,] numbers = new int[3, 2];
numbers[0, 0] = 1;
numbers[1, 0] = 2;
numbers[2, 0] = 3;
numbers[0, 1] = 4;
numbers[1, 1] = 5;
numbers[2, 1] = 6;
Example:
// Two-dimensional array.
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// The same array with dimensions specified.
int[,] array2Da = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// A similar array with string elements.
string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" },{ "five", "six" } };
// Three-dimensional array.
int[, ,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } }, { { 7, 8, 9 }, { 10, 11, 12 } } };
// The same array with dimensions specified.
int[, ,] array3Da = new int[2, 2, 3] { { { 1, 2, 3 }, { 4, 5, 6 } }, { { 7, 8, 9 }, { 10, 11, 12 } } };
// Accessing array elements.
System.Console.WriteLine(array2D[0, 0]);
System.Console.WriteLine(array2D[0, 1]);
System.Console.WriteLine(array2D[1, 0]);
System.Console.WriteLine(array2D[1, 1]);
System.Console.WriteLine(array2D[3, 0]);
System.Console.WriteLine(array2Db[1, 0]);
System.Console.WriteLine(array3Da[1, 0, 1]);
System.Console.WriteLine(array3D[1, 1, 2]);
Output:
1
2
3
4
7
three
8
12

Page 24 of 98
CS-20 : Programming with C# .Net
1.14.5.3 Jagged Arrays:
 A jagged array is an array whose elements are also array. The elements of jagged array can be
different dimensions and sizes. Jagged arrays are arrays of arrays. The elements of a jagged array
are other arrays.
Declaring Jagged Arrays
 Declaration of a jagged array involves two brackets. For example, the following code snippet
declares a jagged array that has three items of an array.
int[][] intJaggedArray = new int[3][];
 The following code declares a jagged array that has two items of an array.
string[][] stringJaggedArray = new string[2][];
Initializing Jagged Arrays
 Before a jagged array can be used, its items must be initialized. The following code snippet
initializes a jagged array; the first item with an array of integers that has two integers, second item
with an array of integers that has 4 integers, and a third item with an array of integers that has 6
integers.
// Initializing jagged arrays
intJaggedArray[0] = new int[2];
intJaggedArray[1] = new int[4];
intJaggedArray[2] = new int[6];
 We can also initialize a jagged array's items by providing the values of the array's items. The
following code initializes item an array's items directly during the declaration.
// Initializing jagged arrays
intJaggedArray[0] = new int[2]{2, 12};
intJaggedArray[1] = new int[4]{4, 14, 24, 34};
intJaggedArray[2] = new int[6] {6, 16, 26, 36, 46, 56 };
Accessing Jagged Arrays
 We can access a jagged array's items individually in the following way:
Console.Write(intJaggedArray3[0][0]);
Console.WriteLine(intJaggedArray3[2][5]);
 We can also loop through all of the items of a jagged array. The Length property of an array helps
a lot; it gives us the number of items in an array. The following code snippet loops through all of
the items of a jagged array and displays them on the screen.
// Loop through all items of a jagged array
for (int i = 0; i < intJaggedArray3.Length; i++)
{
System.Console.Write("Element({0}): ", i);
for (int j = 0; j < intJaggedArray3[i].Length; j++)
{
System.Console.Write("{0}{1}", intJaggedArray3[i][j], j == (intJaggedArray3[i].Length -
1) ? "" : " ");
}
System.Console.WriteLine();
}
Example:
class ArrayTest
Page 25 of 98
CS-20 : Programming with C# .Net
{
static void Main()
{
// Declare the array of two elements:
int[][] arr = new int[2][];

// Initialize the elements:


arr[0] = new int[5] { 1, 3, 5, 7, 9 };
arr[1] = new int[4] { 2, 4, 6, 8 };

// Display the array elements:


for (int i = 0; i < arr.Length; i++)
{
System.Console.Write("Element({0}): ", i);

for (int j = 0; j < arr[i].Length; j++)


{
System.Console.Write("{0}{1}", arr[i][j], j == (arr[i].Length - 1) ? "" : " ");
}
System.Console.WriteLine();
}
}
}
Output
Element(0): 1 3 5 7 9
Element(1): 2 4 6 8
1.15 Decision Statements
 Decision statements are also known as conditional, decision making, or branching statements. A
series of statements surrounded by curly braces form a block of code. Variables or constants
declared within a code block are only available to statements within the same code block. C#
language also processes such decision-making capabilities and supports the following known as
decision statements:
 Selection Statements in C# are the statements that cause the flow of the program to change
based on a certain condition. The program control checks the condition before executing the code
inside the selection statement. C# supports two types of selection statements:
1. If statement
2. Switch statement
1.15.1 If statement:
 The if-statement is a selection statement. This statement works with an expression that evaluates
to a Boolean value. If the Boolean expression evaluates to true, the statement embedded in the if
clause will be executed. If the Boolean expression evaluates to false, the statement in the if clause
will not be executed. The if statement can be followed by an else statement that is executed if the
Boolean expression used in the if clause evaluates too false.
 In other words, in the if statement, a condition or set of condition are checked. If the condition is
fulfilled, the program control enters the if block and execute all the statements stated inside if
block.

Page 26 of 98
CS-20 : Programming with C# .Net
Syntax:
if (expression)
statement1
[else
statement2]
Expression
 An expression that can be implicitly converted to bool or a type that contains overloading of the
true and false operators.
statement1
The embedded statement(s) to be executed if expression is true.
statement2
The embedded statement(s) to be executed if expression is false.

Syntax: (Nested if-else)


if( conditional-expression 1)
{
if( conditional-expression 2)
{
// code statements here.
}
else
{
// code statements here.
}
}
else
{
// code statements here.
}
Example: Enter a character from the keyboard and the program checks if the input character is an
alphabetic character. If so, it checks if it is lowercase or uppercase and message is displayed.
// statements_if_else.cs
// if-else example
using System;
public class IfTest
{
public static void Main()
{
Console.Write("Enter a character: ");
char c = (char) Console.Read();
if (Char.IsLetter(c))
if (Char.IsLower(c))
Console.WriteLine("The character is lowercase.");
else
Console.WriteLine("The character is uppercase.");
else
Console.WriteLine("The character is not an alphabetic character.");
}
Page 27 of 98
CS-20 : Programming with C# .Net
}
Input
2
Output:
Enter a character: 2
The character is not an alphabetic character.
Run #2:
Enter a character: A
The character is uppercase.
Run #3:
Enter a character: h
The character is lowercase.
1.15.2 Switch statement:
 The switch statement in C# is a selection statement that handles multiple selections. This
statement evaluates an expression and compares the expression's value to a number of cases.
Each case is associated with a statement list that is called a switch section. C# executes a
statement list associated with the switch section that matches the expression's value. Switch
statement allows you to compare an expression with different values.
 In other words, the switch statement is like a set of if statements. It's a list of possibilities, with an
action for each possibility, and an optional default action, in case nothing else evaluates to true.
switch (expression)
{
case constant-expression-1:
code block-1
break;

case constant-expression-2:
code block-2
break;

case constant-expression-3:
code block-3
break;

default:
code block
break;
}
 Switch sections start with the keyword case, which is followed by a constant expression. A colon
follows the constant expression, and the statement list follows the colon. The break specifies the
end of the statement block.
 If-else block are time consuming then switch case block.
Example:
using System;
class switchex
{
static void main()
Page 28 of 98
CS-20 : Programming with C# .Net
{
string year;
Console.Write(“Enter year :”);
year=Console.ReadLine();
switch (year)
{
case “FY”:
Console.Write(“First Year”);
break;
case “SY”:
Console.Write(“Second Year”);
break;
case “TY”:
Console.Write(“Third Year”);
break;
default:
Console.Write(“Enter proper year”);
break;
}
Console.Read();
}
}
1.16 Loop Statements
 Loop statements are the primary mechanism for telling a computer that a sequence of tasks needs
to be repeated a specific number of times. Looping statements in C# create loops and execute a
code for a given number of times. In other words, looping structures are used when a group of
statements is to be executed repeatedly, until a condition is TRUE or until a condition is FALSE.
 The following illustration shows a loop structure that runs a set of statements until a condition
becomes true.
C# supports the following loop structures:
1. For loop
2. While loop
3. Do…While loop
4. For each loop

1.16.1 For Loop:


The for loop is the most structured. The forloop is used when a loop
is executed a specific number of times. One ofthe benefits of using
the forloop is that all the conditions for initializing and maintaining
the loop are located in one place, at the top of the loop. The forloop
has four components: the initialization expression, the conditional
expression, the controlled statement, and theiteration expression. The
forloop is also an entry-controlled loop. These components are
executed in the following order:
The initialization expression is run once when the forloop begins execution. The conditional expression is
evaluated to determine whether the forloop should continue executing; if the expression has a value of
Page 29 of 98
CS-20 : Programming with C# .Net
false, control passes to the statements after the forloop. The controlled statement is executed if the
conditional expression evaluates to true. The iteration expression is executed once after each execution of
the controlled statement.
Syntax:
for(initialization; condition; iteration)
{
controlled-statement;
body of the loop;
}
The algorithm for the for loop is shown in Figure:
Example:
using System;
class forloopex
{
static void Main()
{
int i;
for (i = 0; i < 10; i++)
{
Response.Write("value of i = " + i + "<br />");
}
}
}

1.16.2 While Loop:


 The C# while statement continually executes a block of statements until a specified expression
evaluates too false. This expression is evaluated before the loop body statements are executed.
 Like if statement the while statement evaluates the
expression, which must return a Boolean value. If the expression
evaluates to true, the while statement executes the statement(s) in
the while block. The while statement continues testing the
expression and executing its block until the expression evaluates
too false.
Syntax:
while(condition)
{
//statements
}
The algorithm for the while loop is shown in Figure:

Page 30 of 98
CS-20 : Programming with C# .Net
Example:
using System;
class WhileTest
{
public static void Main()
{
int n = 1;

while (n < 6)
{
Console.WriteLine("Current value of n is {0}", n);
n++;
}
}
}
1.16.3 Do…While loop:
 do..while loop is used in situation when you may want to execute the loop at least one time and
then check the condition. The difference between do..while and while is that do..while evaluates
its expression at the bottom of the loop instead of the top. Therefore, the statements within the do
block are always executed at least once.
Syntax:
do
{
statement;
}while(condition);

The algorithm for the do…while loop is shown in Figure:


Example:
using System;
namespace Doloop{
class DoWhileLoop { public static void Main(string[] args)
{ int i = 0; // initialize an int variable
// iterate the loop while the value of i is still less than 10.
do { Console.WriteLine(i);
i++; // increment the value of i
} while (i < 10);
Console.ReadLine(); } }}
1.16.4 For each loop:
 The foreach loop in C# executes a block of code on each element in an array or a collection of
items. When executing foreach loop it traversing items in a collection or an array. The foreach
loop is useful for traversing each item in an array or a collection of items and displayed one by
one.
 The foreach statement repeats a group of statements for each element in an array. Each time the
controlled statement or statement block for a foreach loop is executed, the locally declared
variable is updated to refer to the next member in the collection, simplifying the code in the loop
body.

Page 31 of 98
CS-20 : Programming with C# .Net
Syntax:
foreach(<type><item name> in <list>)
{
//statements
}
Example:
class ForEachTest
{
static void Main(string[] args)
{
int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
foreach (int i in fibarray)
{
System.Console.WriteLine(i);
}
}
}

1.17 Exception using try-catch-finally


 The .NET framework provides a rich set of standard exceptions that are used during exceptions
handling.Exception is a runtime error that arises because of some expected situations. Exception
is the inbuilt object that handles errors, and this follows the word System namespace.All the
exceptions are directly or indirectly inherited from the Exception class. The exception handling
feature in C# helps you to deal with any unexpected situations that occur when a program is
executed. In C#, user can handle exceptions using the try…catch…finally statement. The try
encloses the statements that might throw an exception whereas catch handles an exception if one
exists. The finally can be used for doing any clean-up process. The general form try-catch-finally
in C# is shown below:
try
{
// Statement which can cause an exception.
}
catch(Type x)
{
// Statements for handling the exception
}
finally
{
//Any
}

Page 32 of 98
CS-20 : Programming with C# .Net
 The try block can exist either with one or more catch blocks or a finally block or with both catch
and finally blocks. If there is no exception occurred inside the try block, the control directly
transfers to finally block. We can say that the statements inside the finally block is executed
always. In C#, exceptions are nothing but objects of the type Exception. The Exception is the
ultimate base class for any exceptions in C#.
Example:
//C#: Exception Handling
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine(div);
}
catch(DivideByZeroException de)
{
Console.WriteLine ("Exception occured");
}
finally
{
Console.WriteLine("Finally Block");
}
Console.WriteLine("the Result is {0}");
}
}

Page 33 of 98
CS-20 : Programming with C# .Net
2.1 Class
 A class is a construct that enables you to create your own custom types by grouping together
variables of other types, methods and events. A class is like a blueprint. It defines the data and
behaviour of a type. A class is a group of related methods and variables.
 Classes are declared by using the keyword class followed by the class name and a set of class
members surrounded by curly braces. Every class has a constructor, which is called automatically
any time an instance of a class is created.
 It takes the following form::
[modifiers] class identifier [:base-list] { class-body }[;]

1. modifiers (Optional)
The allowed modifiers are new, abstract, sealed, and the four access modifiers.
2. identifier
The class name.
3. base-list (Optional)
A list that contains the one base class and any implemented interfaces, all separated by
commas.
4. class-body
Declarations of the class members.Fields, properties, methods, and events on a class are
collectively referred to as class members.

Syntax:
class TestClass
{
// Methods, properties, fields, events, delegates
// and nested classes go here.
}
Example:
public class Person {
// Field
public string name;
// Constructor
public Person() {
name = "unknown";
}
// Method
public void SetName(string newName)
{
name = newName;
}
}
class TestPerson
{
static void Main()
{
Person p = new Person();
Console.WriteLine(person.name);

Page 34 of 98
CS-20 : Programming with C# .Net
p.SetName("John Smith");
Console.WriteLine(p.name);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
Output:
unknown
John Smith
2.2 Object
 A class or struck definition is like a blueprint that specifies what the type can do. An object is
basically a block of memory that has been allocated and configured according to the blueprint.
Objects are also called instances. An object is block of memory that contains space to store all the
instance variables.
 An object doesn't exist until an instance of the class has been created; the class is just a definition.
When the object is physically created, space for that object is allocated in RAM.
 It is possible to have multiple objects created from one class. “new” keyword is used to create an
object.
 An object is a software bundle of variables and related methods.
 Objects are instance of classes.
 Declaration of an Object in C#.NET:
ClassName objectName=new ClassName();
E.g.: Person objPerson= new Person();
2.3 Encapsulation
Encapsulation is defined as the wrapping up of data and information under a single unit. It is the
mechanism that binds together the data and the functions that manipulate them. 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 its 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.

Example

// C# program to illustrate encapsulation


using System;
public class DemoEncap {
// private variables declared
// these can only be accessed by
// public methods of class
private String studentName;
private int studentAge;
// using accessors to get and
// set the value of studentName

Page 35 of 98
CS-20 : Programming with C# .Net
public String Name
{
get { return studentName; }
set { studentName = value; }
}
// using accessors to get and
// set the value of studentAge
public int Age
{
get { return studentAge; }
set { studentAge = value; }
}
}
// 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& quot”;
// 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);
}
}
2.4 Inheriting a class
 The most important reason for using OOP is to promote the reusability of code and eliminate
redundancy of code. Inheritance is a relationship between base class and parent class. Inheritance
is the ability to create classes which inherits certain aspects from parent classes. A parent class is
at a higher level in the class hierarchy as compared to the child class. Inheritance enables you to
create new classes that reuse, extend, and modify the behaviour that is defined in other classes.
The class whose members are inherited is called the base class, and the class that inherits those
members is called the derived class.
 Also Inheritance means create new classes based on an existing class. The new class will have
combined features of both the class. In other words, when a new class needs same members as an
existing class then instead of creating those members again in new class, the new class can be
created from existing class, which is called as inheritance.
 When you define a class to derive from another class, the derived class implicitly gains all the
members of the base class, except for its constructors and destructors. The derived class can
thereby reuse the code in the base class without having to re-implement it. In the derived class,
Page 36 of 98
CS-20 : Programming with C# .Net
you can add more members. In this manner, the derived class extends the functionality of the base
class.
Syntax:
[Access Modifier] class ClassName : baseclassname
{ }
 Classes can inherit from another class. This is accomplished by putting a colon after the class
name when declaring the class, and naming the class to inherit from—the base class—after the
colon, as follows:
public class A
{
public A() { }
}
public class B : A
{
public B() { }
}
. Advantages:
 Inheritance is reusability of the code.
 Code is easy to manage and divided into parent and child classes.
 Inheritance provides a clear model structure which is easy to understand without much
complexity
 classes become grouped together in a hierarchical tree structure
 Inheritance reduces maintenance problems, as changes need only to be made in one class,
rather than throughout a series of related classes. Inheritance can be classified to 5 types:
2.4.1 Single Inheritance:
When a single derived class is created from a single base class then the inheritance is called as single
inheritance.

2.4.2 Hierarchical Inheritance:


When more than one derived class is created from a single base class, then that inheritance is called as
hierarchical inheritance.

2.4.3 Multi-Level Inheritance:


When a derived class is created from another derived class, then that inheritance is called as multi-level
inheritance.

Page 37 of 98
CS-20 : Programming with C# .Net

2.4.4 Hybrid Inheritance:


Any combination of single, hierarchical and multi-level inheritances is called as hybrid inheritance.

2.4.5 Multiple Inheritance:


When a derived class is created from more than one base class then that inheritance is called as multiple
inheritance. But multiple inheritance is not supported by .net using classes and can be done using
interfaces.

2.4.6 Fields
 Fields store the data a class needs to fulfil its design. A field is a variable of any type that is
declared directly in a class or struct. Fields are members of their containing type. Fields typically
store the data that must be accessible to more than one class method and must be stored for longer
than the lifetime of any single method.
 Fields are initialized immediately before the constructor for the object instance is called. Fields
are declared within the class block by specifying the access level of the field, followed by the type
of the field, followed by the name of the field. For example:
public class CalendarDate
{
public int month;
public int day;
public int year;
}
 Accessing a field in an object is done by adding a period after the object name, followed by the
name of the field, as in objectname.fieldname. For example:
CalendarDate birthday = new CalendarDate();
birthday.month = 7;
 Fields can be marked as public, private, protected. These access modifiers define how users of the
class can access the fields.
 A field can optionally be declared static. This makes the field available to callers at any time,
even if no instance of the class exists.

Page 38 of 98
CS-20 : Programming with C# .Net
 A field can be declared readonly. A read-only field can only be assigned a value during
initialization or in a constructor. A static readonly field is very similar to a constant, except that
the C# compiler does not have access to the value of a static read-only field at compile time, only
at run time.
2.4.7 Properties
 Properties are members that provide a flexible mechanism to read, write, or compute the values of
private fields. A property does not haves storage locations. Properties enable a class to expose a
public way of getting and setting values, while hiding implementation or verification code.
 A get property accessor is used to return the property value, and a set accessor is used to assign a
new value. These accessors can have different access levels. The value keyword is used to define
the value being assigned by the set indexer.
 Properties that do not implement a set method are read only. Properties provide the opportunity to
protect a field in a class by reading and writing to it through the property.
 There are 3 types of properties:
1. Read/Write(Get/Set)
2. Read-only
3. Write-only
Syntax:
[accessmodifier] returntype proprtyname()
{
get
{
return value;
}set
{
varname=value;
}
}
Example:
using System;
class MyClass
{
private int x;
public int X;
{
get
{
return x;
}
set
{
x=value;
}
}
}
class MyClient
{
public static void Main()
Page 39 of 98
CS-20 : Programming with C# .Net
{
MyClass mc = new MyClass();
mc.X = 10;
int xVal= mc.X;
Console.WriteLine(xVal);//Displays 10
}
}
2.5 Polymorphism
 Polymorphism means "many forms", and it occurs when we have many classes that are related to
each other by inheritance.
 Like we specified in the previous chapter; Inheritance lets us inherit fields and methods from
another class. Polymorphism uses those methods to perform different tasks. This allows us to
perform a single action in different ways.
 For example, think of a base class called Animal that has a method called animalSound(). Derived
classes of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own
implementation of an animal sound (the pig oinks, and the cat meows, etc.):
Example:
classAnimal// Base class (parent)
{
Public void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}
classPig:Animal// Derived class (child)
{
Public void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}
classDog:Animal// Derived class (child)
{
Public void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}
2.6 Creating Class and Objects Methods with “ref” and “out” Parameters

ref keyword out keyword

It is necessary the parameters should initialize It is not necessary to initialize parameters


before it pass to ref. before it pass to out.

It is not necessary to initialize the value of a It is necessary to initialize the value of a

Page 40 of 98
CS-20 : Programming with C# .Net

parameter before returning to the calling parameter before returning to the calling
method. method.

The passing of value through ref parameter is The declaring of parameter through out
useful when the called method also need to parameter is useful when a method return
change the value of passed parameter. multiple values.

When ref keyword is used the data may pass in When out keyword is used the data only passed
bi-directional. in unidirectional.

Example: Example:
// C# program to illustrate the // C# program to illustrate the
// concept of ref parameter // concept of ref parameter
using System; using System;

class GFG { class GFG {

// Main Method // Main Method


public static void Main() public static void Main()
{ {

// Assign string value // Assign string value


string str = "MJKACC"; string str = " MJKACC";

// Pass as a reference parameter // Pass as a reference parameter


SetValue(ref str); SetValue(ref str);

// Display the given string // Display the given string


Console.WriteLine(str); Console.WriteLine(str);
} }

static void SetValue(ref string str1) static void SetValue(ref string str1)
{ {

// Check parameter value // Check parameter value


if (str1 == " MJKACC") { if (str1 == " MJKACC") {

Console.WriteLine("Hello!!MJK"); Console.WriteLine("Hello!!MJK");
} }

// Assign the new value // Assign the new value


// of the parameter // of the parameter
str1 = " MJKACCCollege"; str1 = " MJKACCCollege";
} }
} }

Page 41 of 98
CS-20 : Programming with C# .Net
2.7 Static and Non-Static Members
 In C#, one is allowed to create a static class, by using static keyword. A static class can only contain
static data members and static methods. It is not allowed to create objects of the static class and since
it does not allow to create objects it means it does not allow instance constructor. Static classes
are sealed, means you cannot inherit a static class from another class.
Syntax:
static class Class_Name
{
// static data members
// static method
}
In C#, the static class contains two types of static members as follows:
 Static Data Members: As static class always contains static data members, so static data members
are declared using static keyword and they are directly accessed by using the class name. The
memory of static data members is allocating individually without any relation with the object.
Syntax:
static class Class_name
{
public static nameofdatamember;
}
Static Class Non-Static Class

Non-Static class is not defined by using static


Static class is defined using static keyword.
keyword.

In static class, you are not allowed to create In non-static class, you are allowed to create
objects. objects using new keyword.

The data members of static class can be directly The data members of non-static class is not directly
accessed by its class name. accessed by its class name.

Non-static class may contain both static and non-


Static class always contains static members.
static methods.

Static class does not contain an instance


Non-static class contains an instance constructor.
constructor.

Non-static class can be inherited from another


Static class cannot inherit from another class.
class.

2.8 Constructors

A constructor is a special method that is used to initialize objects. The advantage of a constructor, is that
it is called when an object of a class is created. It can be used to set initial values for fields:
Page 42 of 98
CS-20 : Programming with C# .Net
// Create a Car class
classCar
{
Public string model;// Create a field
// Create a class constructor for the Car class
Public Car()
{
model ="Mustang";// Set the initial value for model
}
Static void Main(string[] args)
{
Car Ford =newCar();// Create an object of the Car Class (this will call the
constructor)
Console.WriteLine(Ford.model);// Print the value of model
}
}
// Outputs "Mustang"

2.9 Overloading Constructor, Method and Operator


 It is quite similar to the Method Overloading. It is the ability to redefine a Constructor in more than
one form. A user can implement constructor overloading by defining two or more constructors in a
class sharing the same name. C# can distinguish the constructors with different signatures. i.e. the
constructor must have the same name but with different parameters list. We can overload constructors
in different ways as follows:
 By using different type of arguments
 By using different number of arguments
 By using different order of arguments

Example:
 public ADD (int a, float b);
 public ADD (string a, int b);
 Here the name of the class is ADD. In first constructor there are two parameters, first one
is int and another one is float and in second constructor, also there is two parameters, first one
is string type and another one is int type. Here the constructors have the same name but the types
of the parameters are different, similar to the concept of method overloading.
Example
// C# program to Demonstrate the overloading of
// constructor when the types of arguments
// are different
using System;
class ADD {
int x, y;
double f;
string s;
// 1st constructor
public ADD(int a, double b)
{
x = a;
Page 43 of 98
CS-20 : Programming with C# .Net
f = b;
}
// 2nd constructor
public ADD(int a, string b)
{
y = a;
s = b;
}
// showing 1st constructor's result
public void show()
{
Console.WriteLine("1st constructor (int + float): {0} ",(x + f));
}
// shows 2nd constructor's result
public void show1()
{
Console.WriteLine("2nd constructor (int + string): {0}", (s + y));
}
}
// Driver Class
class GFG {
// Main Method
static void Main()
{
// Creating instance and passing arguments. It will call the first constructor
ADD g = new ADD(10, 20.2);
// calling the method
g.show();
// Creating instance and passing arguments It will call the second constructor
ADD q = new ADD(10, "Roll No. is ");
// calling the method
q.show1();
}
}

2.10 Abstract Class


 The abstract keyword enables you to create classes and class members that are incomplete and
must be implemented in a derived class. In some case there might be requirement that child class
must and should implement particular method, in this case it should be declare as Abstract.
 When method is declared as abstract it is mandatory for child class to implement it, without which
it can't use other members and methods of the parent class. First it must implement the abstract
method in the parent class as there can be a method body not implemented for an abstract class in
a parent class. An abstract class cannot be instantiated. The purpose of an abstract class is to
provide a common definition of a base class that multiple derived classes can share. Abstract
classes may also define abstract methods.
 This is accomplished by adding the keyword abstract before the return type of the method.
Abstract methods have no implementation, so the method definition is followed by a semicolon
instead of a normal method block. Derived classes of the abstract class must implement all
Page 44 of 98
CS-20 : Programming with C# .Net
abstract methods. The abstract keyword in a class indicates that the class cannot be instantiated
and it is abstract class.
 An abstract class declares one or more methods or properties as abstract. Such methods do not
have an implementation provided in the class that declares them. An abstract class cannot be
instantiated directly, but only as a derived class. Such derived classes must provide
implementations for all abstract methods and properties, using the override keyword, unless the
derived member is itself declared abstract.
 When a method is declared as abstract in the base class then it is not possible to define it in the
derived class and every derived class of that class must provide its own definition for that method.
When a class contains at least one abstract method, then the class must be declared as abstract
class. It is mandatory to override abstract method in the derived class.
 A base class is not intended to be instantiated and is provided solely for the purpose of providing
an outline for subclasses. Such a class is known as an abstract class. Abstract classes cannot be
used to instantiate objects; because abstract classes are incomplete, it may contain only definition
of the properties or methods and derived classes that inherit this implements its properties or
methods.
Declaration:
public abstract class Talk
{
}
Deriving from an Abstract Class
public class SayHello : Talk
{
}
Some characteristics of abstract class are:
 An abstract method is implicitly a virtual method.
 Abstract method declarations are only permitted in abstract classes. Because an abstract method
declaration provides no actual implementation, there is no method body.
 The method declaration simply ends with a semicolon and there are no braces ({ })
 An abstract class is always public.
 User must declare at least one abstract method in an abstract class.
Example:
using System;
namespace OOPSProject
{
abstract class AbsParent
{
public void Add(int x, int y)
{
Console.WriteLine(x + y);
}
public void Sub(int x, int y)
{
Console.WriteLine(x - y);
}
public abstract void Mul(int x, int y);//only method declaration
public abstract void Div(int x, int y);//only method declaration

Page 45 of 98
CS-20 : Programming with C# .Net
}
}
class AbsChild : AbsParent
{
//first we have to implement abstract methods of parent class
public override void Mul(int x, int y)
{
Console.WriteLine(x * y);
}
public override void Div(int x, int y)
{
Console.WriteLine(x / y);
}
static void Main()
{
AbsChild c = new AbsChild();
AbsParent p = c;
p.Add(100, 50); p.Sub(156, 78);//then we can invoke other methods
p.Mul(50, 30); p.Div(625, 25);
Console.ReadLine();
}
}

2.11 Sealed Class


 When you want to restrict your classes from being inherited by others you can create the class as
sealed class. Once a class is defined as sealed class, this class cannot be inherited. It means
derived class cannot override this method. It is an error to use a sealed class as a base class. Use
the sealed modifier in a class declaration to prevent inheritance of the class. It is not permitted to
use the abstract modifier with a sealed class.
 Once user have declared a class as sealed, no other class can inherit that class. When user applies
the sealed keyword as a modifier to a class, the class becomes final.
Example:
using System;
sealed class MyClass
{
public int x;
public int y;
}
class MainClass
{
public static void Main()
{
MyClass mC = new MyClass();
mC.x = 110;
mC.y = 150;
Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
}
}
Page 46 of 98
CS-20 : Programming with C# .Net
Output:
x = 110, y = 150
Error:
class MyDerivedC: MyClass {} // Error

2.12 Overriding Methods


 Method Overriding in C# is similar to the virtual function in C++. Method Overriding is a technique
that allows the invoking of functions from another class (base class) in the derived class. Creating a
method in the derived class with the same signature as a method in the base class is called as method
overriding.
 In simple words, Overriding is a feature that allows a subclass or child class to provide a specific
implementation of a method that is already provided by one of its super-classes or parent classes.
When a method in a subclass has the same name, same parameters or signature and same return
type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the
method in the super-class. Method overriding is one of the ways by which C# achieve Run Time
Polymorphism(Dynamic Polymorphism).
 The method that is overridden by an override declaration is called the overridden base method. An
override method is a new implementation of a member that is inherited from a base class. The
overridden base method must be virtual, abstract, or override.

Example:
class base_class
{
public virtual void mjk();
}
class derived_class : base_class
{
public override void mjk();
}
class Main_Method
{
static void Main()
{
derived_class d = new derived_class();

Page 47 of 98
CS-20 : Programming with C# .Net
d.mjk();
base_class b = new derived_class();
b.mjk();
}
}
2.13 Creating an Interface
 Interface like classes define set of properties, methods and events. But unlike classes interface
don't provide any implementation. Interfaces we can invoke functions from different classes
through the same Interface reference.
 Interfaces in C# are provided as a replacement of multiple inheritance. Because C# does not
support multiple inheritance, it was necessary to incorporate some other method so that the class
can inherit the behaviour of more than one class.
 When a class inherits from one or more interfaces, we say that the class is implementing that
interface(s). The most important thing to remember about interfaces is that the classes can only
implement the methods defined in the interface because in C#, an interface is a built-in keyword
that declares a reference type that includes method declarations. An interface cannot be
instantiated directly.
Syntax:
interface interface_name
{
Member (methods) declaration code;
}
 Methods inside an interface do not have a body i.e. member declaration block contains only list of
members, without implementing code. They only signify that such a method should exist in the
implementing class or structure. Classes that display a common set of features, such as having
similar types of member variables or member functions, are designed in such a way that they
implement a common interface. Class can implement multiple interfaces. It is not possible to
inherit one interface to other interface.
Example:
interface disp
{
void display();
}
2.13.1 Implementing an Interface
 User can implement interface using a class that implements the features of the interface.
Interfaces are used as ‘super classes’ whose properties are inherited by classes. It is therefore
necessary to create a class that inherits the given interface.
 The implementation of interface is similar to implementing any other class. An interface may be
implemented using a colon in C#.
 When a class or struct implements an interface, the class or struct provides an implementation for
all of the members defined by the interface. A class can extend another class and implement as
many interfaces as the class needs. It is possible for a class to inherit an interface multiple times,
through base classes it inherits or through interfaces inherited by other interfaces.
 Classes and structs implement interfaces in a manner similar to how classes inherit a base class or
struct, with two exceptions:
 A class or struct can implement more than one interface.

Page 48 of 98
CS-20 : Programming with C# .Net
 When a class or struct implements an interface, it receives only the method names and
signatures, because the interface itself contains no implementations.
Example:
interface IMyInterface{
void MethodToImplement();
}
class InterfaceImplementer : IMyInterface{
static void Main(){
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
InterfaceImplementer iImp = new InterfaceImplementer();
iImp.MethodToImplement();
}
}
2.13.2 Inheriting an Interface
 When user creates an object of the derived class of the interface type, the inheritance hierarchy is
searched until the object finds that class. The class then directly implements the interface. An
interface can be implemented by a class or inherited by another interface. User can implement an
interface and use it in a class. Interfaces may also be inherited by another interface. Any class or
struct that inherits an interface must also implement all members in the entire interface inheritance
chain.
Example:
using System;
interface IParentInterface{
void ParentInterfaceMethod();
}
interface IMyInterface : IParentInterface{
void MethodToImplement();
}
class InterfaceImplementer : IMyInterface{
static void Main()
{
InterfaceImplementer iImp = new InterfaceImplementer();
iImp.MethodToImplement();
iImp.ParentInterfaceMethod();
}
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
public void ParentInterfaceMethod()
{
Console.WriteLine("ParentInterfaceMethod() called.");
}
}

Page 49 of 98
CS-20 : Programming with C# .Net
2.14 Creating and using Property
 If the members of a class are private then how another class in C# will be able to read, write, or
compute the value of that field.
 If the members of the class are public then another class may misuse that member.
Example:
// C# program to illustrate the problems
// with public and private members
using System;
// public class
public class C1
{
// public data members
public int rn;
public string name;
// private field
// private int marks = 35;
}
// another public class
public class C2
{
// Main Method
public static void Main(string[] args)
{
// Creating object of C1 class
C1 obj = new C1();

// setting values to public


// data members of class C1
obj.rn = 10000;
obj.name = null;

// setting values to private


// data members of class C1
// obj.mark = 0;

// display result
Console.WriteLine("Name: {0} \nRoll No: {1}", obj.name, obj.rn);

}
}
2.15 Creating and using an Indexer
 Indexers permit instances of a class or struct to be indexed in the same way as arrays. Indexers are
similar to properties except that their accessors take parameters.
 An Indexer looks like a property and is written in the same way a property is returned, but two
differences:
 An indexer takes an index argument and looks like an array.
 The indexer is declared using the name this.

Page 50 of 98
CS-20 : Programming with C# .Net
 Indexer gives effect array like to the class. On the inside of a class, you manage a
collection of values any way you want. These objects could be a finite set of class
members, another array, or some complex data structure.
 Indexers are referred as smart arrays. Indexer modifier can be private, public, protected
or internal. The return type can be any valid C# types. Indexers in C# must have at least
one parameter. Else the compiler will generate a compilation error.
Syntax:
public type this [Parameter]
{
get
{
// Get codes goes here
}
set
{
// Set codes goes here
}
}
Example:
using System;
using System.Collections.Generic;
using System.Text;
namespace Indexers
{
class ParentClass
{
private string[] range = new string[5];
public string this[int indexrange]
{
get
{
return range[indexrange];
}
set
{
range[indexrange] = value;
}
}
}
class childclass
{
public static void Main()
{
ParentClass obj = new ParentClass();

/* The Above Class ParentClass create one object name is obj */


obj[0] = "ONE";
obj[1] = "TWO";
Page 51 of 98
CS-20 : Programming with C# .Net
obj[2] = "THREE";
obj[3] = "FOUR ";
obj[4] = "FIVE";
Console.WriteLine("WELCOME TO C# CORNER HOME PAGE\n");
Console.WriteLine("{0}\n,{1}\n,{2}\n,{3}\n,{4}\n", obj[0], obj[1], obj[2], obj[3],
obj[4]);
Console.ReadLine();
}
}
}
 An indexer can be overloaded. The version executed will be one that has the closest type-match
between its parameter and the argument used as an index.
Difference between Indexer & Property
Indexer Property
Allows methods on an object to be called as Allows methods to be called as though they
though the object is an array. were public data members.
Accessed through an index. Accessed through a simple name.
Can be a static or an instance member. Must be an instance member.
Indexer is identified by its signature. Property is identified by its name.
Indexer should be associated with parameters Properties cannot have parameters associated
with it.
A get accessor of an indexer has the same A get accessor of a property has no parameters.
formal parameter list as the indexer.
A set accessor of an indexer has the same formal A set accessor of a property contains the
parameter list as the indexer, in addition to the implicit value parameter.
value parameter.
Indexer doesn’t require a name, and it is Property of a class should have a unique name.
accessed using “this”
2.16 Pointers
 C# is one of the languages in the .NET family, and as such is run under the Common Language
Runtime (CLR). It's the runtime that takes care of memory operations and lower-level
functionality on the program's behalf, so that the program doesn't normally have to worry about
pointers or memory buffers.
 The language does, however, provide a way for pieces of code to avoid the constraints of the
CLR. Any blocks marked as unsafe will not be managed by the runtime, and it's up to the
programmer to test and ensure that the code works as expected.
 C# allows pointers but only in unmanaged code. A pointer is nothing more than a variable that
holds the address in memory of another variable.
 In C#, pointers can only be used on value types and arrays. As a structure is a value type,
pointers can be used with them, but there is one problem with this, the structure must not contain
any reference types if you plan to use pointers.
unsafe keyword
 Typically, when we write code in C# by default it is what's known as safe code. Unsafe code
allows you to manipulate memory directly, in the normal world of C# and the .NET Framework,
this is seen as potentially dangerous, and as such you have to mark your code as unsafe. Using
unsafe code, you are losing garbage collection and directly accessing memory, you have the
possibility of accessing memory that you didn't want to and causing untold problems with your
application. Unsafe code can only be used within a fully trusted assembly.

Page 52 of 98
CS-20 : Programming with C# .Net
 There are three kinds of pointers supported by the CLR: managed pointers, unmanaged pointers
and unmanaged pointers.
 Managed pointers are references to managed blocks of memory which are stored on heap. An
Unmanaged pointers are traditional C++ pointers and each use must be placed in unsafe block of
code. An unmanaged function pointers are also the traditional C++ pointers that refer to the
addresses of the function (delegates are treated as unmanaged function pointers).
Operator
 & = The address-of operator returns a pointer to the address of a value.
 = The dereference operator returns the value at the address of a pointer.
 ->= The pointer-to-member operator is a syntactic shortcut, in whichx->yis equivalent to(*x).y.
Example Description
int* p p is a pointer to an integer
int** p p is a pointer to pointer to an integer
int*[] p p is a single-dimensional array of pointers to integers
 Unsafe code is not verified by the common language runtime.
 We can use unsafe keyword before main(), member of class and even we can write unsafe block.
It is compulsory to write unsafe keyword when we use pointer. Like this:
public class classname
{
static void Main()
{
unsafe
{
Code here
}
}
}

public class classname


{
unsafe static void Main()
{
Code here
}
}
Example:
The ampersand '&' is the referencer and means the 'location of'.
static void Main(string[] args)
{
unsafe
{
int age = 32;
int* age_ptr;
age_ptr = &age
Console.WriteLine(age = {0}, age);
Console.WriteLine(age_ptr = {0}, *age_ptr);
}
}

Page 53 of 98
CS-20 : Programming with C# .Net
Output:
age = 32
age_ptr = 32
2.16.1 Pointers To Arrays
 In C# array elements can be accessed by using pointer notations.
 Fixed: It sets a pointer to a managed code variable during the execution of statement. We can
instruct the garbage collector not to move certain objects using fixed keyword.
Example:
using System;
namespace arrayDemo
{
class Program
{
unsafe static void Main(string[] args)
{
int[] arr={10,20,30,40};
//ptr is pointer to array of integer
fixed (int* ptr = arr)
{
int* p = ptr;
for (int i =0; i<arr.Length ;i++)
{
Console.Write("{0} ",*p);
p++;
}
}
Console.ReadKey();
}
}
}
Output:
10 20 30 40
2.16.2 Pointers to Structures
 The structures in C# are value types. The pointers can be used with structures if it contains only
value types as its members.
 Structure itself a value type.
 With the help of -> operator we can access the members of the structure.
Example:
using System;
struct mystruct{
public int x;
public int y;
public void setXY(int i, int j) {
x=i;
y=j;
}
public void showXY(){
Console.WriteLine(x);
Page 54 of 98
CS-20 : Programming with C# .Net
Console.WriteLine(y);
}
}
class myclient{
public unsafe static void Main() {
mystruct ms = new mystruct();
mystruct *ms1 = &ms;
ms1->setXY(10,20);
ms1->showXY();
}
}
2.17 Delegate
 A delegate in C# is similar to a function pointer in C or C++. A delegate is a type that references a
method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate
method can be used like any other method, with parameters and a return value.
 Delegate is an object that can refer to a method.
 When we are creating delegates, we are creating an object that can hold a reference to a method; it
necessarily means that a delegate can invoke the method to which it refers.
 As the delegate refers to a method, the same delegates can be used to call multiple methods just
by changing the method name at the run time; provided the method (instance or static) match the
signature and return type.
 Any method that matches the delegate's signature, which consists of the return type and
parameters, can be assigned to the delegate. This makes is possible to programmatically change
method calls, and also plug new code into existing classes. As long as you know the delegate's
signature, you can assign your own delegated method.
 A delegate type maintains three important pieces of information:
1. The name of the method on which it make calls.
2. Any argument (if any) of this method.
3. The return value (if any) of this method.
 A delegate will allow us to specify what the function we'll be calling looks like without having to
specify which function to call.

2.17.1 Declaring & Instantiating Delegate


 Delegates are of class type and behave like classes then also C# provides a special syntax for
instantiating their instances.
Syntax:
delegate result-type identifier ([parameters]);
 result-type: The result type, which matches the return type of the function.
 identifier: The delegate name.
 parameters: The Parameters, which the function takes.
 If it is a method name then its signature and return type must be same as those of delegates. If
no matching exists or more than one matching found exists an error occurs.
 The method and the object to which delegate refers are determined when the delegate is
instantiated and then remain constant for the entire lifetime of the delegate. It is therefore not
possible to change them, once the delegate is created.
 It is not possible to create a delegate that would refer to a constructor, indexer or user-defined
operator.

Page 55 of 98
CS-20 : Programming with C# .Net
 When a delegate is invoked, it in turn invokes the method whose reference has been encapsulated
into the delegate.
Example:
// Declaration
public delegate void SimpleDelegate();
class TestDelegate {
public static void MyFunc() {
Console.WriteLine("I was called by delegate ...");
}
public static void Main() {
// Instantiation
SimpleDelegate simpleDelegate = new SimpleDelegate(MyFunc);
// Invocation
simpleDelegate();
} }
Output:
I was called by delegate...
 Once a delegate type has been declared, a delegate object must be created and associated with a
particular method. Like all other objects, a new delegate object is created with a new expression.
When creating a delegate, however, the argument passed to the new expression is special — it is
written like a method call, but without the arguments to the method.
2.17.2 Multicast Delegate
 A delegate can invoke only one method; however, it is possible to hold and invoke multiple
method. Such delegates are called multicast delegates.
 For multicast delegate instance that was created by combining two delegates. The invocation list
is formed by concatenating the invocation list of the two operands of the addition operation.
Delegates are invoked in the order they are added.
Example:
public delegate void fnTwoInteger(int x,int y);
public class DelegateExample
{
public static void Main()
{
ExmapleClass obj = new ExmapleClass();
fnTwoInteger pointer=null;
//observation: adding more than one function called multicast delegate.
pointer += new fnTwoInteger(obj.Add);
pointer += new fnTwoInteger(obj.Multiply);
pointer(52, 72);
Console.ReadLine();
}
}
public class ExmapleClass
{
public void Add(int x, int y)
{
Console.WriteLine("The sum is: " + (x + y));
}
Page 56 of 98
CS-20 : Programming with C# .Net
public void Multiply(int x, int y)
{
Console.WriteLine("The product is: " + (x * y));
}
}
2.18 Events
 An event in C# is a way for a class to provide notifications to clients of that class when some
interesting thing happens to an object. Events are the message sent by an object to indicate the
occurrence of an event. Event can also be defined as a member that enables an object to provide
notification. Events provide a powerful means of inter-process communication. Events are used
for communication between Objects. Communication between Objects is done by events.
 An event in is a way for a class to provide notifications to clients of that class when some
interesting thing happens to an object. The most familiar use for events is in graphical user
interfaces; typically, the classes that represent controls in the interface have events that are
notified when the user does something to the control (for example, click a button). An event is the
outcome of an action.
Event Receiver
The event receiver may be
1 An application
2 An Object
3 A component
Event receiver gets modified when something happens.
Event Sender
The Event sender may be
1. An assembly in an application
2. An object
3. System events like Mouse event or keyboard entry.
 Event sender's job is to raise the Event. Event sender doesn't know anything about, whom and
what the receiver is. To handle the event, there would be some method inside event receiver.
This Event handler method will get executed each time when event is registered to be raised.
 In C#, an event is a delegate type class member that is used by the object or class to provide a
notification to other objects that an event had occurred. The object can act on an event by adding
an event handler to the event.
Syntax:
modifier event type event_name;
 The modifier may be a valid combination of the four access modifiers, and a valid combination of
static, virtual, override, abstract and sealed.
 The type of an event declaration must be a delegate type and the delegate must be accessible as
the event itself.
 The event_name is any valid C# variable name. Event is a keyword that signifies that the
event_name is an event.
Chaining Events
 An EVENT in C# is simply a means to create a CHAIN of functions that will execute when
something “happens” to an object.
Example:
public class Button {
// Define the EVENT here.

Page 57 of 98
CS-20 : Programming with C# .Net
public event Action Pushed;
public void PushButton()
{
Console.WriteLine("Oh, you pushed me.");
// !! VERY IMPORTANT LINE!!
Pushed(); // "FIRE" EVENT: CAUSES ALL FUNCTIONS THAT WERE ATTACHED
Console.WriteLine("Great, now my paint is all dented");
}
}
public class Program
{
public static void ButtonPusher()
{
Console.WriteLine("HI THERE!!");
}
// another function that will be attached
// to the button's Pushed event
public static void func2()
{
Console.WriteLine("HELLO!!");
}
public static void sayHi(int howMany)
{
Console.WriteLine(howMany + " hi's to yoU!");
}
static void Main(string[] args)
{
Button b = new Button();
b.Pushed += new Action(ButtonPusher);
b.Pushed += new Action(func2);
b.Pushed += new Action(ButtonPusher);
b.PushButton();
Console.ReadLine();
}
}
2.19 Understanding Collections
 The .NET framework provides specialized classes for data storage and retrieval. A collection is a
one-dimensional storage area.
 Collections are specialized classes for data storage and retrieval. These classes provide support for
stacks, queues, lists and hash table. The main usage of collections is that they standardize the way
groups of objects are handled by your programs.
 Collection contain in which values of mixed data types can be placed. Collections are increased in
size simply by adding items to it.
 The .NET Framework supports four general types of collections: non-generic, specialized, bit-
based and generic. System.Collection namespace is known as non-generic collection and
System.Collection.Generic is known as generic collection. Generics enhance code reuse, type
safety, and performance.

Page 58 of 98
CS-20 : Programming with C# .Net
 Most collection classes implement the same interfaces, and these interfaces may be inherited to
create new collection classes that fit more specialized data storage needs.
 Collection Classes have the following properties,
 Collection classes are defined as part of the System.Collections or System.Collections.Generic
namespace.
 Most collection classes derive from the interfaces ICollection, IComparer, IEnumerable, IList,
IDictionary, and IDictionaryEnumerator and their generic equivalents.
 Using generic collection classes provides increased type-safety and in some cases can provide
better performance, especially when storing value types.
Collection Interfaces and Classes:
Following are interfaces available in non-generic collection:
Interface Description
ICollection Provides size, enumerators, and synchronization methods for all
non-generic collections.
IComparer Defines a method that compares two objects.
IDictionary Provides a non generic collection of key/value pairs.
IDictionaryEnumerator Enumerates the elements of a non generic dictionary.
IEnumerable Provides the enumerator, which supports a simple iteration over a
non-generic collection.
IEnumerator Supports a simple iteration over a non generic collection.
IEqualityComparer Methods to support the comparison of objects for equality.
IHashCodeProvider Supplies a hash code for an object, using a custom hash function.
IList Represents a non-generic collection of objects that can be
individually accessed by index.
Following is list of classes in non-generic collection:
ArrayList A dynamic array. Implements the IList interface using an array that
can grow as needed.
BitArray Manages a compact array of bit values.
Hashtable A hash table for key/value pairs.
Queue A first-in, first-out list.
SortedList A sorted list of key/value pairs.
Stack A first-in, last-out list.
2.19.1 Array List
 Standard arrays are of a fixed length, which cannot be changed during program execution. So you
have to define array size at compile time. But sometimes you cannot predict array size at compile
time. To overcome this problem, we have ArrayList class, which supports dynamic arrays and it can
grow or shrink as needed. An ArrayList is created with an initial size. When this size is exceeded,
the collection is automatically enlarged.
 ArrayList is a collection from a standard System.Collections namespace. It is a dynamic array. It
provides random access to its elements. An ArrayList automatically expands as data is added. Unlike
arrays, an ArrayList can hold data of multiple data types. Elements in the ArrayList are accessed via
an integer index. Indexes are zero based.
 ArrayList implements the IList interface using an array and very easily we can add, insert, delete,
view etc. It is very flexible because we can add without any size information, that is it will grow
dynamically and also shrink. The ArrayList class implements a collection of objects using an array
whose size is dynamically increased as required. The ArrayList class is very useful if you are
working with arrays and need to add, remove, index, or search for data in a collection.
Page 59 of 98
CS-20 : Programming with C# .Net
 ArrayList as nothing more than a linked-list implementation of an Array.
 ArrayList implements ICollection, IList, Enumerable, and ICloneable.
Methods of ArrayList:
Methods Description
Add(Object value) Adds an object to the end of the ArrayList.
Clear() Removes all the elements from the ArrayList.
Insert(int index, Object value) Inserts an element into the ArrayList at the specified index.
Remove(Object value) Removes the first occurrence of a specified object from the
ArrayList.
RemoveAt(int index) Removes the element at the specified index of the ArrayList.
Sort() Sorts the elements in the entire ArrayList.
 Properties of ArrayList: There are many properties available with ArrayList but most
commonly Count is used. Count is use to get the number of elements actually contained in the
ArrayList.

2.19.2 HashTable
 Hashtable creates a collection that uses a hash table for storage. Hash table is storing data in key-
value pair, where key field will remain unique. An array and ArrayList allows you to access their
elements by an index. Bt Hashtable allows you to access the items by a key. Each item has key
and a value.
Most commonly used Methods of HashTable:
Name Description
Adds an element with the specified key and value into the
Add
Hashtable.
Clear Removes all elements from the Hashtable.
Contains Determines whether the Hashtable contains a specific key.
ContainsKey Determines whether the Hashtable contains a specific key.
ContainsValue Determines whether the Hashtable contains a specific value.
GetHash Returns the hash code for the specified key.
Removes the element with the specified key from the
Remove
Hashtable.
 HashTable have Count property which is used to count elements in collection, Keys which is
read only property and used to retrieve collection of keys and Values which is read only property
and used to retrieve collection of values from HashTable.
Constructing a Hashtable:
There are many constructors available to instantiate a hashtable. The simplest is:
Hashtable ht = new Hashtable();
A constructor can also be constructed by passing in the initial capacity:
Hashtable ht = new Hashtable(10);
Adding items to a Hashtable:
Once you have instantiated a hashtable object, then you can add items to it using its Add()
method.
ht.Add(“st1”,”ABCD”) ;
ht.Add(“st2”,”WXYZ”);
Retrieving items from the Hashtable:
Here we have inserted two items into the hashtable along with their keys. Any particular item
can be retrieved using its key.

Page 60 of 98
CS-20 : Programming with C# .Net
Console.WriteLine(“Size of hashtable :”, ht.Count);l
Console.WriteLine(“Element = {0}”,ht[st1]);
Removing Items from a Hashtable:
The Remove method removes an item from a Hashtable.
ht.Remove("st1");
Example:
namespace hasttableex1{
class Program {
static void Main(string[] args) {
Hashtable ht = new Hashtable();
ht.Add("BCA", "Bachelor in Computer Applications");
ht.Add("BSC.IT", "Bachelor of Science with Information Technology");
ht.Add("MCA","Master in Computer Applications");
ht.Add("MSC.IT","Master of Science with Information Technology");
ht["BE"] = "Bachelor iof Engineering";
ICollection c = ht.Keys;
Console.WriteLine("===========Hashtable=============");
foreach (string str in c)
{
Console.WriteLine(str + ":" + ht[str]);
}
Console.Read();
}
}
}
2.19.3 Stack
 Stacks are one of the common data structures used in the software world, which follows the First
In Last Out paradigm. In collection class there is a Stack class which supports the stack. Stacks
are used in various mathematical functions like Towers of Hanoi, finding Fibonacci Sequence,
Factorial of a number to name a few. It represents a simple last-in-first-out (LIFO) non-generic
collection of objects.
Most commonly used Methods of Stack:
Name Description
Clear Removes all objects from the Stack.
Contains Determines whether an element is in the Stack.
Peek Returns the object at the top of the Stack without removing it.
Pop Removes and returns the object at the top of the Stack.
Push Inserts an object at the top of the Stack.
ToArray Copies the Stack to a new array.
Example:
using System;
using System.Collections;
public class SamplesStack
{
public static void Main()
{
// Creates and initializes a new Stack.
Stack myStack = new Stack();
Page 61 of 98
CS-20 : Programming with C# .Net
myStack.Push("Hello");
myStack.Push("World");
myStack.Push("!");
// Displays the properties and values of the Stack.
Console.WriteLine( "myStack" );
Console.WriteLine( "\tCount: {0}", myStack.Count );
Console.Write( "\tValues:" );
PrintValues( myStack );
}
public static void PrintValues( IEnumerable myCollection ) {
foreach ( Object obj in myCollection )
Console.Write( " {0}", obj );
Console.WriteLine();
}
}
2.19.4 Queue
 A queue is a list in which the first item added to the list will be the first one to be removed. This is
referred to as first-in first-out (FIFO). The Queue works like FIFO system, a first-in, first-out
collection of Objects. Objects stored in a Queue are inserted at one end and removed from the
other.
 The Queue provide additional insertion, extraction, and inspection operations. We can Enqueue
(add) items in Queue and we can Dequeue (remove from Queue) or we can Peek (that is we will
get the reference of first item) item from Queue. Queue accepts null reference as a valid value and
allows duplicate elements.
 Also a Queue is a collection where elements are processed first in, first out (FIFO). The item is
put first in the queue is read first. The item in the end is read last.
Some important functions in the Queue Class are follows:
Enqueue : Add an Item in Queue
Dequeue : Remove the oldest item from Queue
Peek : Get the reference of the oldest item
Clear : Clears the queue
Enqueue : Add an Item in Queue
Syntax : Queue.Enqueue(Object)
Object : The item to add in Queue
days.Enqueue("Sunday");
Dequeue : Remove the oldest item from Queue (we don't get the item later)
Syntax : Object Queue.Dequeue()
Returns : Remove the oldest item and return.
days.Dequeue();
Peek : Get the reference of the oldest item (it is not removed permanently)
Syntax : Object Queue.Peek()
returns : Get the reference of the oldest item in the Queue
days.peek();
Clear : Clears the queue
Syntax: Queue.Clear()
Returns : Sets count to zero, which effectively clears the queue.

Page 62 of 98
CS-20 : Programming with C# .Net
Example:
namespace queueex1{
class Class1 {
public static void Main()
{
int i;
Queue p = new Queue();
for (i = 0; i < 5; i++)
{
p.Enqueue(i * 10);
}
Console.WriteLine("Total elements : " + p.Count);
Console.WriteLine("Elements is queue are :");
for (i = 0; i < 5; i++)
{
Console.WriteLine("Element {0}: {1} ", i, p.Dequeue());
}
Console.WriteLine("Total elements : " + p.Count);
Console.ReadLine();
}
}
}

Page 63 of 98
CS-20 : Programming with C# .Net
3.1 Introduction to Windows Forms & Windows Application
 An important part of Visual Studio .NET is the ability to create Windows applications that run
locally on users' machines. Visual Studio .NET allows you to create the application and user
interface using Windows Forms. A Visual Studio Windows application is built around the .NET
Framework, a rich set of classes that allows you to program sophisticated applications. You can
create Windows applications using any .NET programming language (Visual Basic, C#, Managed
Extensions for C++, and many others).
 Windows Forms is a technique of creating computer applications based on the common language
runtime (CLR). It offers a series of objects called Windows Controls or simply, controls. These
controls are already created in the .NET Framework through various classes. Application
programming consists of taking advantage of these controls and customizing them for a particular
application. To exploit these controls and other features of the .NET Framework, there are various
types of applications you can create, including graphical applications (windows), web-based
applications (ASP.NET web applications), or console applications, etc.
 The advantage of using Visual Studio .NET is that it provides tools that make application
development much faster, easier, and more reliable.
 These tools include:
 Visual designers for Windows Forms with drag-and-drop controls.
 Code-aware editors that include statement completion, syntax checking, and other IntelliSense
features.
 Integrated compilation and debugging.
 A form is the most fundamental object used on an application. It is a rectangular object that uses
part of the computer desktop to represent an application. A form is based on the Form class that is
defined in the System.Windows.Forms namespace.
 Three terms are belonged to Windows.Forms namespace are component, container and control.
 A component is an object that permits sharing between applications. A container is an object
that can hold zero or more components. A container is simply a grouping mechanism and ensures
that set of components are encapsulated and manipulated in similar way. A control is a
component with a visual aspect. In the Windows Forms namespace, a control is a component that
presents a graphical interface on the Windows desktop.
 The .NET Framework provides all of the classes that make up Windows Forms based
applications through System.Windows.Forms namespace. Windows Forms provide your project
with components, such as dialog boxes, menus, buttons, and many other controls, that make up a
standard Windows application user interface (UI).
Key Facts about Windows Forms:
o A form is rectangular
o It is primary platform for user interaction.
o Form is container.
o Form has properties, events and methods.
3.2 Message Box
 A MessageBox is a predefined dialog box that displays application-related information to the user.
It produces pop-up message box, prompt which contains text, buttons and symbols that inform and
instruct the user. Message boxes are also used to request information from the user. Displays a
message box that can contain text, buttons, and symbols that inform and instruct the user.
 It returns an integer indicating which button the user clicked. MessageBox is a class and Show is
static method of it. MessageBox returns object of Dialog Result.

Page 64 of 98
CS-20 : Programming with C# .Net
3.4 Different Windows Controls
3.4.1 Button Control
 The Button control is one control you can add to any Windows Forms program. It renders as a
rectangular box with text or images in the centre that you can resize and add event handlers to.
 In Windows Forms the button control allows the user to click it ti perform an action. We use a
Button control that accepts click events and performs other actions in the user interface. This
control provides a way to accept input—and invoke logic based on that input.
 The Button Base class represents a control that can be displayed as a button. It is an abstract class
in the System.Windows.Forms namespace, and inherits from the Control class.
Public properties of ButtonBase:
FlatStyle Gets or sets the flat style appearance.
Image Gets or sets an image to display on the button.
ImageAlign Gets or sets the alignment of an image on the button.
ImageIndex Gets or sets an image to display on the button as an index into the
ImageList property.
ImageList Gets or sets an ImageList object to associate with the button control.
TextAlign Gets or sets the alignment of text on the screen.

3.4.2 Label Control


 A Label control is used as a display medium for text on Forms. This control serves as an invisible
frame where you can place text. Usually a label is used together with a related to other controls or
to provide messages. Usually a label is used together with a textbox. Label control does not
participate in user input or capture mouse or keyboard events.
 This control is always read only that means user cannot change it at runtime. However user can
change the Text property in the code.
Public properties of Label:
AutoSize Gets or sets whether the label should automatically resize to display its
content.
BorderStyle Gets or sets the border for the label. The default is None.
Flat Style Gets or sets the flat style for the label. The default is Standard.
Image Gets or sets the image to appear on the label
TextAlign Gets or sets the text alignment to use for the text in the control.

3.4.3 TextBox Control


 The TextBox control is one of the most used controls form from the basic tools. A TextBox
control accepts user input on a Form. Windows Forms text boxes are used to get input from the
user or to display text. The TextBox control is generally used for editable text, although it can be
made read-only. TextBoxes can display multiple lines also add basic formatting.
Public properties of Label:
PasswordChar Gets or sets the character used to mask the text displays in the
control.
ScrollBars Gets or sets the scrollbars when there is multiline text box.
TextAlign Gets or sets how displayed text is aligned within the control.
Public Events of TextBox Class:
1. GotFocus
2. LostFocus
3. KeyPress

Page 65 of 98
CS-20 : Programming with C# .Net
4. KeyDown
5. KeyUp
Example:
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace textboxex1{
public partial class Form1 : Form {
public Form1()
{
InitializeComponent();
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("You pressed enter! Good job!");
}
else if (e.KeyCode == Keys.Escape)
{
MessageBox.Show("You pressed escape! What's wrong?");
}
}
private void Form1_Load(object sender, EventArgs e)
{
textBox2.Text = "Apple";
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (textBox2.Text.Length == 1)
{
if (textBox2.Text == "B" || textBox2.Text == "b")
{
textBox2.Text = "Ball";
}
}
}
}
}
3.4.4 RadioButton Control
 Radio buttons are generally used as a group. It is known as option buttons and allows user to
choose one of several options. A RadioButton control provides a round interface to select one
option from a number of options. The RadioButton control can display text, an image or both.
When user selects one option button within a group, the others clear automatically. All
RadioButton in a given container such as Form, constitute a group. To create multiple groups on
one form, place each group in its own container, such as a GroupBox or Panel control.
Public properties of RadioButton:

Page 66 of 98
CS-20 : Programming with C# .Net
Appearance Gets or sets whether the control appears as a normal radio
button or a toggle button.
AutoCheck Gets or sets the behavior of related radio buttons when this
button is clicked. If true, then it automatically deselects all
radio buttons in the same group, if false other radio buttons in
the group must be deselected manually.
CheckAlign Gets or sets the alignment of the click box portion of the
control.
Public Events of RadioButton:
1. AppearanceChanged
2. CheckedChanged

3.4.5 CheckBox Control


 A CheckBox control indicates whether a particular condition is on or off. You can also use check
box controls in groups to display multiple choices from which the user can select one or more.
 The Check Box control is similar to the radio button control in that each is used to indicate a
selection that is made by user. They differ in that only one radio button in a group can be selected
at a time but you can make multiple selections using CheckBox.
Public properties of CheckBox:

This property is used to gets or sets the value that indicates the appearance of a
Appearance
CheckBox control.

This property is used to set a value which shows whether the Checked or
AutoCheck CheckState values and the CheckBox appearance are automatically changed
when you click the CheckBox.

CheckState This property is used to get or set the state of the CheckBox.

This property is used to get or set the horizontal and vertical alignment of the
CheckAlign
check mark on a CheckBox control.

This property is used to get or set a value which determine whether the
Checked CheckBox is in the checked state.

Text This property is used to get or set the text associated with this control.

3.4.6 ListBox, CheckedListBox, ComboBox


 ListBox, CheckedListBox, ComboBox are all derived from the ListControl class. If there is need
to have multiple selections or if the user needs to be able to see several items in the list at any
time, the ListBox or CheckedListBox is going to be the best choice. If only single item is ever
selected in the list at any time a ComboBox is good choice.
 ListBox: The listbox control displays items from the list from which user can select one or more
items. If total number of items exceeds the number that can be displayed, a scrollbar is

Page 67 of 98
CS-20 : Programming with C# .Net
automatically added to the listbox. All items in the listbox control are visible by default. To make
items visible ser the IsDropDown property true. To select more than one item at a time from the
listbox control set the property to single, multiple or extended.
Public properties of ListBox:
DrawMode Gets or sets how this listbox should be drawn.
Item Gets the collection of items to display.
MultiColumn Gets or sets whether this list box should support multiple
columns. Default is false.
SelectedItem Gets or sets the currently selected items.
SelectedItems Gets a collection of all items selected in the list.
SelectionMode Gets or sets how items are selected in the list box.
CheckedListBox: CheckedListBox is almost everything same that a listbox does and can display
a check mark next to items in the list. CheckedListBox can only have one item or none selected.

ComboBox: The ComboBox control is used to display data in a drop-down combo box. By
default, the ComboBox control appears in two parts: the top part is a text box that allows user to
type a list item. The second part is a list box that displays a list of items from which user can
select one.
Public properties of ComboBox:
SelectedItem Gets or sets the currently selected items.
Items Gets or sets the collection of items contained in the combobox.
MaxLength Gets or sets the maximum number of characters permitted in the
textbox portion of the control.
SelectedText Gets or sets any text that is selected in the text box portion of the
control.

3.4.7 PictureBox
 PictureBox control is used to display images in Windows Forms. PictureBox provides a
rectangular region for an image. It supports many image formats. It has an adjustable size.
PictureBox provides the Image property to retrieve or assign the image to display, and the
SizeMode property to retrieve or assign how the image should be displayed.
Public properties of PictureBox:
BorderStyle Gets or sets the style of border to display for the control.
Image Gets or sets the image to display in the picture box.
SizeMode Gets or sets the PictureBoxSizeMode value indicating how the
image is displayed. The default is Normal

3.4.8 ScrollBar
 ScrollBar controls are used to provide easy navigation through a long list of items or a large amount
of information by scrolling either horizontally or vertically within an application or control. The
.NET Framework includes two scroll bar implementations. The HScrollBar class is used to create
horizontal scroll bars, and the VScrollBar class is used to create vertical scroll bars. These classes
are both derived from a common base class, ScrollBar.

Example:
using System;
using System.ComponentModel;
Page 68 of 98
CS-20 : Programming with C# .Net
using System.Windows.Forms;
namespace scrollbarex1{
public partial class Form1 : Form {
public Form1()
{
InitializeComponent();
}
private void hScrollRed_Scroll(object sender, ScrollEventArgs e)
{
changecolor();
}
private void hScrollGreen_Scroll(object sender, ScrollEventArgs e)
{
changecolor();
}
private void hScrollBlue_Scroll(object sender, ScrollEventArgs e)
{
changecolor();
}
void changecolor()
{
this.BackColor=Color.FromArgb(hScrollRed.Value, hScrollGreen.Value,
hScrollBlue.Value);
}
}
}

3.4.9 TreeView
 TreeView Control is used for showing hierarchical structured data visually, like the way files and
folders displayed in the left pane of the Windows Explorer. Each node in the tree view might
contain other nodes, called child nodes. User can display parent nodes, or nodes that contain
child nodes, as expanded or collapsed. You can also display a tree view with check boxes next to
the nodes by setting the tree view’s CheckBoxes property to true.
Public properties of TreeView:
CheckBoxes Gets or sets whether check boxes are displayed next to each
node on the tree. The default is tree.
HideSelection Gets or sets whether a selected node remains highlighted even
when the control does not have focus.
ImageList Gets or sets an ImageList to associate with this control.
Nodes Gets the collection of TreeNode objects assigned to the
control.
SelectedNode Gets or sets the selected tree node.
Sorted Gets or sets whether the tree nodes are sorted alphabetically
based on their label text.
TopNode Gets the tree node currently displayed at the top of the tree
view control.

Page 69 of 98
CS-20 : Programming with C# .Net
Class Hierarchy of TreeView Control
 TreeView
 TreeNodeCollection
 TreeNode
 TreeView is contains collection of TreeNodes. Each TreeNode is a member of
TreeNodeCollection.
 TreeNode is a type of recursive Data Structure as itself contains Collection of TreeNodes.
Example:
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace treeviewex1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
TreeNode treeNode = new TreeNode("Windows");
treeView1.Nodes.Add(treeNode);
// Another node following the first node.
treeNode = new TreeNode("Linux");
treeView1.Nodes.Add(treeNode);
// Create two child nodes and put them in an array.
// ... Add the third node, and specify these as its children.
TreeNode node2 = new TreeNode("C#");
TreeNode node3 = new TreeNode("VB.NET");
TreeNode[] array = new TreeNode[] { node2, node3 };
// Final node.
treeNode = new TreeNode("Dot Net Perls", array);
treeView1.Nodes.Add(treeNode);
}
}
}

ImageList
 ImageList provides a container for image data. We can use ImageList component in our
applications when we are building our own controls such as a photo gallery or an image rotator
control. An ImageList is used to provide a collection of Image objects. . An image list is a
collection of icons or pictures that are stored so that each icon or picture can be located by an
index. The icons or pictures must be of the same size and they should be the same type.
Public properties of ImageList:
ColorDepth Gets or sets the color depth for images in the list.
Images Gets the collection of images for this imagelist.

Page 70 of 98
CS-20 : Programming with C# .Net
ImageList Gets or sets the size for images in the list.
TransparentColor Gets or sets the color to treat as transparent in the list’s images.
3.4.10 Menu

3.4.10.1 Menu Strip


 The MenuStrip class is the foundation of menus functionality in Windows Forms. If you have
worked with menus in .NET 1.0 and 2.0, you must be familiar with the MainMenu control. In
.NET 3.5 and 4.0, the MainMenu control is replaced with the MenuStrip control.
Creating a MenuStrip
 We can create a MenuStrip control using a Forms designer at design-time or using the MenuStrip
class in code at run-time or dynamically.
 To create a MenuStrip control at design-time, you simply drag and drop a MenuStrip control from
Toolbox to a Form in Visual Studio. After you drag and drop a MenuStrip on a Form, the
MenuStrip1 is added to the Form and looks like Figure 1. Once a MenuStrip is on the Form, you
can add menu items and set its properties and events.

 Creating a MenuStrip control at run-time is merely a work of creating an instance of MenuStrip


class, setting its properties and adding MenuStrip class to the Form controls.
 The first step to create a dynamic MenuStrip is to create an instance of MenuStrip class. The
following code snippet creates a MenuStrip control object.
Example:
MenuStrip MainMenu = new MenuStrip();
MainMenu.BackColor = Color.OrangeRed;
MainMenu.ForeColor = Color.Black;
MainMenu.Text = "File Menu";
MainMenu.Font = newFont("Georgia", 16);
this.MainMenuStrip = MainMenu;
Controls.Add(MainMenu);

3.4.10.2 Context Menu Strip


 To create a ContextMenuStrip control at design-time, you simply drag and drop a
ContextMenuStrip control from Toolbox onto a Form in Visual Studio. After you drag and drop a
ContextMenuStrip on a Form, the ContextMenuStrip1 is added to the Form and looks like Figure

Page 71 of 98
CS-20 : Programming with C# .Net
1. Once a ContextMenuStrip is on the Form, you can add menu items and set its properties and
events. If you noticed in Figure 1, first item of the ContextMenuStrip has text Type Here. You
can actually start typing here.

 If you notice in Figure 2, I type couple of menu items. As soon as you select a menu item, you
will see automatically sub menu items areas are editable and you can keep going as many levels
you like. I add two menu items and two sub menu items.

 We can also create context menus at run-time. Even though you can create a ContextMenuStrip at
run-time, it is recommended you create at design-time and then set the properties and methods at
run-time.
 First step to create a dynamic ContextMenuStrip is to create an instance of ContextMenuStrip
class. The following code snippet creates a ContextMenuStrip control object.
Example:
ContextMenuStrip PopupMenu = new ContextMenuStrip();
PopupMenu.BackColor = Color.OrangeRed;
PopupMenu.ForeColor = Color.Black;
PopupMenu.Text = "File Menu";
PopupMenu.Font = new Font("Georgia", 16);
this.ContextMenuStrip = PopupMenu;
PopupMenu.Show();

3.4.11 Tooltip
 Tooltip provide short and explanations of the purpose of a control or other object. A Tooltip class is
a component that provides a small pop-up window for a control. This window normally contains a

Page 72 of 98
CS-20 : Programming with C# .Net
short describing the purpose of the control, and appears whenever the mouse hovers over the
control for some amount of time.
Public properties of Tooltip:
Active Gets or sets whether the Tooltip is currently active. When false
no tooltip will appear. The default is false.
AutomaticDelay Gets or sets the default delay time in milliseconds.
InitialDelay Gets or sets the time in milliseconds before a tooltip will appear
when the mouse is stationary.
ShowAlways Gets or sets whether to display the tooltip for an inactive
control. The default is false.
Example:
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace tooltipex1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
toolTip1.SetToolTip(textBox1, "Enter No");
toolTip1.SetToolTip(textBox2, "Enter Char");
toolTip1.SetToolTip(textBox3, "Enter Upper");
}
}
}
3.4.12 Timer
 A timer is an object used to count lapses of time and send a message when it has finished counting.
Each count is called a tick. When a tick occurs, the control fires a Tick event. This Tick event is of
type EventArgs, meaning that it doesn't provide more information than to let you know that a lapse
has occurred. The Timer control allows you to set a time interval to execute an event after that
interval continuously. It is useful when you want to execute certain applications after a certain
interval.
Public properties of Timer:
Interval Indicates the interval on which to raise the Tick event.
Enabled Indicates whether the Timer raises the Tick event.
3.4.13 Panel
 The Panel control is a container control that is used to host a group of similar child controls.
Windows Forms Panel controls are used to provide an identifiable grouping for other controls.
This control provides a simple frame for putting sub controls inside. These sub controls include
buttons and text boxes. It further provides an optional border and ways to change its visibility.

Page 73 of 98
CS-20 : Programming with C# .Net
Useful properties:
BackImageUrl URL of the background image of the panel.

Gets or sets the identifier for the default button that is


DefaultButton
contained in the Panel control.

Direction Text direction in the panel.

GroupingText Allows grouping of text as a field.

HorizontalAlign Horizontal alignment of the content in the panel.

Specifies visibility and location of scrollbars within the


ScrollBars
panel.

Wrap Allows text wrapping.


3.4.14 GroupBox
 A GroupBox control is a container control that is used to place Windows Forms child controls in
a group. The purpose of a GroupBox is to define user interfaces where we can categories related
controls in a group. They allow you to place controls on it and all the control inherit the properties
from the container in which they sit. This is useful when you to form a group of controls that
performs some action or collect logically similar information from the user.
3.4.15 Notify Icon
 Icons in the notification area are shortcuts to processes that are running in the background of a
computer, such as My Computer, Recycle Bin. The Notify Icon class provides a way to program
in this functionality.
Public properties of Notify Icon:
Icon Defines the icon that appears in the notification area.
Text Gets or sets the Tooltip text displayed when the mouse
pointer rests on a notification area icon.
Example:
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace notifyiconex1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
notifyIcon1.Text = DateTime.Now.ToString();
//view output in system tray right side corner of the moniter.
}
}
Page 74 of 98
CS-20 : Programming with C# .Net
}
3.4.16 ProgressBar
 A ProgressBar control is used to represent the progress of a lengthy operation that takes time where
a user has to wait for the operation to be finished. ProgressBar indicates visually the progress of an
operation.
Public properties of ProgressBar:
Style Determines the style of ProgressBar that is displayed.
Minimum To get or set minimum value of change. Default is 0.
Maximum To get or set maximum value of change. Default is 100.
Step Gets or sets the amount by which a call to the PerformStep method
increases the current position of the progressbar.
Value To get or set position within range of the progressbar. Default is 0.

3.5 Dialog Box


 A dialog box is a form defined with particular properties. Like a form, a dialog box is referred to
as a container.
 A dialog box has following characteristics:
o There is only close button.
o It cannot be minimized, maximized or restored.
o Uses of dialog box are:
o Display specific information to users.
o Gather information from users.
o Both display and gather information.
 There are two types: modal and modeless
 A modal dialog box is displayed by a function when the function needs additional data from a
user to continue.
 Because the function depends on the modal dialog box to gather data, the modal dialog box also
prevents a user from activating other windows in the application while it remains open.
 In most cases, a modal dialog box allows a user to signal when they have finished with the modal
dialog box by pressing either an OK or Cancel button.
 Pressing the OK button indicates that a user has entered data and wants the function to continue
processing with that data. Pressing the Cancel button indicates that a user wants to stop the
function from executing altogether. The most common examples of modal dialog boxes are
shown to open, save, and print data.
3.5.1 Colour Dialog
 A C# ColorDialog control is used to select a color from available colors and also define custom
colors. We can create a ColorDialog control using a Forms designer at design-time or using the
ColorDialog class in code at run-time (also known as dynamically). Unlike other Windows Forms
controls, a ColorDialog does not have and not need visual properties like others. The only purpose
of ColorDialog to display available colors, create custom colors and select a color from these
colors. Once a color is selected, we need that color in our code so we can apply it on other
controls.
Example:
private System.Windows.Forms.ColorDialog colorDialog1;
this.colorDialog1 = new System.Windows.Forms.ColorDialog();

Page 75 of 98
CS-20 : Programming with C# .Net
3.5.2 Font Dialog
 We can create a FontDialog control using a Forms designer at design-time or using the
FontDialog class in code at run-time (also known as dynamically). Unlike other Windows Forms
controls, a FontDialog does not have and not need visual properties like others. You use a
FontDialog to list all the fonts and select one of them and usually apply selected fonts on controls
or some contents.
Example:
private System.Windows.Forms.FontDialog fontDialog1;
this.fontDialog1 = new System.Windows.Forms.FontDialog();
3.5.3 SaveFile Dialog
 We can create a SaveFileDialog control using a Forms designer at design-time or using the
SaveFileDialog class in code at run-time (also known as dynamically). Unlike other Windows
Forms controls, a SaveFileDialog does not have and not need visual properties like others.
Example:
privateSystem.Windows.Forms.SaveFileDialog saveFileDialog1;
this.saveFileDialog1 =newSystem.Windows.Forms.SaveFileDialog();
3.5.4 Open File Dialog
 We can create an OpenFileDialog control using a Forms designer at design-time or using the
OpenFileDialog class in code at run-time (also known as dynamically). Unlike other Windows
Forms controls, an OpenFileDialog does not have and not need visual properties like others. The
only purpose of OpenFileDialog to display available colors, create custom colors and select a
color from these colors. Once a color is selected, we need that color in our code so we can apply it
on other controls.
Example:
privateSystem.Windows.Forms.OpenFileDialog openFileDialog1;
this.openFileDialog1 =newSystem.Windows.Forms.OpenFileDialog();
3.6 MDI Concept with MDI Notepad
 A multiple document interface (MDI) is a graphical user interface in which multiple windows
reside under a single parent window. Such systems often allow child windows to embed other
windows inside them as well, creating complex nested hierarchies. This contrasts with the single
document interfaces (SDI) where all windows are independent of each other.
Advantages of Multiple Document Interface
 With MDI, a single menu bar and/or toolbar is shared between all child windows, reducing
clutter and increasing efficient use of the screen space.
 An application's child windows can be hidden/shown/minimized/maximized as a whole.
Creating an MDI Parent Form with a Menu Bar
 In this exercise, you will create an MDI form in the WinApp project. You will also see how to
create a menu bar for the parent form, that will allow you to navigate to all the child forms. To do
so, follow these steps:
1. Navigate to Solution Explorer, select the WinApp project, right-click, and select "Add" ->
"Windows form". Change the Name value from "Form1.cs" to "ParentForm.cs", and click
"Add".
2. Select the newly added ParentForm in the Design View. Select the ParentForm form by clicking
the form's title bar, navigate to the Properties window, and set the following properties:
o Set the "IsMdiContainer" property to True (the default value is False). Notice that the
background color of the form has changed to dark gray.
o Set the Size property's Width to 546 and Height to 411.

Page 76 of 98
CS-20 : Programming with C# .Net
3. Drag a MenuStrip control to the ParentForm. In the top-left corner, you should now see a drop-
down showing the text "Type Here". Enter the text "Open Forms" in the drop-down. This will be
your main, top-level menu.
4. Now under the Open Forms menu, add a submenu by entering the text "Win App".
5. Under the Win App submenu, enter "User Info".
6. Now click the top menu, "Open Forms", and on the right side of it, type "Help". Under the Help
menu, enter "Exit".
7. Now, click the top menu, on the right side of Help, type "Windows".
8. Under the Windows menu, add the following options as separate submenus: Cascade, Tile
Horizontal, Tile Vertical, and Arrange Icons. These will help in arranging the child forms.
9. Now it's time to attach code to the submenus you have added under the main menu Open Forms.
First, you'll add code for the submenu Win App, that basically will open the WinApp form. In
the Design View, double-click the "Win App" submenu, that will take you to the Code View.
Under the click event, add the following code:
WinApp objWA = new WinApp();
objWA.Show();
10. Now to associate functionality with the User Info submenu: double-click this submenu, and
under the click event add the following code:
UserInfo objUI = new UserInfo();
objUI.Show();
11. To associate functionality with the Exit submenu located under the Help main menu, double-
click "Exit", and under the click event add the following code:
Application.Exit();
12. Now you have the form-opening code functionality in place, and you are nearly set to run the
application. But first, you need to set the ParentForm as the start-up object. To do so, open
Program.cs, and modify the "Application.Run(new UserInfo());" statement to the following:
Application.Run(new ParentForm());
13. Now build the solution, and run the application by pressing F5; the MDI application will open
and should look as in Figure 1-1.

Figure 1-1. Running an MDI form application

Page 77 of 98
CS-20 : Programming with C# .Net
14. Now if you click "Win App" and then "User Info" then both the forms will open one by one.
These forms can be opened and dragged outside of the MDI form. This is not an expected
behaviour from a MDI application, as shown in Figure 1-2.

Figure 1-2. Running an MDI form application

Page 78 of 98
CS-20 : Programming with C# .Net
4.1 Introduction to ADO.NET
 ADO.NET stands for Activex Data Object. ADO.NET is an object-oriented set of libraries that
allows you to interact with data sources. ADO.NET allows you to connect application with database
in Microsoft .Net platform.
 ADO.NET is a collection of classes, interfaces, structures and enumerated data types that manage
data access from relational data stores within the .NET Framework. These collections are organized
into namespaces: System.Data, System.Data.OleDb, System.Data.SqlClient, etc.
4.2 ADO.NET Architecture
 The ADO.NET components have been designed to factor data access from data manipulation.
There are two central components of ADO.NET that accomplish this: the DataSet, and the .NET
Framework data provider, which is a set of components including the Connection, Command,
DataReader, and DataAdapter objects.

Disconnected Connected
 The ADO.NET DataSet is the core component of the disconnected architecture of ADO.NET. The
DataSet is explicitly designed for data access independent of any data source. As a result it can be
used with multiple and differing data sources, used with XML data, or used to manage data local
to the application. The DataSet contains a collection of one or more DataTable objects made up of
rows and columns of data, as well as primary key, foreign key, constraint, and relation
information about the data in the DataTable objects.

4.3 Data Providers in ADO.NET


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.
The ADO.NET Framework comes with the following providers
 OLEDB: The OLEDB provider, is 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.

Page 79 of 98
CS-20 : Programming with C# .Net
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.
Core objects that makeup a .NET Framework data provider
 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, the .NET Framework data provider also contains the classes Transaction,
CommandBuilder, ConnectionStringBuilder, Parameter, Exception, Error, and ClientPermission.

4.4 Connection Object


 The Connection object is the first component of ADO.NET that you should be looking at. A
connection sets a link between a data source and ADO.NET. A Connection object sits between a
data source and a DataAdapter (via Command). You need to define a data provider and a data
source when you create a connection. With these two, you can also specify the user ID and
password depending on the type of data source. Figure 3-3 shows the relationship between a
connection, a data source, and a data adapter.

Figure 1: The relationship between connection, data adapter, and a data source

 Connection can also be connected to a Command object to execute SQL queries, which can be
used to retrieve, add, update, and delete data to a data source. Figure 2 shows the relationship
between the Command and Connection objects.

Figure 2: The relationship between the command object and the connection object

 The Connection object also plays a useful role in creating a transaction. Transactions are stored in
transaction objects, and transaction classes have all those nice features for dealing with
transactions such as commit and rollback. Figure 3 shows the relationship between the connection
object and the transaction.

Page 80 of 98
CS-20 : Programming with C# .Net

Figure 3: Creating a transaction from a connection object

 Each data provider has a Connection class. Below Table shows the name of various connection
classes for data providers.
 Table: Data provider connection classes

DATA PROVIDER CONNECTION CLASS


OleDb OleDbConnection
Sql SqlConnection
ODBC OdbcConnection

4.5 Connected Architecture


4.5.1 The Command object:
 After establishing connection with the database, we can use the Command object for processing
requests in the form of command and returning the results of those requests from the database.
The Command object enables access to database commands to return data, modify data,
run stored procedures, and send or retrieve parameter information.

4.5.2 The DataReader object:


 The DataReader provides a high-performance stream of data from the data source. DataReader
object facilitates communication between the data source and the dataset, it is used to transfer data
from the data source to the dataset and vice versa. It is used mainly to work with the data in the
dataset and then transferring changed data back to the data source.

4.6 Disconnected Architecture


4.6.1 The DataAdapter object:
 The DataAdapter provides the bridge between the DataSet object and the data source. The
DataAdapter uses Command objects to execute SQL commands at the data source to both load the
DataSet with data, and reconcile changes made to the data in the DataSet back to the data source.
4.6.2 Data Set
 It is a class present under the “System.Data” namespace design for holding and managing data on
client machines apart from a DataReader.
Features of DataSet
1. It is also capable of holding multiple tables.
2. It is a designed disconnected architecture that doesn't require a permanent connection with a
Data Source for holding data.
3. It provides scrollable navigation to data, that allows us to move in any direction. In other
words, either top to bottom or bottom to top.

Page 81 of 98
CS-20 : Programming with C# .Net
4. It is updatable, in other words, changes can be performed to data present in it and also send
changes back to the DB.
Working with DataSet
 This class is responsible for the loading of data into a DataReader from a DataSource and is a
command.
 In the same way, the DataAdapter class is used for communication between a DataSource and
DataSet.
Methods of DataAdapter
1. Fill (DataSet ds,string TableName).
2. Update (DataSet ds,string TableName)
Fill in the method to load data from a DataSource into a DataSet.
Update is to transfer data from a DataSet to a DataSource.
 DataAdapter is internally a collection of the following 4 methods:
1. Select Command.
2. Insert Command.
3. Update Command.
4. Delete Command.
 When we call the Fill() method of Adapter, the following action takes place internally.
1. Open a connection with the DataSource.
2. Execute the Select command under it on the DataSource and loads data from the table to
the DataSet.
3. Close the Connection.
 Siince a DataSet is updatable, changes can be made to data that is loaded into it, like adding,
modifying and deleting records.
 After making all the changes to the data in a dataset if we want to send those changes back to the
DataSource then call the Update() method on the DataAdapter that performed the following:
1. Re-opened a connection with the DataSource.
2. Changes made in the dataset will be sent back to the table where in this process it will use
the insert, update and delete commands of the DataAdapter.
3. Close the Connection.
Accessing Data from DataSet
 DataReader provides us a pointer vases access to the data, so we can get data only in sequential
order, whereas a dataset provides us index-based access to data so we can get the data from any
location.
 Dataset is a collection of tables where each table is represented as a DataTable class and identified
by the index position.

4.6.3 DataTable
 DataTable is the collection of tables.
 The following syntax is used for a DataTable:
<DataSet>.Tables[Index]/[Name]
Example:
Ds.Tables[0]
Or
Ds.tables[“Company”]
 Every DataTable is again a collection of Rows and Columns where each row is represented as a
DataRow class and identified by its index position.
 Each column is represented as a DataColumn class and identified by index position or name.

Page 82 of 98
CS-20 : Programming with C# .Net
4.6.4 DataRow
 It is a collection of rows.
Syntax:
<datatable>.Rows[Index].
Example:
Ds.tables[0].rows[0]

4.6.5 DataColumns
 It is a collection of Columns.
Syntax:
<datatable>.Columns[Index] OR columns[Name]

Example:
Ds.Tables[0].Column[0]
Or:
Ds.Tables[0].Column[“ENO”]
Ds.tables[0].rows[0]
 The following is the syntax for referring to a cell under a Data Table:
<datatable>.Rows[row] [col]
Example:
Ds.Tables[0].Rows[0][0]
Or:
Ds.Tables[0].Rows[0][“ENO”]
Ds.tables[0].rows[0]

4.6.6 Data Relation


 The DataRelation is a class of disconnected architecture in the .NET framework. It is found in the
System.Data namespace. It represents a relationship between database tables. It correlates tables
on the basis of matching column.
4.6.7 Data View
 A major function of the DataView is to allow data binding on both Windows Forms and
WebForms. Additionally, a DataView can be customized to present a subset of data from the
DataTable. This capability allows you to have two controls bound to the same DataTable, but
showing different versions of the data. For example, one control may be bound to a DataView
showing all of the rows in the table, while a second may be configured to display only the rows
that have been deleted from the DataTable. The DataTable also has a DefaultView property that
returns the default DataView for the table. For example, if you wish to create a custom view on
the table, set the RowFilter on the DataView returned by the DefaultView.
 A DataView object serves a similar purpose to views in the SQL context. Both are ways to select
a subset of the columns and rows in a table. In SQL Server, it is possible to create a view based on
the result of almost any query, but a DataView in ADO.NET is limited to operation on one table
only. However, unlike views in some versions of SQL Server, a DataView can be sorted into a
given order. The DataViewManager and the DataViewSetting classes do allow multiple table
views.
 A DataView enables you to create different views of the data stored in a DataTable, a capability
that is often used in data-binding applications. Using a DataView, you can expose the data in a
table with different sort orders, and you can filter the data by row state or based on a filter
expression. A DataView provides a dynamic view of data whose content, ordering, and
membership reflect changes to the underlying DataTable as they occur. This is different from the
Select method of the DataTable, which returns a DataRow array from a table per a particular filter
and/or sort order and whose content reflects changes to the underlying table, but whose
Page 83 of 98
CS-20 : Programming with C# .Net
membership and ordering remain static. The dynamic capabilities of the DataView make it ideal
for data-binding applications.
4.7 Data Binding
 Bind data from a Data Source (such as ADO.NET) to a Windows Forms form.
Objectives
 Learn to Build a simple data-bound form
 Learn to implement complex data binding
Contents
 Simple data binding with a TextBox control
 Complex Data binding with DataGridView and ComboBox
 Navigating Between records with Binding Navigator
Windows Forms allow you to bind easily to nearly any structure that contains data. With data
binding, you do not need to explicitly write the code that instantiates a connection and creates a
dataset.On the basis of the number of bound values that can be displayed through a control of a
windows form, binding can be classified into:
 Simple data binding
 Complex data binding

4.7.1 Simple data binding


 Simple data binding allows you to bind a control to a single data element. The most common use
of simple data binding involves binding a single data element, such as the value of a column in a
table, to a control on a form. You use this type of data binding for controls that show only one
value. Uses of simple data binding include binding data to text boxes and labels. Consider a
scenario where a Windows Forms form needs to be created to display employee details in the
following way.

In the preceding form, one value needs to be displayed in each of the controls. Therefore simple
data binding will be performed for each control.
Steps
1. Press F4 to open the properties window.
2. Select the first TextBox to display its properties window.
3. Expand the (DataBindings) property.
4. Select the text property to enable the drop-down list. Click the drop-down list.
5. Add a project data source in the drop-down list.

Page 84 of 98
CS-20 : Programming with C# .Net

6. Create a connection with the AdventureWorks database and select the HumanResources.employee
table.
7. Select the first TextBox. Expand "Other data source" ---> "Project data source" -->
"AdventureWorksdataset" --> "Employee" --> "EmloyeeId".
8. Select the second TextBox. Expand the DataBinding property then select "Text" ---> "Employee
Binding source" then select column(National ID) from the list.
9. Similarly, bind TextBox3 and TextBox4 with the column contactid and Login ID.
10. Press F5. If everything goes well, you will see the following output:

 Here is one problem with the preceding. Every time you run your project, you are able to see only
one record. So how to solve this problem?
 We can solve that problem using the BindingNavigator Control. For every data source that is
bound to a Windows Forms control, there exists a BindingNavigator control. The
BindingNavigator control handles the binding to the data by keeping the pointer to the item in the
record list current.

Implementing BindingNavigator
1. Drag and drop a BindingNavigator control from the Toolbox.

Page 85 of 98
CS-20 : Programming with C# .Net

2. Select BindingNavigator1; this will display the properties window.


3. Select the bindingSource property from the properties Window to enable the corresponding drop-
down list.
4. Select employeeBindingSource from the Drop-Down list as shown in the following figure.

5. Execute the Windows Forms form and verify the output. The Employee Details will be displayed as
shown in the following figure.

The following table describes the various symbols and their function in the BindingNavigator control:

Page 86 of 98
CS-20 : Programming with C# .Net

4.7.2 Complex Data Binding


 Complex data binding allows you to bind more than one data element to control. Using the
column example, complex data binding involves binding more than one column or row from the
underlying record source. Controls that support complex data binding include data grid controls,
combo boxes, and list boxes.
Let's see complex data binding with a DataGridView:
1. Drag and drop a DataGridView from the Toolbox under the Data tab.

2. Click on the DataGridView task pop-up menu as shown in the following figure.

3. Select the choose Data Source drop-down list and then select the Add Project Data Source from the
DataGridView task pop-up menu as shown in the following figure.

Page 87 of 98
CS-20 : Programming with C# .Net

4. In the database configuration wizard select database and click on "Next" as shown in the following
figure.

5. After clicking on the Next button you will get the following output.

6. Click on "New Connection" to create a new connection to your data source.


To add a connection:
o Provide the server name (in my case it is (.))

Page 88 of 98
CS-20 : Programming with C# .Net
o If your server is not using Windows authentication then select "Use SQL Server
authentication".
o Provide the username and password.
o Provide the database name AdventureWorks from the Select or enter a database name drop-
down list.
o Click on the Test Connection Button. If everything goes well you will see a message box
saying thatTest the connection succeeded as shown in the following figure.

7. Click the OK button.


8. Click the OK button on the Add Connection dialog box.
9. Select Yes, Include sensitive data in the connection string, and click the "Next" button in the
DataSource configuration wizard. You will get a page as displayed in the following figure.

Page 89 of 98
CS-20 : Programming with C# .Net
10. Ensure that the Yes, save the connection as the check box is selected and the
AdventureWorksConnection string appears in the TextBox.
Note: We will see what the use of saving the connection string in the App.config file is in my future
article on ADO.Net.
11. Click the "Next" button. The Choose Your Database Objects page is displayed as shown in the
following figure.

12. Expand the table node and select the HumanResources.Employee table is shown in the following
figure.

13. Click the "Finish" button. The form is displayed, as shown in the following figure.

Page 90 of 98
CS-20 : Programming with C# .Net

14. Press F5 to execute the application. You will get the following output.

4.8 GridView Programming

The GridView control displays the values of a data source in a table. Each column represents a field,
while each row represents a record. The GridView control supports the following features:
 Binding to data source controls, such as SqlDataSource.
 Built-in sort capabilities.
 Built-in update and delete capabilities.
 Built-in paging capabilities.
 Built-in row selection capabilities.
 Programmatic access to the GridView object model to dynamically set properties, handle events,
and so on.
 Multiple key fields.
 Multiple data fields for the hyperlink columns.
 Customizable appearance through themes and styles.

Creating a GridView
<asp:GridView ID="gridService" runat="server">
</asp:GridView>

Page 91 of 98
CS-20 : Programming with C# .Net
GridView control in ASP.Net using C# code behind. In this, we perform the following operations on
GridView.
 Bind data to the GridView column
 Edit data in GridView
 Delete rows from GridView
 Update row from database

Page 92 of 98
93

You might also like