CS-20 Programming With C#Net - 240104 - 194116
CS-20 Programming With C#Net - 240104 - 194116
-: 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
Page 1 of 98
CS-20 : Programming with C# .Net
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.
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
ViewToolbox 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
ViewProperties 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
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
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][];
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.
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
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);
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);
}
}
}
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
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.
Page 37 of 98
CS-20 : Programming with C# .Net
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
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;
static void SetValue(ref string str1) static void SetValue(ref string str1)
{ {
Console.WriteLine("Hello!!MJK"); Console.WriteLine("Hello!!MJK");
} }
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
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.
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"
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();
}
}
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();
}
}
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();
// 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();
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
}
}
}
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.
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.
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
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.
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
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.
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.
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.
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.
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.
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
Each data provider has a Connection class. Below Table shows the name of various connection
classes for data providers.
Table: Data provider connection classes
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]
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
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
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.
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.
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.
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