0% found this document useful (0 votes)
235 views

C# Console

Uploaded by

Niranjan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
235 views

C# Console

Uploaded by

Niranjan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 248

Edited with the trial version of

Foxit Advanced PDF Editor


To remove this notice, visit:
www.foxitsoftware.com/shopping

Microsoft® .NET Framework 4.0

An d

C#.NET

.NET 4.0 and Visual Studio 2010 Page 1 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

.NET Framework 4.0 and Visual Studio 2010


C#.NET Training Program Schedule

Chapter – I: .NET Framework Basics

Hour 1 Introduction to .NET Framework Page 5


Hour 2 Applications of .NET, Versions of .NET, Advantages of .NET Page 11
Hour 3 .NET Framework Architecture, FCL, CTS, MSIL, Assemblies, CTS Page 21

Hour 4 Execution Environment of .NET Apps, CLR Page 27


Hour 5 Introduction to Visual Studio, Getting Started with Visual Studio 2010 Page 30

Chapter – II: C# Language Basics

Hour 6 C# Introduction, Basics of Language, Application Definition Syntax Page 45


Hour 7 Keywords, System.Console Class, Data Types, Variables, Constants Page 51
Hour 8 Type Casting, Boxing and Unboxing, Scope of Variables, Operators, Control Page 60
Statements, Enumerations
Hour 9 Arrays, Command Line Arguments Page 74

Chapter – III: Object Oriented Programming

Hour 10 Introduction to OOP, Access Modifiers, Principles of OOP, Classes, Page 86


Objects, Fields, Methods
Hour 11 Read-only Fields, Ref parameters, Out parameters, “this” keyword, Named Page 96
Parameters
Hour 12 Static Members, Static Classes, Constructors, Destructors, Object Initializer Page 102
Hour 13 Static Constructors, Method Overloading, Operator Overloading Page 111
Hour 14 Generics, Properties, Partial Classes Page 116
Hour 15 Indexer, Inheritance, Sealed Classes, Hiding the Methods, Method Page 130
Overriding
Hour 16 Abstract Classes and Methods, Interfaces, Structures Page 146
Hour 17 Extension Methods, Delegates Page 154

.NET 4.0 and Visual Studio 2010 Page 2 of 548


Chapter – IV: Utility Programming

Hour 18 Array Class, Math Class, String Class Page 159


Hour 19 DateTime Structure, Random Class, Collections, Collection Initializer, Page 171
PrintDocument Class
Hour 20 DriveInfo Class, DirectoryInfo Class Page 184
Hour 21 FileInfo class, StreamWriter Class, StreamReader class Page 191
Hour 22 Multi Threading, Anonymous Methods Page 197
Hour 23 Speech Translation, Memory Management Page 205
Hour 24 LINQ Page 211
Hour 25 Exception Handling, EventLog, Break points, Immediate window Page 220
Hour 26 Assemblies Page 236

Chapter – V: Windows Forms Applications Development using C#

Hour 27 Getting started with Windows Apps Page 243


Hour 28 Button, Event Handling, The “Form” class Page 256
Hour 29 Label, Textbox, Checkbox, Radiobutton, LinkLabel, Picturebox Page 276
Hour 30 Panel, GroupBox, Listbox, Combobox, TreeView, NumericUpdown, Page 290
DomainUpdown, DateTimePicker, MonthCalendar
Hour 31 TrackBar, Timer, ProgressBar, MenuStrip, ContextMenuStrip Page 307
Hour 32 ColorDialog, FontDialog, OpenFileDialog, SaveFileDialog, PrintDialog, Page 319
RichTextBox, NotifyIcon
Hour 33 TabControl, TreeView, MDI Applications, ToolStrip, StatusStrip, Page 336
MessageBox, Adding Controls Programmatically
Hour 34 User Controls and Windows Forms Control Library Page 350
Hour 35 Creating Graphics with GDI+ Page 359

.NET 4.0 and Visual Studio 2010 Page 3 of 548


Chapter – VI: Data Access using C# with ADO.NET support

Hour 36 SQL Server Basics Page 367


Hour 37 ADO.NET Basics, ADO.NET Library and ADO.NET Database Connection Page 378
Hour 38 Sending Commands to the Database using Command Class Page 388
Hour 39 Retrieving Data using Command and DataReader Page 400
Hour 40 ADO.NET Disconnected Model using DataAdapter, DataSet, DataTable, Page 416
DataRow and DataColumn
Hour 41 Working with Stored Procedures and Functions Page 432
Hour 42 Storing the Connection String in App.config Page 444

Chapter – VII: Database Reports Development using C#

Hour 43 Crystal Reports Page 447

Chapter – VIII: Network Programming using C#

Hour 44 Introduction to Distributed Application Development Page 454


Hour 45 .NET Remoting Page 465
Hour 46 .NET Remoting Page 469
Hour 47 Network communication with Sockets Page 477

Chapter – IX: Windows Services Development using C#

Hour 48 Windows Services Basics, ServiceProcessInstaller, ServiceInstaller, Page 483


installutil.exe
Hour 49 Development of Windows Services, ChatService Development Page 485

Chapter – X: Package and Deployment

Hour 50 Setup Project Development, Installing and Un-installing the projects Page 496

Chapter – XI: Mini Project

Chapter – XII: FAQ’s

.NET 4.0 and Visual Studio 2010 Page 4 of 548


An Introduction to .NET Framework

 The .NET framework is a collection of many small technologies integrated together, to


develop most powerful applications which can be executed anywhere and anytime.
 In other words, .NET Framework is a Microsoft's development platform, which is used
for development of software applications.
 It‘s a ―Network enabled technologies collection‖. That‘s why it was named as ―.NET‖.
There is no any abbreviation for ―.NET‖.
 It can also be considered as ―Frontend Tool‖ as it is used to develop the frontend
applications.
 For the any live project development, we require two tools to be used:
 Frontend tool: It is used to develop UI (User Interface), which is actually
visible by the user. The UI can be termed as ―Application‖. The limitation of
application is: any frontend application can‘t store the data. That‘s why you
require backend tool to store the necessary data.

 Backend tool: It acts as storage mechanism. The data related to the project
will be stored in this backend tool. It allows us to create and store the databases.
Ex: Oracle, SQL Server, My SQL, Sybase, DB2 etc.

 It was released by Microsoft Corporation in 2002. At this year, in the programming world,
we have so many languages like Basic, COBOL, Pascal, Fortran, C, C++, VB, VC++ etc.
But if you observe these languages, each and every language is having its own

.NET 4.0 and Visual Studio 2010 Page 5 of 548


limitations and boundaries only. To overcome all of the limitations, Microsoft announces
and releases .NET Framework in 2002.
 Later, several improvements take place in .NET Framework, which makes it as much
strong, advanced and more efficient platform for building different kinds of software
applications.
 It offers visually stunning user experiences, which is mostly required today‘s competitive
programming world.
 It offers much advanced security features never before.
 It‘s not a single language; it‘s a collection of multiple languages and multiple
technologies. That‘s why it can be called as ―platform‖ (by containing multiple languages
and technologies).
 .NET Framework:
 Languages:
1. VC#.NET  Visual C Sharp.NET
2. VB.NET  Visual Basic.NET
3. VC++.NET  Visual C++.NET
4. VJ#.NET  Visual Java Sharp.NET
etc.
 Technologies:
1. ASP.NET  Active Server Pages.NET
2. ADO.NET  ActiveX Data Objects.NET
3. WCF  Windows Communication Foundation
4. WPF  Windows Presentation Foundation Introduced in .NET 3.0
5. WWF  Windows Workflow Foundation
6. AJAX  Asynchronous JavaScript And Xml
Introduced in .NET 3.5
7. LINQ  Language Integrated Query

 Language: It acts as interface (mediator) between the programmer and the system. It
offers some rules and regulations for writing the programs. It also offers some library,
which is required for writing the programs. Obviously, the collection of programs is called
as ―Software‖.

 Technology: It is designed for a particular purpose. For example, for development of


web related applications, you have a technology called ―ASP.NET‖. For development of

.NET 4.0 and Visual Studio 2010 Page 6 of 548


database related applications, you have another technology called ―ADO.NET‖. Bu the
technology doesn‘t offer any specific rules for writing the programs. But it offers some
library. That‘s why; a technology can‘t be implemented individually. It requires a
language for the rules to write the programs.

Features of .NET Framework

 Next Generation User Experiences:


.NET offers a Framework for building applications and high-fidelity
experiences in Windows that blend together application UI, documents, and media
content, while exploiting the full power of the computer. WPF (Windows Presentation
Foundation) offers developers support for 2D and 3D graphics, hardware accelerated
effects, scalability to different form factors, interactive data visualization, and
superior content readability.

 Seamless and Secured Environment:


Application security is a big deal these days; perhaps the most closely
examined feature of any new application. .NET offers its best secured environment at
run time. So that it is highly impossible to access the .NET application and its related
data by the un-authorized users / hackers.

The assembly (the compiled code of .NET framework) contains the


security information like which categories of users or who can access the class or
method. So that we can say that .NET Framework applications are much secured.

The security can be improved in the ASP.NET Web Sites by Security


models like Integrated Windows Authentication, Microsoft Passport Authentication,
Forms Authentication, and Client Certificate authentication.

.NET 4.0 and Visual Studio 2010 Page 7 of 548


 Multi Language Support:
.NET provides a multi-language development platform, so you can work
in the programming language you prefer. The Common Language Runtime (A part of

.NET Framework) provides support for 3 Microsoft developed languages and several
other languages from other vendors.

Languages Supported by .NET Framework


Languages from Visual C#.NET
Visual Basic.NET
Microsoft
Visual C++.NET
Languages from other VJ#.NET,
Python.NET,
vendors
IronPython.NET,
APL.NET,
Cobol.NET,
Perl.NET,
Pascal.NET,
Component Pascal.NET,
Curriculum.NET,
Eiffel.NET,
Forth.NET,
Fortran.NET,
Haskell.NET,
Mercury.NET,
Mondrian.NET,
Oberon.NET,
RPG.NET,
Scheme.NET,
Small Talk.NET,
Standard ML.NET

 Flexible Data Access:


.NET Framework supports flexible accessibility of database data with
ADO.NET (ActiveX Data Objects .NET). ADO.NET is a set of classes that expose data
access services to the .NET programmer. 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.

.NET 4.0 and Visual Studio 2010 Page 8 of 548


 Superior of all previous languages and technologies:
Microsoft‘s target is to be at the top of all the development technologies
/ languages. That‘s why Microsoft designed .NET Framework with more advanced
and superior programming features and standards, such as
 Platform independency
 Hardware independency
 Language independency
 Automatic generation of designer code
 Multi-threaded programming
 Rich OOP features like delegates, interfaces, extension methods,
anonymous types, anonymous methods etc.
 Support for mobile application development
etc.

Modules of .NET

1. VC#.NET (Visual C Sharp.NET) –(Language)

 It is highly used .NET programming


language, used by most of the .NET
programmers.

 It borrows some programming features from ―C‖ and some other


programming features from ―C++‖. In addition to these, it borrows few of
the good features of java language.

 It is the object oriented programming language.

2. VB.NET (Visual Basic.NET) –(Language)

 It is the Microsoft‘s recommended


language for beginners of windows
programming.

.NET 4.0 and Visual Studio 2010 Page 9 of 548


 But in fact, it is used in very few of the projects in the real-time development
world, because most of the programmers usually comes with ―C‖ and ―C++‖
background; hence they feel comfortable with ―C#‖.

 It borrows some programming features from VB (Visual Basic) language.

 It is the object oriented programming language.

3. ASP.NET (Active Server Pages.NET) – (Web Technology)

 It is the Microsoft‘s web technology.

 It is used for web sites development.

 It offers much attractive and user friendly


user interfaces in the server side
applications.

 It is the new version to another Microsoft‘s technology called ASP (Active


Server Pages), which is a famous web technology before introducing
ASP.NET.

 It requires HTML for web page designing.

 It requires a .NET language (like C#, VB.NET, VC++.NET etc.) for server
side logic implementation.

4. ADO.NET (ActiveX Data Objects.NET) – (Database Technology)

It is the Microsoft‘s database technology.

 It offers necessary programming libraries to access


the local / server databases.

 It is the new version to another Microsoft‘s


technology called ADO (ActiveX Data Objects),
which is a famous database technology, used with
VB, VC++ and ASP languages.

 It requires a .NET language (like C#, VB.NET, VC++.NET etc.) for logic
implementation.

.NET 4.0 and Visual Studio 2010 Page 10 of 548


Applications of .NET
Using .NET Framework, we offered to develop the following types of applications.

1. Console Applications

 These applications contains similar user interface to the operating systems like MS-
DOS and UNIX.

 Known as C.U.I (Character User Interface) applications.

 These are similar to C/C++ applications.

 These are smaller in size.

 Doesn‘t contain any graphical features like mouse pointer, colors, fonts, buttons etc.

2. Windows Forms Applications


 These applications are designed similar to the ―Windows‖ operating system.

 Known as G.U.I (Graphical User Interface) applications.

 Offers graphical features like mouse pointer, colors, fonts, buttons, text boxes etc.

.NET 4.0 and Visual Studio 2010 Page 11 of 548


3. Windows Services
 A Windows service is a long-running executable application.

 These can run only on windows platforms.

 These perform specific functions as background process.

 Doesn‘t contain user interface or doesn‘t require any user interaction.

 Windows services can be configured to start when the operating system


is booted and run in the background as long as Windows is running, or they can be
started manually when required.

 Examples:

i. Windows Time.

ii. Windows Audio.

iii. Anti-Virus Security.

iv. Database services like SQL Server, My SQL and Oracle etc.

v. Plug and Play.

vi. Battery Power Supply Status on Laptops.

etc.

 To see the all the installed windows services on the system, click on ―Start‖ –
―Control Panel‖ – ―Administrative Tools‖ – ―Services‖.

.NET 4.0 and Visual Studio 2010 Page 12 of 548


4. Windows Mobile Applications
 The Mobile applications can run on the
small devices like Pocket PCs, Smart
phones and mobile devices.

 Ex: Mobile based calculators, schedulers,


database manipulation applications etc.

.NET 4.0 and Visual Studio 2010 Page 13 of 548


5. Web Sites / Web Applications
 These are most frequently used applications by every internet literature.

 In modern life every business (commercial) / educational / service oriented


organizations are having their own web sites.

 Some other web sites are offering general purpose services that can be used by
anybody like E-Mail, Search Engines, and Blogs etc.

 So, there is much demand for these applications in modern software development
industry.

 In .NET Framework, the web sites can be developed using the technology called
ASP.NET.

 Ex:

i. http://www.yahoo.com/

ii. http://www.google.co.in/

iii. http://www.orkut.com/

iv. http://www.hotmail.com/

.NET 4.0 and Visual Studio 2010 Page 14 of 548


6. Web Services
 Web Services are simple and easy to understand.

 These can be developed using again ASP.NET.

 The web services are used to implement ―SOA‖ (Service Oriented Architecture) in
web applications.

 The main purpose of SOA is to implement some interaction between two


applications.

 Examples:

i. Online shopping requires credit card authentication, from back web site.

ii. www.way2sms.com accesses the mail services of Yahoo and Gmail.

7. WPF Applications
 WPF stands for Windows Presentation Foundation.

 WPF Applications are GUI applications similar to ―Windows Applications‖.

 These Applications support more advanced graphical features like shapes, object
transformation, brushes etc.

.NET 4.0 and Visual Studio 2010 Page 15 of 548


What you need to learn .NET
To get started with .NET Programming, the programmer must have
previous knowledge in the following languages.

 C
(For General Programming Experience)

 C++ (or) OOP Theory


(For Object Oriented Programming Experience)

 SQL
(For writing the database queries in ADO.NET)

 HTML
(For web page designing in ASP.NET)

Promises by Microsoft:

While introducing .NET Framework, Microsoft Corporation has given a promise to


the software industry to deliver a standard Framework which overcomes the old problems and
along with following:

 Multiple platforms: The system runs on a broad range of computers, from servers and
desktop machines, smart phones and cell phones.
 Industry standards: The system uses industry standard communication protocols,
such as XML, HTTP, SOAP, and WSDL.
 Security: The system can provide a much safer execution environment, which can‘t be
hacked or robbed by others.

.NET 4.0 and Visual Studio 2010 Page 16 of 548


Versions of .NET

.NET Framework Exact Version Date of Release Visual Studio


Version Number

.NET Framework 1.0 1.0.3705.0 Feb 13, 2002 Visual Studio.NET 2002

.NET Framework 1.1 1.1.4322.573 April 24, 2003 Visual Studio.NET 2003

.NET Framework 2.0 2.0.50727.42 November 17, 2005 Visual Studio 2005

.NET Framework 3.0 3.0.4506.30 November 06, 2006 [No Visual Studio]

.NET Framework 3.5 3.5.21022.8 November 19, 2007 Visual Studio 2008

.NET Framework 4.0 4.0.30319.0 April 12, 2010 Visual Studio 2010

dvantages of .NET

 Supports multiple languages like VC#, VB.NET, VC++.NET, VJ#.NET etc., so that the
programmer can write the code in his/her interested language.
 Offers more secured environment never before.
 Offers flexible data access with ADO.NET.
 Supports to develop windows services and web services, which are necessary to
handle in the live projects in the modern programming world.
 Supports to develop applications for small devices like PDA‘s, smart phones, mobile
phones etc.
 Offers ―Partial platform independency‖, because it supports to run the .NET
applications on Windows and LINUX platforms with Mono Tool.
 Offers easier and faster UI design (with drag and drop technique), when compared with
the languages like Java.

.NET 4.0 and Visual Studio 2010 Page 17 of 548


 Offers the best debugging tools in the industry, which makes the programmer to easily
fix the bugs.
 Offers improved object oriented programming features like properties, sealed
classes, inner classes, delegates, enumerations, collections, interfaces, generics,
extension methods, anonymous types, anonymous methods, lambda expressions, named
parameters etc.
 Offers to share and reuse the code among multiple applications very easily, with the
concept of ―Assemblies‖.
 Offers to write db queries in the programming code itself, using the newly added
querying technology called ―LINQ‖ (Language Integrated Query), which is introduced in
.NET 3.5.
 Offers faster and easier Deployment features, to generate ―Installer packages‖ for
installing the .NET application on the client systems.
 Offers to create multiple threads and also to manage them for creating Multi-Threaded
Applications.
 Offers XML support and interaction, which is mostly required in the modern application
development environment.
 Supports to create user defined graphics like lines, rectangles, bars, circles etc., very
easily using “GDI+” (Graphics Device Interface) concepts.
 Offers a new an attractive feature called WPF (Windows Presentation
Foundation), which is built on Vector based graphics and which enables the
programmer to create 2-D and 3-D graphics, animations, games, audio and view players
etc. This is newly added feature in .NET 3.0.
 Offers another prestigious feature called WCF (Windows Communication Foundation),
which integrates the several distributed technologies like .NET Remoting, SOAP enabled
web services, named pipes and message queues etc., which helps the programmer to
develop service and network oriented applications using .NET. This is newly added
feature in .NET 3.0.
 Support for the most recent web technology called AJAX (Asynchronous JavaScript and
XML) along with ASP.NET. As a result of AJAX, the developer can produce newer
generation user experiences on the web. Ex: www.orkut.com.

.NET 4.0 and Visual Studio 2010 Page 18 of 548


.NET (vs) Java
Microsoft‘s .NET and SUN‘s Java are strong competitors.

Similarities
Sl.
.NET and Java
No
Both of these support to develop console applications, windows applications, web
1
sites, web services etc.
Both use their own intermediate language. Java calls it as ―byte code‖ and .NET
2
calls it as ―MSIL‖.
3 Both are Object oriented programming languages.
4 Both support Remoting.
5 Both support multi-threading.
6 Both support web related languages like Java Script, XML, CSS etc.
7 Both support the recent web development technology like AJAX.
Both support ―Garbage collection‖, which automatically clears the un-used
8
memory.
Both support to develop the applications for small devices like PDA‘s, mobile
9
phones, smart phones etc.
10 Both offer better security features in their own style.

Differences
Sl.
.NET Java
No
It is cost effective. Costs more than It is open source product, which can be
1
$700 (nearly Rs. 35,000) freely downloaded on the Internet.
2 It‘s a collection of multiple languages It‘s itself is a language.
It‘s partially platform independent (as
.NET applications can run on
3 It‘s fully platform independent.
Windows and LINUX operating
systems)
Offers IDE as Visual Studio by Doesn‘t offer any IDE. But other IDE‘s by
4
Microsoft. other vendors such as Eclipse etc.
Offers easiest and fastest application Requires much time for the application
5 development, which indirectly reduces development, which indirectly increases
the cost of the software. the cost of the software.
Designing the UI is very much easy UI Design requires much programmer‘s
6
with ―Drag and Drop‖ technique. effort and stress.
AJAX is implementation is much time
7 AJAX is implementation is much easy. taking process, requires much code to
write.

.NET 4.0 and Visual Studio 2010 Page 19 of 548


.NET Framework Types:

The .NET Framework is available in 3 different types:

 .NET Framework: This is the general version, required to run .NET applications on
Windows operating system.
 .NET Mono Framework: This is required to run .NET applications on other operating
systems like UNIX, LINUX and Solaris etc.
 .NET Compact Framework: This is required to run .NET applications on other devices
like PDA (Personal Digital Assistants), Mobile phones and Smart phones.

.NET 4.0 and Visual Studio 2010 Page 20 of 548


Components of .NET Framework
The .NET Framework is simply a collection of two components.

1. FCL (.NET Framework Class Library)


2. CLR (Common Language Runtime)

You can see the .NET Framework Architecture in the following diagram.

1. .NET Framework Class Library (FCL)


 The .NET Framework class library contains the necessary library classes that are
needed for development of different types of .NET applications like Console
applications, Windows applications, Windows services, ASP.NET Web sites, ASP.NET
Web Services, Windows Communication Foundation (WCF) applications and Windows
Presentation Foundation (WPF) applications.
 The library‘s classes are organized using a hierarchy of namespaces.
 A namespace is nothing but a collection of classes.

.NET 4.0 and Visual Studio 2010 Page 21 of 548


 For example, all the classes for performing I/O operations are located in the
System.IO namespace.
 All the types (structures and classes) are commonly available for all the .NET
languages. This concept can be called as ―CTS‖ (Common Type System).

Naming Convention

We have to follow these naming conventions for good practice of programming:


1. For Namespace, Classes, Structures and Methods:
 Each world in the name space should be started with upper case character.

 Ex: WebControls, Threading, OleDbClient, InitializeComponent() etc.

2. For Variables and objects:


 This is programmer‘s choice. You can maintain all the characters in lower case (or)
you can also maintain the naming convention recommended for namespaces.
Ex: i, abc, Abc, AbcXyz etc.

.NET 4.0 and Visual Studio 2010 Page 22 of 548


The .NET Framework Class Library (FCL) Architecture
The .NET Framework Class Library contains the following namespaces.
Note: A ―namespace‖ is a collection of few classes or namespaces. The inner namespaces, contained by another namespace is
called as ―sub namespace‖. The most frequently used namespaces of FCL are listed here.

System

Windows Web Drawing Linq Xml Data Threading IO Text Speech Runtime

Configuration Remoting
Forms UI Printing OleDb SqlClient

HtmlControls WebControls

.NET 4.0 and Visual Studio 2010 Page 23 of 548


2. Common Language Run Time (CLR)

 The Common Language Runtime (CLR) is the agent that manages your .NET
applications at execution time. In other words, CLR is the completely responsible
component of .NET Framework that is responsible to manage the .NET applications at
run time.
 In other words, The Common Language Runtime (CLR) is the virtual machine in the
.NET Framework.
 It provides core services such as memory management, thread management,
exception handling, security and resource management.
 A .NET application is compiled into a ―bytecode‖ format known as MSIL (Microsoft
Intermediate Language). The MSIL bytecode allows .NET applications to be portable
(at least theoretically) to other platforms because the application is compiled to native
code only during runtime.
 During execution, the CLR‘s JIT (just - in - time) compiles the bytecode into the
processor‘s native code and executes the application.

Assemblies and Microsoft Intermediate Language (MSIL)

 In .NET, when an application is compiled, into a bytecode called MSIL. That MSIL code
is stored in an assembly. The assembly is contained in one or more PE (portable
executable) files and may end with an EXE or DLL extension.
 The assembly contents are:
 Byte code — The code in MSIL language.
 Security Information — Information about the users / user types, who can

access the assembly.


 Manifest — Information about the assembly, such as identification, name,
version, and so on.
 Versioning — The version number of an assembly.
 Metadata — Information that describes the types and methods of the assembly.

.NET 4.0 and Visual Studio 2010 Page 24 of 548


Types of Ass emblies

 Private Assemblies: The private assemblies are simple types. An assembly that can
be used only within a software application is called as ―Private assembly‖. This type of
assemblies contains ―.exe‖ file extension.
 Shared Assemblies: An assembly that can be used by one or more software
applications is called as ―Shared Assemblies‖. This type of assemblies contains ―.dll‖
(dynamic linking library) file extension.

Example:
To get a better idea of a MSIL file and its content, take a look at the following
example, which has two console applications. One is written in C# and the other is written in
VB.NET.
The following C# code displays the “Hello, World” message in the
console window:
using System;
using System.Collections.Generic;
using System.Linq; using
System.Text; namespace
HelloWorldCS
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(―Hello, World!‖);
Console.ReadLine();
}
}
}

The following VB.NET code displays the “Hello, World” message in the
console window:

Module Module1
Sub Main()
Console.WriteLine(―Hello, World!‖)
Console.ReadLine()
End Sub
End Module

.NET 4.0 and Visual Studio 2010 Page 25 of 548


The Main method of the C# MSIL looks like this:

.method private hidebysig static void Main(string[] args) cil managed


{
.entrypoint
// Code size 19 (0x13)
.maxstack 8
IL_0000: nop
IL_0001: ldstr ―Hello, World!‖
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: call string [mscorlib]System.Console::ReadLine()
IL_0011: pop
IL_0012: ret
} // end of method Program::Main

The Main method of the VB.NET MSIL looks like this:

.method public static void Main() cil managed


{
.entrypoint
.custom instance void [mscorlib]System.STAThreadAttribute::.ctor() = ( 01 00
00 00 )
// Code size 20 (0x14)
.maxstack 8
IL_0000: nop
IL_0001: ldstr ―Hello, World!‖
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: call string [mscorlib]System.Console::ReadLine()
IL_0011: pop
IL_0012: nop
IL_0013: ret
} // end of method Module1::Main

Conclusion: The Main method of the VB.NET MSIL looks very similar to that of the C#.NET‘s
MSIL program.

The important thing to note here is that regardless of the language you use to develop your .NET
applications, all .NET applications are compiled to the MSIL bytecode as this example shows.

Note: MSIL can also be called as IL (Intermediate Language) and CIL (Common Intermediate
Language).

.NET 4.0 and Visual Studio 2010 Page 26 of 548


The RTE (Run Time Environment) of a .NET Application

Code in another .NET


Code in C#.NET Code in VB.NET
Language

C#.NET Compiler VB.NET Compiler


Another Compiler
(csc) (vbc)

Assembly (.exe)

MSIL Code

Common Language Run Time

Just-in Time
Compiler

Native Machine Code

01010101010111010
01010101010111010
01010101010111010
01010101010111010

Operating System

.NET 4.0 and Visual Studio 2010 Page 27 of 548


Components of CLR
The CLR contains the following components.

 Security Manager / Code safety verifier


 JIT Compiler
 Memory Manager
 Garbage Collector
 Exception Manager

1. Security Manager / Code Safety Verifier

 This is the initial and most component of CLR.


 Application security is much more important issues today.
 If you analyze this in-depth, we have 3 types of security support by .NET Framework.
A. Evidence Based Security (EBS):
 This security feature is meant for protecting entire assembly not to
be accessed by un-authorized users.
 The ―Security Manager‖ component first checks privileges of the
current user that the user is allowed to access the assembly or
not, based on the ―evidence‖.
 The evidence is nothing but the information about the security
permissions related to the assembly, that resides with in the
assembly.

B. Code Access Security (CAS):


 This verifies whether the current user is allowed to perform the
actions written in the MSIL code.
 For example, accessing the file system, event log, printing, remote
or network access etc.

.NET 4.0 and Visual Studio 2010 Page 28 of 548


2. JIT Compiler
 As you seen in the diagram of RTE previously, the ―JIT‖ compiler is responsible for
compiling the ―MSIL‖ code into the ―Native code‖.
 The native code is directly understandable by the system hardware.

3. Memory Manager
 The ―Memory Manager‖ component of CLR, allocates necessary memory for the
variables and objects that are to be used by the application.

4. Garbage Collector
 This component of CLR de-allocates or cleans-up the un-necessary memory of the
application, after usage automatically.
 Instead, in older languages such as C/C++ this kind of component is not available so
that the programmer should free-up the memory explicitly using some code.

5. Exception Manager
 An exception means ―Run time error‖.
 This component redirect the processor to execute the ―catch‖ block or ―finally‖ block,
whenever an exception is occurred at run time.
 We can learn how to write these catch and finally blocks in C#.NET and VB.NET
languages later.

.NET 4.0 and Visual Studio 2010 Page 29 of 548


Introducing Visual Studio

About Visual Studio:

 Visual Studio is nothing but the Visual IDE (Integrated Development


Environment), which is needed to development applications with .NET Framework.
 The IDE integrates three features:
 Editor
 Compiler (For compilation)
 Interpreter (For running the application)
 In simple, we can say like ―.NET Framework is something that is required to run the
.NET applications and which also offers the necessary library‖ and ―Visual Studio is
something that is required to develop the .NET applications‖.

Visual Studio Versions:


 There are several versions in Visual Studio like Visual Studio 2002, Visual Studio
2003, Visual Studio 2005, Visual Studio 2008, and Visual Studio 2010 (as shown in
the previous table).

Getting started with Visual Studio:


 To start with Visual Studio 2010, click ―Start‖ – ―Programs‖ – ―Microsoft Visual
Studio 2010‖ – ―Microsoft Visual Studio 2010‖.

.NET 4.0 and Visual Studio 2010 Page 30 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

.NET 4.0 and Visual Studio 2010 Page 31 of 548


 Then the screen appears like this:

.NET 4.0 and Visual Studio 2010 Page 32 of 548


 Finally, Visual Studio 2010 will be opened. The initial screens looks like this:

System Requirements of Visual Studio 2008

 Processor:
 Minimum: P-IV
 Recommended: Higher than P-IV
 RAM:
 Minimum: 512 MB
 Recommended: 1 GB (or above)
 OS:
 MS Windows
(XP / 2003 / Vista / 2008 / Windows 7)

.NET 4.0 and Visual Studio 2010 Page 33 of 548


 Hard disk free space:
 4.2 GB (on system drive ( C: ))
 Internet Connection (optional)
(To get latest news and updates from Microsoft‘s web site)

System Requirements of Visual Studio 2010

 Processor:
 Minimum: P-IV
 Recommended: Higher than P-IV
 RAM:
 Minimum: 512 MB
 Recommended: 1 GB (or above)
 OS:
 MS Windows
(XP Service Pack 3 / 2003 / Vista / 2008 / Windows 7)

 Hard disk free space:


 6.3 GB (on system drive ( C: ))

 Internet Connection (optional)


(To get latest news and updates from Microsoft‘s web site)

.NET 4.0 and Visual Studio 2010 Page 34 of 548


Getting Started with Visual Studio 2010

I) Opening Visual Studio 2010


 Click on ―Start‖ – ―Programs‖ – ―Microsoft Visual Studio 2010‖ – ―Microsoft Visual Studio
2010‖.
 The following screen will be opened.

 Initially, the ―Visual Studio 2010‖ will be opened along with ―Start Page‖.
 The start page is nothing but the welcome page, which contains
 Logo: A logo of ―Microsoft Visual Studio 2010‖ on the top of the start page.
 Recent Projects: List of most recently opened projects. If you click on any one,
the project will be opened immediately.
 Get started / Guidance and Resources / Latest News: Headlines of visual
studio help for .NET programmers. If you click on any one head line, online help
will be opened (if Internet connection is available).

.NET 4.0 and Visual Studio 2010 Page 35 of 548


II) The Visual Studio 2010 Basics
To start programming with Visual Studio, you should know some common terminology
that is used most frequently in Visual Studio.

 Project: An application developed in Visual Studio. That may be of different


types such as Console application, Windows application, Windows Service, Web
site etc.

 Solution: Collection of one or more projects. Initially, in a solution, one project


will be placed. Later, you can add other projects to it.

 Build: Compilation of entire .NET Project (all the files will be compiled at-a-
time).

 Class: A collection of data members and methods (member functions).


Ex:

class class1

int mydatamember;

void mymethod()

 Namespace: It‘s nothing but a collection of classes. It may also contain sub
namespaces. A project may require implementing at least one or more classes.
Any class can‘t be defined individually, without a namespace. In .NET, all of the
classes related one application should be defined with a user defined namespace.

.NET 4.0 and Visual Studio 2010 Page 36 of 548


Ex:

namespace MyApplication
{
class class1
{
}
class class2
{
}
}

III) Creating a new project


To create a new project in Visual Studio, follow the steps given below.

 Open Microsoft Visual Studio 2010.


 Click on ―File‖ – ―New‖ – ―Project‖.

.NET 4.0 and Visual Studio 2010 Page 37 of 548


 In the ―New Project‖ dialog box, the left side panel displays the list of .NET
languages like
 Visual C#
 Visual Basic
 Visual C++
etc.
The right side panel displays the list of project templates like
 Windows Forms Application
 Class Library
 ASP.NET Web Application
 ASP.NET Web Service Application
 WPF Application
 WPF Browser Application
 Console Application
 WCF Service Application
 Windows Forms Control Library

.NET 4.0 and Visual Studio 2010 Page 38 of 548


 Select the appropriate language and required project template. For example
select ―Visual C#‖ and ―Windows Forms Application‖.
 Provide the following details:
 Name: Specifies the name of the project.
Ex: WindowsFormsApplication1.
 Location: Specifies the path, in which the project is to be stored.
 Solution Name: The actual name of the solution. (By default the
solution will be created with one project, later you can add other
projects to this solution if needed).
 Click on ―OK‖ to confirm. Then the new project will be created.

In the above screen, you can see an empty form created automatically, named as ―Form1‖.

IV) Project Directory Structure


When we create a new project, some directory structure will be created automatically by
following the below specified rules.

.NET 4.0 and Visual Studio 2010 Page 39 of 548


 Each solution will be created as a folder.
 Each project will be created as a folder, and placed in the solution folder.
 All the files related to the project, will be placed in the project folder.
 The information about the solution members will be saved in a file called
―Solution‖ file and it will be placed in the solution folder. When we double click
on it, that solution will be opened in Visual Studio. The file extension of the
solution file is ―.sln‖.
 In the same way, the information about the project members will be saved in the
―Project‖ file and it will be placed in the project folder. When we double click on
it, that project will be opened in Visual Studio.

You can observe the project directory structure according to our previous example.
Note: First, recollect the project name, project location and solution name from previous
example.

Project Folder Solution File


Solution Folder:

.NET 4.0 and Visual Studio 2010 Page 40 of 548


Project Folder:

 bin: This folder contains the ―EXE‖ file after compiling the project.
 obj: This folder cntains the temporary files of the project, while compilation.
 Properties: This folder contains necessary files that contain information about the
settings and resources related to the project.
 WindowsFormsApplication1.csproj (Project File): This file contains the information
about all the files related to the project; When you double click on it, the project will be
opened in Visual Studio.
 Form1.cs: This file contains the executable code of ―Form1‖.
 Form1.Designer.cs: This file contains the code related to the design of Form1.
 Program.cs: This file contains the code of ―Program‖ class with Main() method.

.NET 4.0 and Visual Studio 2010 Page 41 of 548


Components of Visual Studio IDE
In this section, we make a closer look to the IDE offered by Visual Studio.

Menu Bar Tool Bars Tabs Form Designer Solution Explorer

Toolbox Properties window

1) Menu Bar: This bar contains the available menus in Visual Studio like ―File‖, ―Edit‖,
―View‖ and ―Project‖ etc.
2) Tool Bars: There are several toolbars in Visual Studio, which contain frequently used
options in Visual Studio.
3) Tabs: Displays tabs; just click to open required tab.
4) Form designer: Used to view and edit the visual design of the form.
5) Code Window: This is where you write actual programming of your application. You
can switch to this view, by right click on the ―form designer‖ and choosing ―View Code‖
(or) by pressing F7 key on the keyboard.

.NET 4.0 and Visual Studio 2010 Page 42 of 548


6) Solution Explorer: Explores the information about the solution and its members.
7) Properties: Displays the available properties and values for the selected solution,
project, form or control; and also allows changing the property values.
8) Other: In addition to the above specified IDE components, some other components are
also available docked at the bottom area of Visual Studio window like ―Output‖, ―Error
List‖, ―Command window‖, ―Immediate window‖, ―Breakpoints‖. We discuss about these
components whenever required, in upcoming chapters later.

V) Creating Console Applications


The console applications are the project types, recommended for the .NET programming
beginners, where you can learn the language features better.

 In Microsoft Visual Studio 2010, click on ―File‖ – ―New‖ – ―Project‖.


 Select the language as ―Visual C#‖ and select the project template as ―Console
Application‖.

.NET 4.0 and Visual Studio 2010 Page 43 of 548


 Then enter the project name and location (with your choice) and click on OK.

.NET 4.0 and Visual Studio 2010 Page 44 of 548


C#.NET
Overview
 It‘s a programming language, offered by .NET Framework.
 It is recommended for both .NET programming beginners and .NET professionals.
 This is the mostly used language used by most of the IT companies today.
 It derives some programming features from ―C‖ and ―C++‖ also.
 It is the object oriented programming language.
 It is the case sensitive language.
 The programmer, having knowledge in C and C++ can easily understand the
programming in C#.

File Extensions in C#
 Project File Extension: ―.csproj‖ (means C Sharp Project)
 Code File Extension: ―.cs‖ (means C Sharp)

Basic Terminology in C#
 Statement: It‘s a line in the program.
--------------;
 Keyword: It‘s a reserved word, which has some pre-defined meaning. Ex: void, class,
struct, using, while, do, for, if, else etc.
 Data type: It‘s a keyword, which specifies the type of the data that you are going to
store in a variable or constant. Ex: int, float, char, string etc.
 Variable: It‘s a named memory location, which contains a particular type value and
which value can be changed during the program execution.

data_type variable_name;

 Constant: It‘s a fixed value, which value can‘t be changed during the program
execution. Ex: 1, 10, ‗a‘, ―abcd‖.
 Operator: It‘s a symbol, which performs some operation. Ex: +, -, *, /, ++ etc.
 Condition: It‘s an expression, which can have a result (True / False).

.NET 4.0 and Visual Studio 2010 Page 45 of 548


(x == y)

 Array: It‘s a collection of multiple values, of same data type.


 Enumeration: It‘s a collection of multiple constants. For each constant, one integer
value will be associated automatically, starting from 0.
 Class: It‘s a collection of fields, properties and methods (member functions).

class <classname>
{
//fields
//properties
//methods
}

 Object: It‘s an instance to the class. The memory will be allocated for the object only,
not for the class. It is able to access the members of the class. An object can be created
as follows:

classname objname = new classname();

 Field / Data Member: It‘s a variable, declared inside of the class.


 Property: It‘s almost all similar to the filed. The additional feature of property is, it
executes some code automatically, whenever the value is changed.
 Method / Member Function: A function, defined inside of a class. It‘s a collection of
few statements. It can receive one or more arguments and can return a value.
 Argument / Parameter: A value that can be sent as an input value for the method.
 Return value: A value that is given back to the calling portion of the function, as a
result.
 Namespace: It‘s a collection of few classes. A namespace can also contain sub
namespaces.

Sample Application Development in C#


 Launch Visual Studio 2010.
 Create a new ―Console Application‖ with ―Visual C#‖ language.
 It generates an empty ―Program‖ class, with ―Main()‖ method.
 Type a simple program as follows:

.NET 4.0 and Visual Studio 2010 Page 46 of 548


Application 1: A simple C# program

 To run the application, simply press ―F5‖ key on the keyboard. Then the application will
be executed and output will be as follows.

.NET 4.0 and Visual Studio 2010 Page 47 of 548


A closer look at the syntax

Importing section Namespace Declaration Class Declaration

Main() method

1. Importing section:
 This section contains importing statements that are used to import (include or link) the
.NET Framework Class Library (FCL).
 This is most similar to the ―include‖ statements in ―C‖ language.
 Syn:
using namespace;
 Note: If the required namespace is a member of another namespace, we have specify
the parent and child namespaces separated with ―.‖ (dot).
 Ex:
using System;

.NET 4.0 and Visual Studio 2010 Page 48 of 548


using System.IO;
using System.Data;
etc.

2. Namespace declaration:
 Here, a user define namespace is to be declared.
 Rule: In .NET applications, all the classes related to the project should be declared in
one namespace.
Syn:
namespace namespacename
{

}
 Generally, the namespace name will be same as ―Project‖ name.

2. Class declaration:
 This is to declare the startup class of the project.
 In every .NET application (like Console and Windows Application), there should a startup
class. In these applications, the startup class name should be ―Program‖. You can‘t
change it.
 A startup class nothing but a class, which contains Main() method.
Syn:
class classname
{

3. Main() method:
 As you know already in C/C++ languages, the Main() method is the Starting Execution
Point of the application.
 When the application is executed, the Main() method will be executed first.
 This method contains the main logic of the application.

.NET 4.0 and Visual Studio 2010 Page 49 of 548


Syn:

Specifies that Main() is a static method; which


allows to directly call Main() method, without Means no return value
creating an instance of “Program” class.

Receives arguments sent


to the Main() method in a
string array format.

Features of Main() Method:


 void: It can‘t return any value unlike other methods. So that, it should be defined with
―void‖ keyword.
 static: In fact to access any class member, an object should be created. Object can be
created after starting the application only. But to start the application execution, ―Main()‖
method is to be called. So that, it should be accessed without creating any object for the
―Program‖ class. That‘s why you need to declare it as a ―static‖ method.
 string[] args: To receive the command like arguments. A command line argument is
nothing but an argument, which can be passed from the command window, before the
application execution is started.

Compiling and Running the application


 Compile:
Click on ―Build‖ menu – ―Build Solution‖. (or) Press Ctrl+Shift+B.
 Run:
Click on ―Debug‖ menu – ―Start Debugging‖. (or) Press F5.

.NET 4.0 and Visual Studio 2010 Page 50 of 548


I) Basic Programming Techniques in C#

1) Keywords
You can observe the available keywords in C#.

2) The “Console” class:


 To implement the UI in the console applications, Microsoft has provided a class called
―Console‖.
 Library: System.Console
 With the support of properties and
methods of ―Console‖ class, you can
implement the UI in console
applications.
 All the properties and methods of
―Console‖ class are static members.
So that you can access them,
without creating any object for that
class.

.NET 4.0 and Visual Studio 2010 Page 51 of 548


Properties of “Console” class
Property Description
Title Specifies the title of the console window.
BackgroundColor Specifies background color of the text.
ForegroundColor Specifies foreground color of the text.
CursorSize Specifies the height of the cursor in the console window. (1-100)

Methods of “Console” class


Method Description
Clear() Clears the screen.
Beep() Plays a beep sound using PC speaker at run time.
ResetColor() Resets the background and foreground colors to its default state.
Write(“string”) Displays the specified message on the console window.
WriteLine(“string”) Same as Write() method, but automatically moves the cursor to the next
line after printing the message.
Write(variable) Displays the value of the given variable.
WriteLine(variable) Displays the value of the given variable along with moving the cursor to
the next line.
Read() Reads a single character on the keyboard and returns its ASCII value.
ReadLine() Reads a string value from the keyboard and returns the entered value (in
string mode only).

.NET 4.0 and Visual Studio 2010 Page 52 of 548


3) Comments
 Single Line Comment:
//comment
 Multi Line Comment:
/* comment line 1
comment line 2
comment line 3
*/

Application 2: Demo on “Console” class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleClassDemo
{
/*Demo on Console Class*/
class Program
{
static void Main(string[] args)
{
//Output demo
System.Console.WriteLine(".NET Framework is:");
System.Console.Write("C#.NET+");
System.Console.Write("VB.NET+");
System.Console.WriteLine("ASP.NET");

//Input demo
string name;
System.Console.Write("\nEnter your name: ");
name = System.Console.ReadLine();

//clear the screen


System.Console.Clear();

//change the window title


System.Console.Title = "A System.Console class demo";

//play beep sound


System.Console.Beep();

.NET 4.0 and Visual Studio 2010 Page 53 of 548


//change the cursor size
System.Console.CursorSize = 60;

//background and foreground colors demo


System.Console.BackgroundColor = ConsoleColor.DarkRed;
System.Console.ForegroundColor = ConsoleColor.Yellow;
System.Console.WriteLine("Hello, " + name);

//reset the background and foreground colors


System.Console.ResetColor();
System.Console.WriteLine("Thank you, visit again!");

System.Console.Read();
}
}
}

Output:

After pressing Enter…

4) Skip writing the imported namespaces


 When you import any namespace, all of the classes of that namespace are implicitly
accessible in the code.
 For example, when we import ―System‖ namespace, all of the classes under ―System‖
namespace can be accessed without specifying ―System.‖.
 Ex:
When you import like:
using System;
To access ―Console‖ class:
System.Console is not required. Console is enough.

.NET 4.0 and Visual Studio 2010 Page 54 of 548


5) Data Types
 C# supports several types of predefined data types. You can observe them in the
following diagram.

You can observe the data types, memory size and ranges inthe following table.

Data Type Description Range Bytes


sbyte 8-bit signed integer -128 to 127 1
byte 8-bit unsigned integer 0 to 255 1
short 16-bit signed integer -32,768 to 32,767 2
ushort 16-bit unsigned integer 0 to 65,535 2
int 32-bit signed integer -2,147,483,648 to 2,147,483,647 4
uint 32-bit unsigned integer 0 to 4,294,967,295 4
-9,223,372,036,854,775,808 to
long 64-bit signed integer 8
9,223,372,036,854,775,807
ulong 64-bit unsigned integer 0 to 18,446,744,073,709,551,615 8
float Single-precision float 1.5×10-45 to 3.4×1038 4
double Double-precision float 5×10-324 to 1.7×10308 8
Decimal value with
decimal 28-significant-digit ±1.0×1028 to ±7.9×1028 16
precision
bool Boolean true, false 1
char Unicode character Any one character 2
No. of chars X 2
string Group of characters 2 billion characters
(Initially 0)
Based on the
object Any type of value ----
value

.NET 4.0 and Visual Studio 2010 Page 55 of 548


6) Variables
 Variable declaration:
Syn: datatype variable;
Ex: int x;
 Variable declaration along with initialization:
Syn: datatype variable=value;
Ex: int x=10;
 Multiple Variable declaration:
Syn: datatype variable1, variable2, variable3,…;
Ex: int x,y,z;

Note: When we declare any variable, it should be assigned to a value before its usage.
Otherwise, it causes a compile time error.

Note: ―+‖ is known as ―concatenation‖ operator, which can concatenate two similar or
different types of values as a ―string‖.

Application 3: Demo on Variables

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Variables
{
class Program
{
static void Main(string[] args)
{
int n = 4561;
Console.WriteLine(n);
decimal a, b, c;
double d1, d2=45.123, d3;
Console.WriteLine("d2 value is " + d2);
string s1;
bool b1 = true;
Console.WriteLine(b1);
string Country = "India";
int States = 28;
Console.WriteLine("Our country is " + Country + ". It has " + States + " states.");

.NET 4.0 and Visual Studio 2010 Page 56 of 548


Console.Read();
}
}
}

Output:

7) Escape Sequence Characters


Escape Sequence Description Actual Character
\’ Single quotation mark ‗
\” Double quotation mark ―
\\ Backslash \
\0 Null Null
\b Backspace Backspace
\n New line New line
\t Tab Tab space (8 spaces)

Application 4: Demo on Escape Sequence Characters

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EscapeSequenceCharacters
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("This is first line\nThis is second line\nThis is third line.");

.NET 4.0 and Visual Studio 2010 Page 57 of 548


Console.WriteLine("\'C#\' has derived from \"C\" and \"C++\".");
Console.WriteLine("The escape sequence character \\n is used to insert new line.");
Console.WriteLine("One\tTwo\tThree");
Console.WriteLine("An\bt");
Console.Read();
}
}
}

Output:

8) Constants
 Constants look just like variables, but concept wise, they differ from variables.
 The main differences between constants and variables are:
 The value of constants can‘t be changed during the program execution time.
 The constants should be initialized at the time of its declaration.
 To declare constants,
Syn: const datatype constantname = value;
Ex: const int x=100;

Application 5: Demo on Constants

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Constants
{
//An application, that calculates area of circle
class Program
{

.NET 4.0 and Visual Studio 2010 Page 58 of 548


static void Main(string[] args)
{
const double PI = 3.14;
Console.WriteLine("Enter r value:");
int r = Convert.ToInt32(Console.ReadLine());
double area = PI * r * r;
Console.WriteLine("Area of circle is " + area);
Console.Read();
}
}
}

Output:

.NET 4.0 and Visual Studio 2010 Page 59 of 548


9) Type casting
Def: The process of converting the value from one data type to another data type is
called as ―Casting‖.
This is of two types.
1. Implicit Casting:
The value can be converted by the compiler automatically, without using any
extra statement.
2. Explicit Casting:
The value can be converted by the programmer using a conversion method.

Implicit Casting
Implicit casting is possible in the following cases.

 Any numerical value from lower to higher type.


Ex: byte to short
short to int
float to double
etc.
 Any numerical value from non-decimal type to decimal type.
Ex: int to float
long to double
etc.
The following table shows the all possible implicit conversions supported by C#.

.NET 4.0 and Visual Studio 2010 Page 60 of 548


Implicit Casting in C#:

Explicit Casting
Explicit casting should be performed in the following cases:

 Any numerical value from higher type to lower type.


 Any numerical value from decimal type to non-decimal type.
 Any value from numerical type to non-numerical type.
 Any value from non-numerical type to numerical type.
Syn: (target data type)variable

(target data type)value

Application 6: Demo on Casting

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Casting
{
class Program
{
static void Main(string[] args)
{

.NET 4.0 and Visual Studio 2010 Page 61 of 548


int x = 10;
long y = x; //implicit
byte z = (byte)x; //explicit
double p = x; //implicit
int q = (int)p; //explicit
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(z);
Console.WriteLine(p);
Console.WriteLine(q);
Console.Read();
}
}
}

Output:

Explicit Casting using Conversion Methods


Explicit casting can also be performed by using the ―Conversion methods‖. The ―System.Convert‖
class provides several methods to perform explicit casting.

 System.Convert.ToSByte(value);
Converts the value into ―sbyte‖ type.

 System.Convert.ToByte(value);
Converts the value into ―byte‖ type.

 System.Convert.ToInt16(value);
Converts the value into ―short‖ type.

 System.Convert.ToUInt16(value);
Converts the value into ―ushort‖ type.

 System.Convert.ToInt32(value);
Converts the value into ―int‖ type.

.NET 4.0 and Visual Studio 2010 Page 62 of 548


 System.Convert.ToUInt32(value);
Converts the value into ―uint‖ type.

 System.Convert.ToInt64(value);
Converts the value into ―long‖ type.

 System.Convert.ToUInt64(value);
Converts the value into ―ulong‖ type.

 System.Convert.ToSingle(value);
Converts the value into ―float‖ type.

 System.Convert.ToDouble(value);
Converts the value into ―double‖ type.

 System.Convert.ToDecimal(value);
Converts the value into ―decimal‖ type.

 System.Convert.ToChar(value);
Converts the value into ―char‖ type.

 System.Convert.ToString(value);
Converts the value into ―string‖ type.

 System.Convert.ToBoolean(value);
Converts the value into ―bool‖ type.

Application 7: Demo on Casting with Conversion Methods

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConversionMethods
{
class Program
{
static void Main(string[] args)
{

.NET 4.0 and Visual Studio 2010 Page 63 of 548


int x = 10;
long y = x; //implicit
byte z = Convert.ToByte(x); //explicit
double p = x; //implicit
int q = Convert.ToInt32(p); //explicit
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(z);
Console.WriteLine(p);
Console.WriteLine(q);
char c = 'A';
string s = Convert.ToString(c); //explicit
Console.WriteLine(s);
Console.Read();
}
}
}

Output:

IMP Note:
 By default, C# recognizes all the integer constants as the type of ―int‖.
 In the same way, C# recognizes all the floating point constants as the type of
―double‖.
 There is no ―ToObject()‖ method to convert a value into ―object‖ data type.

10) Boxing and Unboxing

 Boxing: Converting a variable value into ―Object‖ type value implicitly.


 Unboxing: Converting the ―Object‖ type value into variable explicitly (using
conversion methods).

Application 8: Demo on Boxing and Unboxing

.NET 4.0 and Visual Studio 2010 Page 64 of 548


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BoxingAndUnboxingDemo
{
class Program
{
static void Main(string[] args)
{
int x = 10;

//boxing
Object obj;
obj = x;
Console.WriteLine(obj);

//un-boxing
x = Convert.ToInt32(obj);
Console.WriteLine(x);

Console.Read();
}
}
}

Output:

11) Variable Scopes


 A ―variable scope‖ simply is something, which decides the lifetime of the variable.
 The variable scope depends on the place, where the variable is declared in the program.
 For example, a variable is declared in ―if‖ block, is available only within the ―if‖ block
itself.
 To have a better idea on this, we discuss about all available scopes in C#.

.NET 4.0 and Visual Studio 2010 Page 65 of 548


Scope Description Accessibility Example
This is known as data
class sample
member, which accessibility is
1) Class level A variable declared {
based on the access modifier
scope within the class. private int x;
you use. (like private, public
}
etc.)
void sample()
{
2) Method A variable declared Accessible only within the
int x;
level scope within the method method only.
//some code
}
A variable declared
within a block. Ex: if
if (x==y)
block, else block, for
{
3) Block block, try block, catch Accessible only within the
int x;
level scope block etc. block only.
//some code
Note: A block can be
}
specified when you use
curly braces. { }

 Strong Rule to follow: Multiple variables with same name within the same scope
can‘t be declared anywhere.

12) Operators
C# supports different kinds of operators.

 Assignment operator
=
 Arithmetical / Mathematical operators
+, -, *, /, %

 Self Assignment operators


+=, -=, *=, /=
 Prefix and Postfix operators
++, --

 Relational operators
==, !=, <, >, <=, >=

.NET 4.0 and Visual Studio 2010 Page 66 of 548


 Logical operators
&&, ||, !

 Comment operators
//xxxxxxxxxxxxxx

(or)

/* xxxxxxxxxxx
xxxxxxxxxxx
xxxxxxxxxxx*/

 Concatenation Operator
+

 Block specification operators


{}

 Method specification operators


()

 Conditional operator
?:

 Dynamic memory allocation operator


new

.NET 4.0 and Visual Studio 2010 Page 67 of 548


Operator Precedence:

13) Flow Control with Control Statements


 C# supports several types control statements.
 These are almost all similar to C.

Types of Control Statements


 Branching Control Statements
 if
 switch-case
 break
 continue
 goto
 Looping Control Statements
 while
 do-while
 for

.NET 4.0 and Visual Studio 2010 Page 68 of 548


Note: All the syntaxes are same as C/C++. Just for idea, we recollect the syntaxes now.

Implementation Syntax of Control Statements


 Branching Control Statements
 if
 Simple if
if (condition)
{
----;
----;
}

 if-else
if (condition)
{
----;
----;
}
else
{
----;
----;
}

 else-if
if (condition)
{
----;
----;
}
else if (condition)
{
----;
----;
}
else if (condition)
{
----;
----;
}
else
{
----;
----;
}

.NET 4.0 and Visual Studio 2010 Page 69 of 548


 Nested-if
if (condition)
{
if (condition)
{
----;
----;
}
else
{
----;
----;
}
}
else
{
if (condition)
{
----;
----;
}
else
{
----;
----;
}
}

 switch-case
switch (variable)
{
case value1: ---------; break;
case value2: ---------; break;
case value3: ---------; break;
case value4: ---------; break;
default: ---------; break;
}

 break
for loop / while loop / do-while loop
{
----------;
----------;
break;
----------;
}

.NET 4.0 and Visual Studio 2010 Page 70 of 548


 continue
for loop / while loop / do-while loop
{
----------;
----------;
continue;
----------;
}

 goto
----------;
----------;
----------;
goto labelname;
----------;
----------;
labelname:
----------;
----------;
----------;

 Looping Control Statements


 while
initialization;
while (condition)
{
----------;
----------;
----------;
Increment / decrement;
}

 do-while
initialization;
do
{
----------;
----------;
----------;
Increment / decrement;
} while(condition);

.NET 4.0 and Visual Studio 2010 Page 71 of 548


 for
for (initialization; condition; increment/decrement)
{
----------;
----------;
----------;
}

Note: You can also implement nested loops as you implemented in C/C++.

14) Enumerations
 An enumeration is a collection of constants. That means you can create your own set of
named constants by using enumerations.
 Each constant will have a name with an integer value.
 Syntax for Enumeration Declaration:
public enum enumname
{
Constant1 = value1, Constant2 = value2, Constant3 = value3
}
 Syntax for usage
enumname.constantname

Application 9: Enumeration Demo

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EnumerationDemo
{
public enum Months
{
January = 1, February = 2, March = 3, April = 4, May = 5, June = 6, July = 7,
August = 8, September = 9, October = 10, November = 11, December = 12
}
class Program
{

.NET 4.0 and Visual Studio 2010 Page 72 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

static void Main(string[] args)


{
Console.WriteLine(Months.March);
Console.WriteLine((int)Months.March);
Console.Read();
}
}
}

Output:

.NET 4.0 and Visual Studio 2010 Page 73 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

15) Arrays
 An array is the collection of similar type of values.
 Each value in the array is to be called as an element.
 The total no. of array elements is called as ―Array size‖.

Implementation of Arrays:
 Single Dimensional Arrays:
 Array declaration:
Single-dim
 Without initialization:
array
datatype[] arrayname = new datatype[size];

 With initialization:
datatype[] arrayname = {val1,val2,val3,…..};

 Accessing the elements:


arrayname[index]

 Double Dimensional Arrays:


 Array declaration:
 Without initialization:
datatype[,] arrayname = new datatype[rows size,columns size];

 With initialization:
datatype[,] arrayname = {{val1,val2,…}, {val1,val2,…},…};

 Accessing the elements:


arrayname[row index,column index] Double-dim
array

.NET 4.0 and Visual Studio 2010 Page 74 of 548


 Multi Dimensional Arrays:
Same as ―Double‖ dimensional arrays, but increase the no. of
dimensions.

Application 10: Demo on Single Dim Arrays

namespace ArrayDemo
{
//Demo on Single-Dim Array.
class Program
{
static void Main(string[] args)
{
//read the no. of students
int n;
Console.Write("Enter no. of students: ");
n = Convert.ToInt32(Console.ReadLine());

//check n value whether it is greater than 0 or not.


if (n > 0)
{
//declare the arrays
string[] Names = new string[n];
int[] Marks = new int[n];
string[] Result = new string[n];

//read student names


Console.WriteLine("\nEnter " + n + " students names:");
for (int i = 0; i < n; i++)
{
Console.Write((i + 1) + ": ");
Names[i] = Console.ReadLine();
}

//read student marks


Console.WriteLine("\nEnter " + n + " students marks:");
for (int i = 0; i < n; i++)
{
Console.Write((i + 1) + ": ");
Marks[i] = Convert.ToInt32(Console.ReadLine());
}

//calculate results
for (int i = 0; i < n; i++)
{

.NET 4.0 and Visual Studio 2010 Page 75 of 548


if (Marks[i] >= 0 && Marks[i] <= 100)
{
if (Marks[i] >= 80)
Result[i] = "Distinction";
else if (Marks[i] >= 60)
Result[i] = "First Class";
else if (Marks[i] >= 50)
Result[i] = "Second Class";
else if (Marks[i] >= 35)
Result[i] = "Third Class";
else
Result[i] = "Fail";
}
else
Result[i] = "Invalid";
}

//display the student names and marks


Console.WriteLine("\n\nStudent Details:");
for (int i = 0; i < n; i++)
Console.WriteLine((i + 1) + ". " + Names[i] + " - " + Marks[i] + " - " + Result[i]);
}
else
Console.WriteLine("N value can't be zero.");
Console.Read();
}
}
}

Output:

.NET 4.0 and Visual Studio 2010 Page 76 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

Application 11: Demo on Multi Dim Arrays

namespace MultiDimArrays
{
//Demo on Multi-Dimensional Arrays
class Program
{
static void Main(string[] args)
{
//Single dimensional arrays int[] x = { 10, 20,
30, 40}; Console.WriteLine("Single dimensional
array:"); for (int i = 0; i < x.Length; i++)
Console.Write(x[i] + ", ");
//Double dimensional arrays
int[,] y = { {10, 20}, {30, 40}, {50, 60} };
Console.WriteLine("\n\nDouble dimensional array:");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
Console.Write(y[i, j] + " ");
Console.WriteLine();
}
//Multi dimensional arrays
int[, ,] z = { { { 5, 10 }, { 15, 20 } }, { { 25, 30 }, { 35, 40 } }, { { 45, 50 }, { 55, 60 } } };
Console.WriteLine("\nMulti dimensional array:");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 2; k++)
Console.Write(z[i, j, k] + " ");
Console.WriteLine();
}
Console.WriteLine();
}
Console.Read();
}
}
}

.NET 4.0 and Visual Studio 2010 Page 77 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

Output:

“foreach” Loop
 One of the most common usages of the ―for‖ loop is to iterate through a collection of
values (array).
 C# offers a simplified and easier syntax of for loop called ―foreach loop‖, designed only
for such kind of array iterations.
 Syntax:
foreach (datatype variable in arrayname)
{
-----------;
-----------;
}
 In the above syntax, the loop will be executed once for each value in the array. For
every iteration, the values of the array will be assigned to the variable.
 For example, you take the following for loop.
int[] nums = { 10, 20, 30};
for (int i = 0;i < nums.Length; i++)
{
Console.WriteLine(nums[i]));
}
 You can re-write the above example with ―foreach‖ syntax as follows:
int[] nums = { 10, 20, 30};
foreach (int n in nums)
{
Console.WriteLine(n);
}

.NET 4.0 and Visual Studio 2010 Page 78 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

Note: The ―arrayname.Length‖ property gets the size of the array. We discuss about the ―Array‖
class in future.

Jagged Arrays

 A two-dimensional array is of rectangular size always.


 But the jagged arrays are more flexible in sizing them.
 They may not be rectangular size.
 To declare them, declare the array size in one brackets [size] and then give empty
brackets, because different no. of elements can be stored in each row.

Application 12: Demo on Jagged Arrays

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JaggedArraysDemo
{
class Program
{
static void Main(string[] args)
{
int[][] a = new int[3][];
a[0] = new int[] { 1, 2 };
a[1] = new int[] { 3, 4, 5, 6, 7, 8 };
a[2] = new int[] { 9, 10, 11 };

.NET 4.0 and Visual Studio 2010 Page 79 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

for (int i = 0; i < a.Length; i++)


{
for (int j = 0; j < a[i].Length; j++)
{
Console.Write(a[i][j] + " ");
}
Console.WriteLine();
}

Console.Read();
}
}
}

Output:

16) Executing .NET Applications from Command Window:


 Sometimes, you may require running the .NET applications from Command window
(MS-DOS window).
 At that time, follow the below steps:
 Click on ―Start‖ – ―Run‖.
 Type ―cmd‖.
 Press Enter.
 A MS-DOS prompt window will be opened.

.NET 4.0 and Visual Studio 2010 Page 80 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

 Now, locate the ―bin‖ folder of the required application, by using the following
commands. For example, let us imagine that there is a project named
―ConsoleApplication1‖ in ―D:‖ drive.

 Now, you got the output as


Welcome to C# Console Programming…

17) Passing Arguments to Main() Method


 All of the previous examples in the material have been given without any arguments
to the Main() method.
 However, when the program is invoked, you can pass some arguments to the Main()
method, if required.
 C#‘s Main() method receives those arguments in string array format, traditionally
called as ―args‖ (of course, C# allows you change the name also).

Syn: Main(string[] args)

 Those arguments could be called as ―Command line arguments‖.


 You can use these command line arguments for the internal logic in the application.

Application 13: Demo on Main() method arguments

For example, Let us create this application on “D:”

.NET 4.0 and Visual Studio 2010 Page 81 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ArgsDemo
{
class Program
{
static void Main(string[] args)
{
if (args.Length > 0)
{
Console.WriteLine(args.Length + " arguments found. Those are:");
for (int i = 0; i < args.Length; i++)
Console.WriteLine(args[i]);
}
else
Console.WriteLine("No arguments found...");
Console.Read();
}
}
}

Output:

.NET 4.0 and Visual Studio 2010 Page 82 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

18) Multiple Main() Methods


 As you know already, Main() method is nothing but the entry point of the application.
 Most commonly, a .NET application contains only one Main() method.
 If needed, you are supposed to define multiple Main() methods also.
 But, at run time, only one Main() method can be specified as ―Entry Point‖. This
specification can be changed using the project properties.
 To understand better, we start with an example on this.

Application 14: Demo on Multiple Main() Methods

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MultipleMainMethods
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("This is the Main() method in Program class.");
Console.Read();
}
}
class MySample
{
static void Main(string[] args)
{
Console.WriteLine("This is the Main() method in MySample class.");
Console.Read();
}
}
}

.NET 4.0 and Visual Studio 2010 Page 83 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

 When this program is compiled, the compiler shows 2 compile time errors.

 It‘s because, two Main() methods are found in MySample class and Program class;
So that the compiler can‘t understand which Main() method is to be used as exact
entry point.
 To specify the required entry point, we have to change ―Startup Object‖ option in the
project properties.
 To open the project properties, click on ―Project‖ menu – ―Properties‖.
 Then the project properties will be opened. Now, observe the ―Startup Object‖ option.
 The ―Startup Object‖ option contains two options.
 (Not Set)
 MultipleMainMethods.Program
(―MultipleMainMethods‖ is the project name).
 Whenever it is set to “(Not Set)”, C# compiler automatically detects the Main()
method, where it is exists. This is the default value in the ―Startup object‖ option. But
this fails whenever multiple Main() methods are defined.
 Now you have to select the required class that contains the desired Main() method as
entry point.

.NET 4.0 and Visual Studio 2010 Page 84 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

 Finally close the properties tab and come to ―Program.cs‖ tab.


 Now run the application.
 Then you can get the output from the desired Main() method.

.NET 4.0 and Visual Studio 2010 Page 85 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

II) Object Oriented Programming Features of C#

II.a) An introduction to Object Oriented Programming:

 Types of Programming Languages:


 Structure Oriented Programming Language:
 The programming implementation flow depends on ―structures‖. That
means you need to create the structures for each data entity. Those
structure members can be created in the individual functions.
 Ex: Pascal, C, C++ etc.

 Object Oriented Programming Languages:


 The programming implementation flow depends on ―classes‖. In the
Main() method, you need to create the instances for the classes and
access those methods. These instances are called ―Objects‖.
 Ex: C++, VC++, Java and all .NET languages.
 The ―OOP‖ is a new type of programming style, introduced in 1980‘s.

 Basic Terminology in OOP Languages:


 Class:
 A class describes about the logical structure of an object.
 That means it describes about the data to be stored in the in an object
and also some operations, that are to be performed on that data.
 No memory will be allocated for the class.
 In other words, a class is used to classify the objects.
 Syn:
class classname
{
//fields
//properties
//methods
}

.NET 4.0 and Visual Studio 2010 Page 86 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

 Field / Data Member:


 A variable, declared inside of the class is called as ―field‖ / ―data
member‖.
 The fields are used to store the data values.

 Property:
 It‘s an extension to the field, which automatically performs the specified
code, whenever its value is changed.

 Method / Member function:


 It‘s also called as operation / member function.
 A method is nothing but a function, which is defined inside of the class.
 It is used to perform some process on the data members.

 Object:
 It‘s an instance of the class.
 It‘s required because, no memory will be allocated for the class, so that
you can‘t store any data and you can‘t call any operation.
 It is similar to ―structure variables‖, which is declared for the ―structure‖.
 The actual memory will be allocated for the object, which includes with
all the data members.
 The object can access the members that are defined in the class.

class employee

employee id Object1
name
phone
address
salary Object2
tax
net_salary

getdetails()
displaydetails()
Object3
calculate_net_salary()

.NET 4.0 and Visual Studio 2010 Page 87 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

 By default, the objects are isolated. That means there is no any relation
between the data stored in one object and another object.

Object1 Object2

employee id = 101 employee id = 102


name = abc name = xyz
phone = 9934839328 phone = 9834832821
address = hyd address = pune
salary = 9390 salary = 7800
tax = 782 tax = 450
net_salary = 8608 net_salary = 7350

Object3

employee id = 103
name = pqr
phone = 7839403200
address = chennai
salary = 10380
tax = 1270
net_salary = 9110

C++ (vs) C#

 In C++, the class definition syntax should end with ; whereas in C#, it‘s not required.
 In C++, we have private section, public section and protected section separately. But in
C#, there no such kind of sections and the access modifier should be specified for each
member of the class.
 In C++, it is not possible to initialize the data members in the class definition. But
whereas in C#, it is possible.
 In C++, there is provision to declare the member functions inside the class and then
write the definitions of those member functions outside of the class. But in C#, there is
no such kind of provision. The methods should be defined inside of the class definition
only.
 In C++, 3 access modifiers (private, protected and public) only supported. But in C#, 5
access modifiers are supported (private, protected, public, internal, protected internal).

.NET 4.0 and Visual Studio 2010 Page 88 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

II.b) Principles of Object Oriented Programming:

1) Data Encapsulation / Data Binding

2) Data Abstraction

3) Data Hiding / Security

4) Polymorphism

5) Inheritance

1) Data Encapsulation / Data Binding:

 This is the default nature of a class.


 A class encapsulates (combines) some data values (fields or properties) and
some operations (methods) related to the data as a pack.
 This nature can be called as ―Data Encapsulation‖.

2) Data Abstraction:

 The nature of ―instance‖ creation is called as ―Data Abstraction‖.


 This feature is taken from ―structures‖ in ―C‖ languages. (In ‗C‘ language you can
create any no. of structure variables based on one structure. The structure
variables act as instances for the structure).
 In the same way, you can create any no. of instances (objects) for a class.

3) Data Hiding / Security:

 This feature is not available in ―C‖ language; introduced in OOP.


 By default, all the members of the class will be hidden. So that, those are not
accessible from the object (generally the objects will be created outside of the
class).
 Of course, if you want to permit the object to access the class members from
outside of the class, you can give permission.
 These permissions can be given using the ―access modifiers‖.

.NET 4.0 and Visual Studio 2010 Page 89 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

Access Modifiers:

1. private: The private members are accessible within the self


class only; not accessible in outside of the class.

2. protected: This is similar to ―private‖. The protected members


are accessible within the self class and also in respective derived
classes. This is useful in inheritance.

3. public: The public members are accessible any where. This


offers un-limited accessibility.

4. internal: This is similar to ―public‖. The internal members are


accessible any where within the current project.

5. protected internal: This is similar to ―internal‖. These


members are accessible in the current project and also in the
classes of other projects, which are derived from the current
working class.

In the same In derived In other In derived In other


Access Modifier
class classes classes classes classes
private  X X X X
protected   X X X
public     
internal    X X
protected internal     X
In the same project In other projects

Note: X = Not Accessible

 = Accessible

Rule to follow: According to the nature of data hiding, it recommends us to define the fields as
―private members‖ and methods as ―public members‖.

So that finally the object can perform only the allowed operations (defined by the methods);
can‘t perform other operations.

.NET 4.0 and Visual Studio 2010 Page 90 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

4) Polymorphism:

 The decision making capacity of the compiler is called ―Polymorphism‖.


 It is of two types:
1) Compile-time Polymorphism:
 The decision can be made at the time of compilation.
 This can be implemented with two concepts:
i) Method Overloading: You can write multiple
methods with same name within the same class.
ii) Operator Overloading: You can write multiple
definitions for the same operator.

2) Run-time Polymorphism:
 The decision can be made at run time.
 This can be implemented with two concepts:
i) Templates / Generics: You can pass any type of
value as an argument to a method.
ii) Interfaces: Contains method declarations only,
doesn‘t contain method definitions.

5) Inheritance:

 The process of creating a new class that derives all the features of another
existing class is called as ―Inheritance‖.
 In other words, we can extend the features of a class.

Super class / Base class

Inherit

Sub class / Derived class

.NET 4.0 and Visual Studio 2010 Page 91 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

II.c) OOP Development


i) Class Definition Syntax:

class classname
{
//fields
//properties
//methods
}

ii) Fields Declaration Syntax:

accessmodifier functionalModifier datatype variablename;


(or)
accessmodifier functionalModifier datatype variablename = value;

Note 1: We cover about ―Properties‖ syntax in further hours.

Note 2: The functional modifiers are static, readonly, virtual, override. We cover about these
modifiers also in further hours.

iii) Methods (Member Functions) Declaration Syntax:

accessmodifier functionalModifier returntype/void methodname(args)


{
//method body
}

iv) Object (Instance) Construction Syntax:

//object reference creation


classname objname;

//memory allocation
objname = new classname();

(or)

.NET 4.0 and Visual Studio 2010 Page 92 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

//object creation along with memory allocation


classname objname = new classname();

v) Accessing Object Members:

obj.field

obj.property

obj.method()

Application 15: OOP Demo

namespace OOPDemo
{
class test
{
//fields
public string str = "windows";
public int num = 90251;

//methods
public void ReverseString()
{
string r = "";
int i;
int len = str.Length;
for (i = len - 1; i >= 0; i--)
r = r + str[i];
Console.WriteLine("Reversed string is: " + r);
}

public void ReverseNumber()


{
string s = num.ToString();
string r = "";
int i;
int len = s.Length;
for (i = len - 1; i >= 0; i--)
r = r + s[i];
Console.WriteLine("Reversed string is: " + r);
}
}
class Program
{

.NET 4.0 and Visual Studio 2010 Page 93 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

static void Main(string[] args)


{
//construct an object
test t = new test();

//access fields
Console.WriteLine(t.num);
Console.WriteLine(t.str);

//access methods
t.ReverseString();
t.ReverseNumber();

Console.Read();
}
}
}

Output:

Application 16: Data Hiding Demo

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DataHidingDemo
{
class MyMath
{
//private fields
private int x, y;

//public methods
public void SetValues(int FirstVal, int SecondVal)
{
x = FirstVal;
y = SecondVal;
}

.NET 4.0 and Visual Studio 2010 Page 94 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

public void Addition()


{
int sum = x + y;
Console.WriteLine("Sum is " + sum);
}

public void Subtraction()


{
int diff = x - y;
Console.WriteLine("Difference is " + diff);
}

public void Multiplication()


{
int prod = x * y;
Console.WriteLine("Product is: " + prod);
}
public void Division()
{
int div = x / y;
Console.WriteLine("Division is: " + div);
}
}
class Program
{
static void Main(string[] args)
{
MyMath mm = new MyMath();

mm.SetValues(10, 3);

mm.Addition();
mm.Subtraction();
mm.Multiplication();
mm.Division();

Console.Read();
}
}
}

Output:

.NET 4.0 and Visual Studio 2010 Page 95 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

ReadOnly Fields
 The ―ReadOnly‖ members are just like constants according to the objects.
 The ―readonly‖ modifier can be used for fields only.
 Once you initialize the value of ―ReadOnly data members‖, the object can‘t change that
value, but it can access the value.
 Note: The read only field‘s values can be changed inside of the class only.
 To declare the read only fields:
Syntax: access_specifier readonly data_type variable_name = value;

Application 17: Demo on ReadOnly fields

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ReadOnlyDataMembersDemo
{
class Sample
{
//read only data member
public readonly string CompanyName = "Wipro";
}
class Program
{
static void Main(string[] args)
{
Sample s = new Sample();
Console.WriteLine(s.CompanyName);
//s.CompanyName = "TCS"; // is not allowed bcoz it is the readonly member.
Console.Read();
}
}
}

Output:

.NET 4.0 and Visual Studio 2010 Page 96 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

“Ref” Parameters
 The reference parameters are similar to the normal parameters.
 The only difference between the normal parameters and reference parameters is: When
the value is changed in the reference parameter, would automatically affect
the actual parameter in the calling portion.
 Implementation: Use ―ref‖ keyword in calling portion and also in method definition.
 Rule: The actual parameter at the calling portion should be a variable and can‘t be a
constant.
 This is just like ―Call by reference‖ concept in C/C++.

Application 18: Ref Parameters Demo

namespace RefParameterDemo
{
class SampleClass
{
public void FirstMethod(int x, int y)
{
x++;
y++;
}
public void SecondMethod(int x, ref int y)
{
x++;
y++;
}
}
class Program
{
static void Main(string[] args)
{
int a = 10, b = 20;
SampleClass sc = new SampleClass();
Console.WriteLine(a + ", " + b);
sc.FirstMethod(a, b);
Console.WriteLine(a + ", " + b);
sc.SecondMethod(a, ref b);
Console.WriteLine(a + ", " + b);
Console.Read();
}
}
}

.NET 4.0 and Visual Studio 2010 Page 97 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

Output:

“Out” Parameters

 This is to return multiple values from a method.


 The ―out‖ parameter is similar to ―ref‖ parameter; but the difference between these two
parameters is, ―out‖ parameter does not carries any value from calling portion to the
method definition; but it carries the return value to the calling portion.
 Implementation: Use ―out‖ keyword in calling portion and also in method definition.
 So, the ―out‖ may not be initialized, when you call the method.

Application 19: “Out” Parameters Demo

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OutParametersDemo
{
class Test
{
public string GetBigAndSmall(string s1, string s2, out string small)
{
string big;
if (s1.Length > s2.Length)
big = s1;
else
big = s2;

if (s1.Length < s2.Length)


small = s1;
else
small = s2;

return (big);
}
}

.NET 4.0 and Visual Studio 2010 Page 98 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

class Program
{
static void Main(string[] args)
{
Test t = new Test();
string s1 = "dotnet";
string s2 = "framework";
string small; //no need of initialization
string big;
big = t.GetBigAndSmall(s1, s2, out small);
Console.WriteLine("Small string: " + small);
Console.WriteLine("Big string: " + big);
Console.Read();
}
}
}

Output:

“this” Keyword
 This is similar to ―this pointer‖ in C++.
 It represents current working object.
 It is used to access the members of current working object.
this.field
this.property
this.method()
 Current object: The object, with which object, the method is called.
 “this” keyword can‘t be used in the static methods, because static methods doesn‘t have
current object.

Application 20: “this” Keyword Demo

.NET 4.0 and Visual Studio 2010 Page 99 of 548


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ThisKeywordDemo
{
class Sample
{
//fields
public int n = 100;

//methods
public void Increment()
{
int n = 10; //incrementation value
this.n = this.n + n;
}
}
class Program
{
static void Main(string[] args)
{
Sample s = new Sample();
Console.WriteLine(s.n);
s.Increment();
Console.WriteLine(s.n);
Console.Read();
}
}
}

Output:

Named Parameters
 This feature is introduced in C#.NET 4.0.
 This is used to pass the arguments to the method, with those names.

Application 21: Named Parameters Demo

Page 100 of 553


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NamedParametersDemo
{
class User
{
//fields
public string FirstName;
public string LastName;

//methods
public void SetUserName(string FirstName, string LastName)
{
this.FirstName = FirstName;
this.LastName = LastName;
}

public void ShowUserName()


{
Console.WriteLine(FirstName + " " + LastName);
}
}
class Program
{
static void Main(string[] args)
{
User u = new User();

u.SetUserName(LastName: "Kumar", FirstName: "Raj"); //call a method, with


named parameters
u.ShowUserName();

Console.Read();
}
}
}

Output:

Page 101 of 553


Static Members
Types of Class Members:
1. Non-static Members:
 This is the default type for all the members.
 If you are not using ―static‖ keyword while the declaration of a field / property or
a method, then it can be called as ―Non-static member‖.
 The main feature of non-static member is - it will be bounded with the object
only.
 Non-static Fields / Properties: The memory will be allocated, when
an object is created.
 Non-static Methods: These methods can implement operations on
non-static fields and properties.

2. Static Members:
 If you are using ―static‖ keyword while the declaration of a field / property or a
method, then it can be called as ―Static member‖.
 The main feature of non-static member is - it will not be bounded with the any
object. It is individually accessible with the class name. In other words, the static
members are accessible directly, without even creating one object also.

 Static Fields / Properties: The memory will be allocated individually,


without any relation with the object.
 Static Methods: These methods can implement operations on static
fields and properties only; and can‘t access the non-static members.

Page 102 of 553


Object1
p
q
Sample
class sample r
{ s
int p; Object2
double q; static p
int r; static q
double s;
}
Object3
p
q

Application 22: Demo on static members

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StaticMembersDemo
{
class Student
{
//non-static data members
public string StudentName;
public string Course;

//non-static methods
public void SetStudentDetails(string StuName, string Cou)
{
StudentName = StuName;
Course = Cou;
}

public void DisplayStudentDetails()


{
Console.WriteLine(StudentName + " - " + Course);
}

Page 103 of 553


//static data members
public static string CollegeName = "ABC College of Technology";
public static string CollegeAddress = "Hyderabad";

//static methods
public static void DisplayCollegeDetails()
{
Console.WriteLine(CollegeName);
Console.WriteLine(CollegeAddress);
}

}
class Program
{
static void Main(string[] args)
{
//access static members
Student.DisplayCollegeDetails();

//access non-static members


Console.WriteLine();
Student s1 = new Student();
Student s2 = new Student();
s1.SetStudentDetails("Sarath", "MCA");
s2.SetStudentDetails("Syam", "MBA");
s1.DisplayStudentDetails();
s2.DisplayStudentDetails();

Console.Read();
}
}
}

Output:

Static Classes
 A static class can be created using a keyword called ―static‖ used at the class definition.
 A static class can contain only static members (static data members and static methods).

Page 104 of 553


 You can‘t create an object for the static class.
 Advantages:
 If you declare any non-static member, it generates a compile time error; so that
it is guaranteed that the class contains only static members; no chance of
declaring non-static member accidentally.
 When you try to create an instance to the static class, it again generates a
compile time error, because the all static members can be accessed directly with
its class name.
 Syntax:
static class classname
{
//static data members
//static methods
}

Application 23: Static Classes Demo

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StaticClassesDemo
{
static class Sample
{
public static string SampleStaticMember = "This is my static data member";
public static void SampleStaticMethod()
{
Console.WriteLine("This is my static method.");
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Sample.SampleStaticMember);
Sample.SampleStaticMethod();
Console.Read();
}
}
}

Page 105 of 553


Output:

Constructors and Destructors


Constructor:
 The constructor is a special type of method.
 It will be called automatically, whenever an object is declared for the class.
 This is used to initialize the fields / properties.
 Def: A constructor is a method of the class, i.e. meant for initializing the data members.
The constructor gets called automatically, whenever the object is declared.
 Note: In C++, it is not possible to initialize the fields directly, that‘s why you require
―Constructor‖ compulsory. But in C#.NET andVB.NET it is possible initialize the data
members directly, along with the declaration. So, to initialize the simple values into the
fields, you don‘t require the constructor particularly in C#.NET. But if you want to
initialize the fields with some complex code, then you require to write the constructors
compulsory in C#.NET and VB.NET also.

Rules of Constructors:

 Its name must be same as "classname".


 It must be defined as "public method".
 It can be defined with/without arguments.
 It can't return any value. So, no return type specification is required.
 "Constructor overloading" is possible. Writing multiple constructors in the same class is
called as "Constructor overloading".

Types of Constructors:

i) Implicit constructor:
 A constructor, offered by the compiler implicitly is called as "Implicit constructor".

Page 106 of 553


 But the compiler automatically offers an implicit constructor, for "constructor-less
class" only.

ii) Explicit constructor:


 A constructor, defined by the programmer.
 It always overrides the implicit constructor.

Models of Constructors:

i) Default constructor:
 It's a constructor, with no arguments.
ii) Parameterized constructor:
 It's a constructor, with one or more arguments.

Constructor Implementation:

i) Default constructor:
public classname()
{
---------------;
---------------;
}

ii) Parameterized constructor:


public classname(arguments)
{
---------------;
---------------;
}

Destructor

 It is also a method of a class, which is having some special features just like constructor.
 But it can be called automatically by the compiler, at "object destruction time".
 Object destruction time means, the time of clearing of memory i.e. allocated for the
object.

Page 107 of 553


 The destructor is used to implement any process that is to be performed at the time of
object closing.

Rules for destructor:


 Its name must be defined as class name.
 It' name must be started with "~" character.
 Access modifier can‘t be specified for this.
 No arguments.
 No return value.
 Destructor overloading is not possible. That means multiple destructors can't be defined
inside of a class.

Destructor Implementation:
~classname()
{
----------;
----------;
----------;
}

Application 24: Demo on Constructors and Destructors

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConstructorsAndDestructorsDemo
{
class Student
{
//private fields
private int StudentID;
private string StudentName;

//public method
public void Display()
{
Console.WriteLine(StudentID + ", " + StudentName);
}

Page 108 of 553


//default constructor
public Student()
{
StudentID = 101;
StudentName = "Ram";
}

//parameterized constructor
public Student(int StudentID, string StudentName)
{
this.StudentID = StudentID;
this.StudentName = StudentName;
}

//destructor
~Student()
{
Console.WriteLine("This is destructor...");
}
}
class Program
{
static void Main(string[] args)
{
//invoke default constructor
Student s1 = new Student();
s1.Display();

//invoke parameterized constructor


Student s2 = new Student(102, "Sita");
s2.Display();

Console.Read();
}
}
}

Output: (Press Ctrl+F5)

Page 109 of 553


Object Initializer
 This concept is introduced in .NET Framework 3.0.
 This is used to initialize all the fields of an object, without using a constructor.
 Syntax:
Classname ObjectName = new Classname() { field1=value1, field2=value2, … };

Application 25: Demo on Object Initializer

namespace ObjectInitializerDemo
{
class Department
{
//fields
public int DeptNo;
public string DeptName;
public string Location;

//methods
public void Display()
{
Console.WriteLine("Department No: " + DeptNo);
Console.WriteLine("Department Name: " + DeptName);
Console.WriteLine("Location: " + Location);
}
}
class Program
{
static void Main(string[] args)
{
Department d = new Department() { DeptNo=10, DeptName="Sales",
Location="Hyderabad" };
d.Display();
Console.Read();
}
}
}

Output:

Page 110 of 553


Static Constructors
 The static constructor is used to initialize the ―static data members‖, whereas the normal
constructor (non-static constructor) is used to initialize the non-static data members.

 Syntax:
static classname()
{
//some code
}
 Rules:
1. Static constructors can‘t contain any access modifiers.
2. Static constructors can‘t be defined with arguments.
3. Static constructors can‘t access the non-static data members.

Application 26: Demo on Static Constructors

namespace StaticConstructorsDemo
{
class MyCollege
{
//static fields
public static string CollegeName;
public static string Address;

//static constructor
static MyCollege()
{
CollegeName = "ABC College of Technology";
Address = "Hyderabad";
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(MyCollege.CollegeName);
Console.WriteLine(MyCollege.Address);
Console.Read();
}
}
}
Page 111 of 553
Output:

Method Overloading
 Def: Method overloading is nothing but writing multiple methods with same name and
with different arguments.
 To overload methods, you should follow the below rules.
1. All of the overloaded methods name should be same.
2. Any difference between the method arguments should be maintained. The
difference may be in no. of arguments or the data types of arguments.
 Finally, when you call the overloaded method, automatically compiler takes the decision
that ―which method is to be called‖, based on the arguments that you are passing.

Application 27: Method Overloading Demo

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MethodOverloadingDemo
{
class OverloadTest
{
public double GetSimpleInterest(double p, double n, double r)
{
double si;
si = (p * n * r) / 100;
return (si);
}
public double GetSimpleInterest(double p, double n)
{
double si;
si = (p * n * 8.45) / 100;
return (si);
}
}

Page 112 of 553


class Program
{
static void Main(string[] args)
{
OverloadTest ot = new OverloadTest();
double result = ot.GetSimpleInterest(9000, 5, 3.5);
Console.WriteLine("Simple Interest is: " + result);
result = ot.GetSimpleInterest(10000, 8);
Console.WriteLine("Simple Interest is: " + result);
Console.Read();
}
}
}

Output:

Operator Overloading
 Def: Re-defining the functionality of an operator is nothing but ―Operator Overloading‖.
 With the support of operator overloading, you can use any of the existing operators with
the combination of objects.
 For example to add two numbers, you write like this (a and b are the variables).
a+b
 But suppose you have two objects declared for ―Student‖ class. Then you can‘t write like
this:
s1 + s2
 Finally, if you want to use the operator with the combination of objects, you require
―Operator Overloading‖.
 To implement this feature, write the ―Operator method‖ as follows:

public static operator symbol(arguments)


{

Page 113 of 553


 If you use the specific operator with the objects, then automatically the above method
will be called and the object(s) will be passed as arguments to the above operator
method.
 Generally operator method returns a result object.

Application 28: Operator Overloading Demo

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OperatorOverloadingDemo
{
class PersonHeight
{
//data members
private int Feet, Inches;

//methods
public void SetHeight(int Feet, int Inches)
{
this.Feet = Feet;
this.Inches = Inches;
}

public void DisplayHeight()


{
Console.WriteLine(this.Feet + " feet and " + this.Inches + " inc.");
}

//operator method
public static PersonHeight operator - (PersonHeight p1, PersonHeight p2)
{
PersonHeight ph = new PersonHeight();
if (p1.Inches < p2.Inches)
{
p1.Feet--;
p1.Inches += 12;
}
ph.Inches = p1.Inches - p2.Inches;
ph.Feet = p1.Feet - p2.Feet;
return (ph);
}
}

Page 114 of 553


class Program
{
static void Main(string[] args)
{
//create two objects for two persons
PersonHeight p1 = new PersonHeight();
PersonHeight p2 = new PersonHeight();
p1.SetHeight(8, 3);
p2.SetHeight(6, 7);

//display the height of two persons


p1.DisplayHeight();
p2.DisplayHeight();

//create one more object for result


PersonHeight p3 = new PersonHeight();

//use '-' operator


p3 = p1 - p2;

Console.WriteLine("\nThe difference is:");


p3.DisplayHeight();
Console.Read();
}
}
}

Output:

Page 115 of 553


Generics
 Generics are similar to ―templates‖ in C++.
 Def: A generic is an identifier, which automatically identifies the data type of a variable.
 This is designed to represent a particular data type, during an object life time or a
method execution.
 Here, you can observe two types of generics. One is representing a data type during an
object life time and another one is representing a data type during the method execution
time.

Types of Generics:

 Generic Classes:
The generic represents a data type, during the object‘s life time of the class.
 Generic Methods:
The generic represents a data type, during the method execution.

Definition of Generic Classes:

 A class that contains a data member of the ―generic‖ type.


 This should specify the generic type name after the class name as follows:
class classname<generic type name>
{

Definition of Generic Methods:

 A method that contains an argument of the ―generic‖ type.


 This should specify the generic type name after the method name as follows:
accessmodifier returntype methodname<generic type name>(arguments)
{

Page 116 of 553


Advantage of Generic Classes:

 According to generic classes, when an instance is created, the required type of values
could be stored as the data members.

Advantage of Generic Methods:

 According to generic methods, when you call a method, you can pass different types of
arguments to the same method, without overloading it.

Implementation of Generic Classes

 Class Definition with Generics:


class classname<T>
{
accessmodifier T datamembername;
}

 Object Construction:
classname<data type> objname = new classname<data type>;

Implementation of Generic Methods

 Method Definition with Generics:


accessmodifier returntype methodname<T>(T arg)
{

 Method Calling:
methodname<data type>(value);

Application 29: Demo on Generic Classes

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
Page 117 of 553
namespace GenericClassesDemo
{
class Sample<T>
{
T n;
public void Set(T n)
{
this.n = n;
}
public void Print()
{
Console.WriteLine(n);
}
}
class Program
{
static void Main(string[] args)
{
Sample<int> s1 = new Sample<int>();
s1.Set(10);
s1.Print();

Sample<string> s2 = new Sample<string>();


s2.Set("hai");
s2.Print();

Console.Read();
}
}
}

Output:

Application 30: Demo on Generic Methods

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GenericMethodsDemo
{
class Sample
{
public void ReverseAndPrint<T>(T[] arr)
{

Page 118 of 553


Array.Reverse(arr);
foreach (T item in arr)
Console.Write(item + ", ");
Console.WriteLine();
}
}

class Program
{
static void Main(string[] args)
{
int[] intArray = { 3, 5, 7, 9, 11 };
string[] stringArray = { "first", "second", "third" };
double[] doubleArray = { 3.567, 7.891, 2.345 };

Sample s = new Sample();


s.ReverseAndPrint<int>(intArray);
s.ReverseAndPrint<string>(stringArray);
s.ReverseAndPrint<double>(doubleArray);

Console.Read();
}
}
}

Output:

Properties
 ―Properties‖ are one of the new features of C#.
 It‘s taken from ―Visual Basic‖, not from C/C++.
 Generally, ―Properties‖ concept not used in the classes, in some rare cases and complex /
large scale classes, those are used.
 In simple, properties are extensions to ―data members‖.
 As you know that a data member contains a value, a property implements additional
logic on that data member, especially when its value is changed.
 For example, you imaging a windows form.

Page 119 of 553


 Currently, the form window height is 300 pixels.
 Suppose you change its height like this:
Form1.Height = 400;
 In this case, let us imagine that ―Height‖ is a normal data member. With the above
statement, the value of the data member will be changed. But it‘s not enough. The
window height should be increased visually. So, whenever you assign the value of the
data member, some necessary code should be executed automatically, that changes the
window height visually. In this kind of situations, ―Properties‖ are used.
 Now, let us imagine that ―Height‖ is a property. Then whenever you assign a value to it,
it‘s ―set‖ method will be executed automatically.
 In the same way, in the properties, ―get‖ method is also implemented, which gets
automatically called when the property value is requested in the client code.
 We understand better with the following implementation diagram of ―Properties‖. It
contains two accessors called ―set‖ and ―get‖.

No explicit Parameter declaration. The


implicit parameter named ―value‖ of
accessmodifier datatype propertyname
the same type as the property type is
{
set available.
{
Always void return type.
//code to set the property value
}
get
{ No implicit / explicit parameters.
//code to get the property value Always returns a value of the type of
} the property.
}
Page 120 of 553
 The “Set” Accessor:
1. This gets called automatically, whenever a value is assigned to the property in
the client code. Ex: obj.property = value;
2. The value that is assigned in the client code is available as ―implicit parameter‖,
named ―value‖ in this ―set‖ accessor.
3. This accessor can‘t return any value.

 The “Get” Accessor:


1. This gets called automatically, whenever the property value is requested in the
client code. Ex: obj.property
2. No implicit parameters are available.
3. This accessor should return the value of the property.

IMP Note: No memory gets allocated for the property. So that it can‘t store any value. To store
the actual value, we use a ―private data member‖.

The Complete Property Implementation Syntax:

private datatype variablename;


accessmodifier datatype propertyname
{
set
{
variablename = value;
}
get
{
return (variablename);
}
}

Note: There should be some difference in the variable name and property name.

Page 121 of 553


Ex:
private string name;
public string Name
{
set
{
name = value;
}
get
{
return (name);
}
}

Application 31: Demo on Properties

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PropertyDemo
{
class Student
{
//private fields
private string studentname_val;
private int age_val;

//public properties
public string StudentName
{
set
{
if (value.Length <= 20)
{
Console.WriteLine("The student name is changed as " + value);
studentname_val = value;
}
else
{
Console.WriteLine("Why you are assigning two large name...?");
}
}
get
{
return studentname_val;
}
}
Page 122 of 553
public int Age
{
set
{
if (value>=18 && value<=60)
{
Console.WriteLine("The student age is changed as " + value);
age_val = value;
}
else
{
Console.WriteLine("Why you are assigning the wrong age...?");
}
}
get
{
return age_val;
}
}
}
class Program
{
static void Main(string[] args)
{
Student stu = new Student();

stu.StudentName = "Syam";
Console.WriteLine(stu.StudentName);

Console.WriteLine();
stu.Age = 25;
Console.WriteLine(stu.Age);

Console.WriteLine();
stu.StudentName = "abcdefghijklmnopqrstuvwxyz";
Console.WriteLine(stu.StudentName);

Console.WriteLine();
stu.Age = 900;
Console.WriteLine(stu.Age);

Console.Read();
}
}
}

Page 123 of 553


Output:

Read only Properties:


 Simply implement ―get‖ accessor only, don‘t implement ―set‖ accessor.
 Syn:
private datatype variablename;
accessmodifier datatype propertyname
{
get
{
return (variablename);
}
}

 Ex:
private string name;
public string Name
{
get
{
return (name);
}
}

Page 124 of 553


Write only Properties:
 Simply implement ―set‖ accessor only, don‘t implement ―get‖ accessor.
 Syn:
private datatype variablename;
accessmodifier datatype propertyname
{
set
{
variablename = value;
}
}

 Ex:
private string name;
public string Name
{
set
{
name = value;
}
}

Auto Implemented Properties:


 This is introduced in C#.NET 3.0.
 To simplify the syntax of property declaration that contains no extra logic in ―set
accessor‖ and ―get accessor‖, this concept is introduced.
 According to this, no code for ―set‖ and ―get‖ accessors needed to write.
 No extra variable is needed to be declared.
 Syn:
accessmodifier datatype propertyname { get; set; }

 Ex:
public string Name { get; set; }

Page 125 of 553


Defining the class definitions in individual files

 All of the examples up to now have been implemented with one or more classes within
the same file.
 But in the real programming world, each class will be implemented in individual file.
 To do so,
o Click on ―Project‖ menu – ―Add Class‖.
o Enter the name of the new class.
o Click on ―Add‖ button to confirm.
o Then a new file will be created in the same project named as:
classname.cs
Note: (cs stands for C Sharp)

Application 32: Class Definition in individual files

Demo.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ClassDefInSeperateFiles
{
class Demo
{
public void DemoMethod()
{
Console.WriteLine("This is demo method...");
}
}
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

Page 126 of 553


namespace ClassDefInSeperateFiles
{
class Program
{
static void Main(string[] args)
{
Demo d = new Demo();
d.DemoMethod();
Console.Read();
}
}
}

Output:

Partial Classes
 The ―partial‖ keyword allows you to define a class, struct or interface across multiple
files.
 As you learned above, each class will be placed in individual files.
 But in some situations in future, you may require to define a class within multiple files. In
other words, the class definition can be split into multiple files.
 For example, if multiple programmers need to develop a class simultaneously, this may
be required. In the same way, in windows applications, the automatic code generator
generates some design part code for your own form class. In this case also, ―partial
classes‖ are required.

Implementation:

MyClassPart1.cs
partial class myclass
{
//some members
}

Page 127 of 553


MyClassPart2.cs
partial class myclass
{
//some more members
}

Application 33: Demo on Partial Classes

SampleClassPart1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PartialClasses
{
partial class SampleClass
{
public void FirstMethod()
{
Console.WriteLine("This is first method.");
}
}
}

SampleClassPart2.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PartialClasses
{
partial class SampleClass
{
public void SecondMethod()
{
Console.WriteLine("This is second method.");
}
}
}

Page 128 of 553


SampleClassPart3.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PartialClasses
{
partial class SampleClass
{
public void ThirdMethod()
{
Console.WriteLine("This is third method.");
}
}
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PartialClasses
{
class Program
{
static void Main(string[] args)
{
SampleClass sc = new SampleClass();
sc.FirstMethod();
sc.SecondMethod();
sc.ThirdMethod();
Console.Read();
}
}
}

Output:

Page 129 of 553


Indexer
 This is used to access the object like an array.
 Syntax: object[index]
 When you use the above syntax, a field can be accessed.
 Syntax for Indexer:
public datatype this[int index]
{
get
{
return arrayname[index];
}
set
{
arrayname[index] = value;
}
}

Application 34: Demo on Indexer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IndexerDemo
{
class IndexDemo
{
//array field
public string[] countries = new string[10];

//constructor
public IndexDemo()
{
for (int i = 0; i < countries.Length; i++)
countries[i] = "Not set";
}

//method
public void ShowCountries()
{

Page 130 of 553


foreach (string c in countries)
{
Console.WriteLine(c);
}
}

//indexer
public string this[int ind]
{
get
{
return countries[ind];
}
set
{
countries[ind] = value;
}
}
}
class Program
{
static void Main(string[] args)
{
IndexDemo id = new IndexDemo();

id.countries[3] = "India"; //access value using field


id[5] = "USA"; //access value using indexer

id.ShowCountries();

Console.Read();
}
}
}

Output:

Page 131 of 553


Inheritance
 Def: The process of implementing the "Parent-Child" relationship between two or more
classes.
 As a part of this "Inheritance" implementation, parent and child classes are to be
implemented.
 Advantage: All the data members and methods of the parent
class are accessible by child class. This is called as ―Re-usability‖. BaseClass
That means the parent class members are re-usable in the child
class.
 The parent class can also be called as "Base" / "Super" class. DerivedClass
 The child class can also be called as "Derived" / ―Sub‖ class.

Classification of Inheritance supported by C#:

1) Implementation Inheritance:

 This is commonly used inheritance.


 Whenever a class is derived from another class, it can be called as ―Implementation
Inheritance‖.
 As said above, all of the members of the super class are adopted by sub class.

2) Interface Inheritance:

 This type of inheritance is taken from ―Java‖.


 Whenever a class is derived from an interface, it can be called as ―Interface
Inheritance‖.
 The interface is similar to the class, but doesn‘t contain the method definitions; it
contains the method declarations only. We discuss about the interfaces in-depth later.

Page 132 of 553


Types of Inheritance:

1) Single Inheritance

 This is the simplest type of inheritance. BaseClass


 An inheritance relationship, with only one super class
and one sub class.
DerivedClass

2) Hierarchical Inheritance

 An inheritance relationship,
BaseClass
with only one super class and
multiple sub classes.

DerivedClass 1 DerivedClass 2

3) Multi-Level Inheritance

 An inheritance relationship, with only one super BaseClass


class and multiple sub classes, and also
extended with another sub class from the first
Intermediate Class
sub class.
 In other words, one class acts as super class
and sub class simultaneously. DerivedClass

4) Multiple Inheritance

 An inheritance relationship,
with only multiple super classes
BaseClass 1 BaseClass 2
and only one sub class.
 ―Multiple Implementation
Inheritance‖ is not supported DerivedClass
by C#, but ―Multiple Interface
Inheritance‖ is supported by C#.

Page 133 of 553


BaseClass
5) Hybrid Inheritance

 An inheritance relationship
that contains a
Intermediate Class 1 Intermediate Class 2
combination of any other
two types of inheritances.

 Ex: DerivedClass
 Multiple +
Hierarchical Inheritance
 Multiple + Multi Level Inheritance etc.

Note: Other OOP languages like C++ support multiple inheritance. But C# and VB.NET doesn‘t
support multiple inheritance to avoid some practical problems while developing future GUI
applications like windows forms applications, web sites etc.

But instead, C# and VB.NET supports ―multiple interface inheritance‖, because it doesn‘t
cause any practical problems.

Implementation steps for Inheritance

 Define the super class


class superclassname
{
//data members of super class
//methods of super class
}

 Define the sub class


class subclassname : superclassname
{
//data members of sub class
//methods of sub class
}

Page 134 of 553


 Construct the object for sub class
SubClass obj = new SubClass();

 Invoke members
obj.SuperClassMember

obj.SubClassMember

Example

 We start with an example:


class A
{
void Hello()
{
Console.WriteLine(―Hello, World!‖);
}
}
class B:A
{
void Hai()
{
Console.WriteLine(―Hai to all!‖);
}
}

 In the above example, we have two classes called ―A‖ and ―B‖. The inheritance
relationship has been established between these classes. Now, the ―A‖ class is called as
―Super‖ class and ―B‖ class is called as ―Sub‖ class. All the members of ―A‖ class are
exactly copied into ―B‖ class. Finally, whenever you construct an object for the ―B‖ class,
you can access both ―Hello()‖ method and ―Hai()‖ method also from that object. This is
what we learned up-to-now.
 But sometimes, some of the super class members may not be accessible directly from
the sub class‘s object. This kind of nature depends on the ―access modifiers‖, we use in
the super class, while we declare the super class members.

Page 135 of 553


Application 35: A simple demo on inheritance

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpleInheritanceDemo
{
//super class
class Country
{
public void ShowCountry()
{
Console.WriteLine("This is India..");
}
}

//sub class
class State : Country
{
public void ShowState()
{
Console.WriteLine("This is Andhra Pradesh..");
}
}

class Program
{
static void Main(string[] args)
{
//create instance for sub class
State st = new State();

//access the members


st.ShowCountry();
st.ShowState();

Console.Read();
}
}
}

Output:

Page 136 of 553


Application 36: Demo on “protected” modifier

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ProtectedModifierDemo
{
//super class
class Country
{
protected void ShowCountry()
{
Console.WriteLine("This is India..");
}
}
//sub class
class State : Country
{
public void ShowState()
{
ShowCountry();
Console.WriteLine("This is Andhra Pradesh..");
}
}
class Program
{
static void Main(string[] args)
{
//create instance for sub class
State st = new State();
//access the members
st.ShowState();
Console.Read();
}
}

Output:

Page 137 of 553


Try to implement the following applications

1) An application with “Single Inheritance”.

2) An application with “Hierarchical Inheritance”.

Page 138 of 553


3) An application with “Multi Level Inheritance”.

Page 139 of 553


4) An application with “Hybrid Inheritance”.

Page 140 of 548


Sealed Classes

 The sealed classes can be declared using ―sealed‖ keyword as follows:


sealed class classname
{
//some members
}
 The sealed classes are just like normal classes, but you can‘t inherit the sealed class. In
other words, you can‘t create a sub class for the sealed class.
 Trying to inherit the sealed class would cause a compilation error.
 This is just like ―Final classes‖ in java.
 Demo:
sealed class one
{

}
class two : one //can‘t inherit this. Will give a compilation error.
{

Hiding the Super Class Methods


 Let us imagine a super class and a sub class having two methods with same name and
same arguments.
 If you call the method from the client code, which method would be called? (either super
class method or sub class method?) Ans: Sub Class Method only.
 This is called as ―Hiding Methods‖. Here, the super class method is hidden by sub class
method.
 But, a compile time warning will be displayed in the sub class method definition to use a
keyword called ―new‖.
 The “new” keyword hides the super class method, that contains same name and same
arguments set.

Page 141 of 548


 Of course, this is done by default, but to implement a strong programming, ―new‖
keyword is recommended to be used when you want to hide the super class method with
intention.

Application 37: Hiding Methods with “new” keyword

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NewKeywordDemo
{
class US
{
public void ShowCountry()
{
Console.WriteLine("This is United States.");
}
}
class India : US
{
public new void ShowCountry()
{
Console.WriteLine("This is India.");
}
}
class Program
{
static void Main(string[] args)
{
India i = new India();
i.ShowCountry();
Console.Read();
}
}
}

Output:

Page 142 of 548


Virtual Methods and Method Overriding
 The similar operation as above can be implemented with two keywords called ―virtual‖
and ―override‖.
 The ―virtual‖ keyword should be used in the ―super class method‖ definition and the
―override‖ keyword should be used in the ―sub class method‖ definition.
 This concept can be called as “Method Overriding”.
 In fact, there is no much difference between ―Hiding methods‖ and ―Method Overriding‖.
 This is similar to ―virtual functions‖ in C++; but ―override‖ keyword is not required in
C++.
 The access modifiers used in the base and derived classes for the virtual methods should
be same.

Application 38: Virtual Methods and Method Overriding

namespace VirtualDemo
{
class US
{
public virtual void ShowCountry()
{
Console.WriteLine("This is United States.");
}
}
class India : US
{
public override void ShowCountry()
{
Console.WriteLine("This is India.");
}
}
class Program
{
static void Main(string[] args)
{
India i = new India();
i.ShowCountry();
Console.Read();
}
}
}

Page 143 of 548


Output:

Calling base class versions of methods


 In the above two applications, the base class method named ―ShowCountry()‖ is not
executed.
 If you want to call the base class version, simply use ―base‖ keyword in the sub class
method.
 The ―base‖ keyword simply represents the respective super class.
Syn:
base.superclassmethod();

Application 39: Demo on “base” keyword

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BaseKeywordDemo
{
class US
{
public virtual void ShowCountry()
{
Console.WriteLine("This is United States.");
}
}
class India : US
{
public override void ShowCountry()
{
base.ShowCountry(); //call the base class method
Console.WriteLine("This is India.");
}
}
class Program
{

Page 144 of 548


static void Main(string[] args)
{
India i = new India();
i.ShowCountry();
Console.Read();
}
}
}

Output:

Page 145 of 548


Abstract Classes and Methods

Abstract Methods
 The abstract method is same as ―pure virtual functions‖ in C++.
 The abstract method can be declared with ―abstract‖ keyword like this:
public abstract void samplemethod();
 The abstract method doesn‘t contain method definition; it contains only method
declaration as above.
 The abstract methods can be declared only within abstract classes.

Abstract Classes
 A class that is declared with ―abstract‖ keyword is called as ―abstract class‖.
abstract class classname
{

 Rule: If a class contains at least one abstract method, that class should be declared as
abstract class.
 The abstract class can contain abstract methods, non-abstract class and normal data
members also.
 Note: You can‘t create an object for the abstract class. It can be inherited from another
non-abstract class.
 The non-abstract class, that inherits the abstract class, should implement the
definition(s) (with ―override‖ keyword) for all of the abstract methods declared in the
abstract class.
 Note: The access modifiers used in the base and derived classes for the abstract
methods should be same.

Page 146 of 548


Implementation Syntax:
abstract class abstractclassname
{
//data members if any
//non-abstract methods if any
accessmodifier abstract returntype methodname(arguments);
}

class derivedclassname : abstractclassname


{
accessmodifier override returntype methodname(arguments)
{
//method body
}
}

Application 40: Abstract Classes and Methods

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AbstractDemo
{
//abstract class
abstract class MyBaseClass
{
public abstract void FirstMethod();
public void SecondMethod()
{
Console.WriteLine("This is Non-Abstract Method");
}
}
//non-abstract class
class MyDerivedClass : MyBaseClass
{

Page 147 of 548


public override void FirstMethod()
{
Console.WriteLine("This is Abstract Method");
}
}
class Program
{
static void Main(string[] args)
{
MyDerivedClass s = new MyDerivedClass();
s.FirstMethod();
s.SecondMethod();
Console.Read();
}
}
}

Output:

Summary of Modifiers
 Up to now, you learned several modifiers like static, new, virtual, abstract, override,
sealed.
 You get a summary of all of these modifiers with following table:
Sl.
Modifier Applies to Description
No
The method hides a base class method with same
1 new Methods only
signature.
The member does not depends / instantiates with any of
2 static All members with its class‘s objects. It can be accessed with its class
name.
3 virtual Methods only The member can be overridden by a derived class.
The abstract class can‘t be instantiated.
The abstract method is nothing but a virtual method that
Classes and
4 abstract contains only declaration with no definition. It should be
Methods only
implemented with ―override‖ keyword in the derived
class.
The member overrides an inherited virtual or abstract
5 override Methods only
member of the base class.

6 sealed Classes only The class can‘t be inherited.

Page 148 of 548


Interfaces

 This is the one of the most important features of C#.


 The .NET beginners may not understand the importance of the interfaces exactly, but in the
real-time development of .NET applications, the interfaces are used by the Sr. Developers
and the Jr. Developers.
 The ―Interfaces‖ are similar to abstract classes, but having its own features along with having
some differences with the abstract classes.

Features of Interfaces:
o The interface can be declared with ―interface‖ keyword, as follows:
interface interfacename
{

}
o The interface contains only method declarations and can‘t contain method
definitions (similar to the abstract methods).
o The interface can‘t contain any data members but can contain ―automatic
properties‖ (Already you know that the automatic property doesn‘t contain
definitions for ―get‖ and ―set‖ accessors).
o Interface methods are by default ―public‖. You can‘t use another access modifier
like private and public etc.
o The interface can‘t be instantiated. That means you can‘t create an object for the
interface.
o The interface can‘t contain constructors.
o The class that inherits the interface is called as Implementation Class.
o The implementation class should implement the definitions for all the interface
methods. If not, it would generate compile time errors.
o One interface can be inherited by any no. of classes (Hierarchical inheritance).
o One class can inherit any no. of interfaces (Multiple inheritance).
o The interface methods can‘t be declared as ―virtual‖ or ―static‖ in the interface
definition.

Page 149 of 548


Implementation Syntax of Interfaces:
//interface definition
interface interfacename
{
returntype methodname(arguments);
}

//implementation class definition


class classname : interfacename
{
public returntype methodname(arguments)
{
//some code
}
}

Application 41: Demo on Interfaces

namespace InterfaceDemo
{
interface SimpleInterest
{
double GetSimpleInterest(double P, int N, double R);
}
class SimpleInterestImpl : SimpleInterest
{
public double GetSimpleInterest(double P, int N, double R)
{
return ((P * N * R) / 100);
}
}
class Program
{
static void Main(string[] args)
{
SimpleInterestImpl sii = new SimpleInterestImpl();
Console.WriteLine("Simple Interest: " + sii.GetSimpleInterest(5000, 3, 4.5));
Console.Read();
}
}
}

.NET 4.0 and Visual Studio 2010 Page 150 of 548


Output:

Structures
 This concept is not new in C#; it is taken from C language.
 In C language‘s structures, you can write only some member variables, called as ―data
members‖ / ―fields‖. But in C#‘s structures, you can write fields along with some
methods also.
 So, In C#, structures are almost all similar to the classes, but having some differences
with the classes.

Classes (vs) Structures

Sl. No Classes Structures

1 Declared with ―class‖ keyword. Declared with ―struct‖ keyword.


Can contain fields, methods,
2 Can contain fields, methods, constructors,
constructors, destructors, properties
destructors, properties etc.
etc.
3 Supports inheritance. Doesn’t support inheritance.
User-defined default constructor can be User-defined default constructor can‘t
4
implemented. be implemented.
Data Members can be initialized in the Data members can‘t be initialized in the
5
class definition. structure definition.

Implementation:
 Define structure
struct structurename
{
//fields
//methods
}

 Create instance for structure


structurename instancename = new structurename();

.NET 4.0 and Visual Studio 2010 Page 151 of 548


Application 42: Demo on Structures

namespace StructuresDemo
{
struct Employee
{
//fields
private int EmployeeID;
private string EmployeeName;
private double Salary, Tax, NetSalary;

//methods
public void ReadData()
{
Console.Write("Enter Employee ID: ");
EmployeeID = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Employee Name: ");
EmployeeName = Console.ReadLine();
Console.Write("Enter Salary: ");
Salary = Convert.ToDouble(Console.ReadLine());
}
public void Calculate()
{
Tax = Salary * 10 / 100;
NetSalary = Salary - Tax;
}
public void DisplayData()
{
Console.WriteLine("\n\nEmployee ID: " + EmployeeID);
Console.WriteLine("Employee Name: " + EmployeeName);
Console.WriteLine("Salary: " + Salary);
Console.WriteLine("Tax: " + Tax);
Console.WriteLine("Net Salary: " + NetSalary);
}
}
class Program
{
static void Main(string[] args)
{
//create structure instance
Employee e = new Employee();
//call the methods
e.ReadData();
e.Calculate();
e.DisplayData();
Console.Read();
}
}
}

.NET 4.0 and Visual Studio 2010 Page 152 of 548


Output:

.NET 4.0 and Visual Studio 2010 Page 153 of 548


Extension Methods

 This is concept is meant for extending the methods of a class.


 There are two ways to extend a class:
o Inheritance
o Extension Methods
 As you know already in ―inheritance‖, you can extend the features of a class by defining
derived class.
 But in this ―inheritance‖ feature, you are creating two classes (base class and derived
class).
 But, if you want to add a method to an existing class, that is accessible with the
objects of the same class, it is not possible in ―inheritance‖. But it is possible using
―Extension Methods‖.
 Conclusion: This feature allows you to add one or more new methods to the same
class, without changing the definition of that particular class.
 This is more useful, when you want to add more methods to a pre-defined class.

Implementation:
 When you want to implement this concept practically, simply take a new static class first.
 In this static class, write a static method, with the required name.
 In that method, the first argument should be like this:
this classname argumentname
 Here, in place of ―classname‖, specify the class name, for which you want to write the
extension method.
 Then the ―argument name‖ acts as ―this‖ pointer in the code.
 Note: Even though it is defined as a ―static method‖ it is accessible as a non-static
method from the object of the source class.
 Syntax:
public static return_type method_name(this class_name arg, <other args if any>)
{
//some code
}
 Limitation: You can‘t add a ―static method‖ for an existing class.

.NET 4.0 and Visual Studio 2010 Page 154 of 548


Application 43: Extension Methods Demo

StringExtension.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExtensionMethodsDemo
{
static class StringExtension
{
public static string Reverse(this String str)
{
char[] ch = str.ToCharArray();
Array.Reverse(ch);
string mystr = new String(ch);
return (mystr);
}
}
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExtensionMethodsDemo
{
class Program
{
static void Main(string[] args)
{
string s = "abcdefghijklmnopqrstuvwxyz";
Console.WriteLine(s.Reverse());
Console.Read();
}
}
}

Output:

.NET 4.0 and Visual Studio 2010 Page 155 of 548


Delegates
 This is the new concept introduced in C#.
 Def: A delegate is the reference to the method.
 Using the delegate, you can call the method.
 This is used in ―GUI Events‖ and ―Multi-Threading‖ concept in future.

Implementation Syntax:

1. Define the Method:


accessmodifier returntype methodname(arguments)
{
//some code
}
2. Declare the delegate (as a data member):
delegate returntype delegatename(arguments);
3. Create instance of the delegate:
delegatename delegateinstancename = new delegatename(methodname);
4. Access the properties of the delegate:
 delegateinstancename.Target
//gets the class name that contains the target method
 delegateinstancename.Method
//gets the signature of the target method
5. Invoke / call the target method:
delegateinstancename.Invoke();
(or)
delegateinstancename.Invoke(arguments);

Application 44: Demo on Delegates

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

.NET 4.0 and Visual Studio 2010 Page 156 of 548


namespace DelegatesDemo
{
class Sample
{
public int GetSum(int a, int b, int c)
{
return (a + b + c);
}
}
class Program
{
//create the delegate
delegate int SampleDelegate(int a, int b, int c);

static void Main(string[] args)


{
//create the object
Sample s = new Sample();

//create the delegate instance


SampleDelegate sd = new SampleDelegate(s.GetSum);

//access properties of delegate Console.WriteLine("Target


Method: " + sd.Target); Console.WriteLine("Target Method
Signature: " + sd.Method);

//call the method


int SumValue = sd.Invoke(10, 20, 30);
Console.WriteLine("\nSum is: " + SumValue);

Console.Read();
}
}
}

Output:

.NET 4.0 and Visual Studio 2010 Page 157 of 548


Multi Cast Delegates
 It contains the address of multiple methods.
 You can add the reference of the methods, one by one using ―+=‖ operator.
 When you call the methods using ―Invoke()‖ method, all the methods will be called at-a-
time.
 Rule: All of the methods should have same return type and same arguments set.
 Limitation: If there is any return value, you can get only the last returned value.

Application 45: Multi-Cast Delegates Demo

namespace MultiCastDelegatesDemo
{
class Test
{
public void ShowSquare(int n)
{
int x = n * n;
Console.WriteLine("Square: " + x);
}
public void ShowCube(int n)
{
int x = n * n * n;
Console.WriteLine("Cube: " + x);
}
}
class Program
{
delegate void MyDelegate(int n);
static void Main(string[] args)
{
Test t = new Test();
MyDelegate md = new MyDelegate(t.ShowSquare);
md += new MyDelegate(t.ShowCube);
md.Invoke(10);
Console.Read();
}
}
}

Output:

.NET 4.0 and Visual Studio 2010 Page 158 of 548


The “Array” class
 There is a pre-defined class called ―Array‖.
 C# recognizes every array as an object for the ―System.Array‖ class.
 As an advantage of this, every array can access the members for that ―Array‖ class.
 For common programming needs, the ―Array‖ class offers few properties and few
methods, which are useful for general manipulations of arrays.
 Here, you can see the available properties of ―array‖ class in this table:

Properties of “Array” Class


Property Description
Length Gets the array size (total no. of elements in the array)
Rank Gets the no. of dimensions of the array

Syntax to access the property: arrayname.Property

Manipulations on Arrays
 Copying arrays:
Syn: arrayname.CopyTo(DestinationArray, StartIndex);
Ex: a.CopyTo(b, 0);
Note: The size and dimensions of both a and b arrays, should be same. It copies
all the elements into the destination array.

 Sorting arrays:
Syn: Array.Sort(arrayname);
Ex: Array.Sort(a);
Note: ―Sort‖ is a static method of ―Array‖ class. It sorts all the array elements in
ascending order.

 Reversing arrays:
Syn: Array.Reverse(arrayname);
Ex: Array.Reverse(a);

.NET 4.0 and Visual Studio 2010 Page 159 of 548


Note: ―Reverse‖ is a static method of ―Array‖ class. It exactly reverses the all
the array elements.

 Searching arrays for an element:


Syn: Array.IndexOf(arrayname, value);
Ex: Array.IndexOf(a, 50);
Note: ―IndexOf‖ is a static method of ―Array‖ class. It searches the array for the
given value, and returns it‘s index if it is found; otherwise it returns -1;

Application 46: “Array” Class Demo

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ArrayClassDemo
{
class Program
{
static void Main(string[] args)
{
//single dimensional array
Console.WriteLine("Single dimensional array:");
int[] a = { 643, 32948, 39, 23094, 112};
foreach (int i in a)
Console.Write(i + " ");
Console.WriteLine("\nLength: " + a.Length);
Console.WriteLine("Rank: " + a.Rank);

//double dimensional array


Console.WriteLine("\nDouble dimensional array:");
int[,] b = { {56, 1238, 8812}, {99, 2784, 2892} };
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
Console.Write(b[i,j] + " ");
Console.WriteLine();
}
Console.WriteLine("Length: " + b.Length);
Console.WriteLine("Rank: " + b.Rank);

//string array
Console.WriteLine("\nString array:");

.NET 4.0 and Visual Studio 2010 Page 160 of 548


string[] s = { "Java", "Corba", "C++", "Perl", "AJAX", "JavaScript" };
foreach (string i in s)
Console.Write(i + " ");

//copying arrays
Console.WriteLine("\n\nSingle dim array after copy:");
int[] c = new int[5];
a.CopyTo(c, 0);
foreach (int i in c)
Console.Write(i + " ");
//sorting arrays
Array.Sort(c);
Array.Sort(s);
Console.WriteLine("\n\nSingle dim array after sorting:");
foreach (int i in c)
Console.Write(i + " ");
Console.WriteLine("\n\nString array after sorting:");
foreach (string i in s)
Console.Write(i + " ");

//reversing arrays
Array.Reverse(c);
Array.Reverse(s);
Console.WriteLine("\n\nSingle dim array after reversing:");
foreach (int i in c)
Console.Write(i + " ");
Console.WriteLine("\n\nString array after reversing:");
foreach (string i in s)
Console.Write(i + " ");
Console.WriteLine("\n");

//searching an element
Console.WriteLine("Index of 'Java' in the string array is : " + Array.IndexOf(s,
"Java"));

Console.Read();
}
}
}

.NET 4.0 and Visual Studio 2010 Page 161 of 548


Output:

The “Math” class


 The ―System.Math‖ class offers some pre-defined methods related to mathematical
operations.
 ―Math‖ is a static class. So, all of the methods of ―Math‖ class are static methods, so that
you can access them without creating any object.
 Here, you can see the available methods of ―Math‖ class in this table:

Methods of “Math” Class


Method Description
Abs(value) Returns absolute (positive) value.
Pow(n, m) Returns n power m (nm) value
Min(n1, n2) Returns the minimum value among given two values.
Max(n1, n2) Returns the maximum value among given two values.
Sqrt(n) Returns the square root value of ‗n‘.

.NET 4.0 and Visual Studio 2010 Page 162 of 548


Floor(n) Returns the previous integer value of ‗n‘.
Ceiling(n) Returns the next integer value of ‗n‘.
Returns rounded integer value of ‗n‘. If the decimal part starts with a digit,
Round(n) i.e. lesser than 5, it returns previous integer value; otherwise it returns next
integer value.
Round(n, dec) Returns rounded decimal value of ‗n‘, based on the given no. of decimals.
Returns ―1‖, if the n value is positive.
Sign(n) Returns ―0‖, if the n value is 0.
Returns ―-1‖, if the n value is negative.

Fields of “Math” Class


Data Member Description
PI It‘s a constant. It contains the value of PI. (3.14)

Application 47: “Math” Class Demo

namespace MathClassDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Math.Abs(-84));
Console.WriteLine(Math.Pow(10, 3));
Console.WriteLine(Math.Min(5, 100));
Console.WriteLine(Math.Max(5, 100));
Console.WriteLine(Math.Min(25, Math.Min(78, 87)));
Console.WriteLine(Math.Max(25, Math.Max(78, 87)));
Console.WriteLine(Math.Sqrt(9));
Console.WriteLine(Math.Floor(10.56));
Console.WriteLine(Math.Ceiling(10.56));
Console.WriteLine(Math.Round(10.56));
Console.WriteLine(Math.Round(10.23));
Console.WriteLine(Math.Round(10.2342, 2));
Console.WriteLine(Math.Round(10.2392, 2));
Console.WriteLine(Math.Sign(10));
Console.WriteLine(Math.Sign(-10));
Console.WriteLine(Math.PI);
Console.Read();
}
}
}

.NET 4.0 and Visual Studio 2010 Page 163 of 548


Output:

The “String” class


 In C#, every string variable will be recognized as an object for ―System.String‖ class.
 The ―String‖ class provides necessary properties and methods for performing all the
common and advanced manipulations on strings.
 Here are the properties of ―String‖ class.

Properties of “String” Class


Property Description Syntax
Length Gets the total no. of characters in the string object. stringobj.Length

Methods of “String” Class


Method Description Syntax
Converts the string into lower case and
ToLower() stringobj.ToLower()
returns it.
Converts the string into upper case and
ToUpper() stringobj.ToUpper()
returns it.
Removes the blank spaces at left and
Trim() stringobj.Trim()
right side of the string and returns it.
Removes the blank spaces at left of the
TrimStart() stringobj.TrimStart()
string and returns it.

.NET 4.0 and Visual Studio 2010 Page 164 of 548


Removes the blank spaces at right side
TrimEnd() stringobj.TrimEnd()
of the string and returns it.
Checks the string with the given string
Equals() for equality. If both are equal, returns stringobj.Equals(str)
―true‖, otherwise returns ―false‖.
Checks whether the string contains the
given string at the left most side. If it
StartsWith() stringobj.StartsWith(str)
contains, returns ―true‖, otherwise
returns ―false‖.
Checks whether the string contains the
given string at the right most side. If it
EndsWith() stringobj.EndsWith(str)
contains, returns ―true‖, otherwise
returns ―false‖.
Inserts the given string value into the
stringobj.Insert(index,
Insert() string object at the specific index and
stringvalue)
returns it.
Removes all the characters from the
Remove() string, starting from given index and stringobj.Remove(index)
returns it.
Removes specific no. of characters
(based on the given count) from the
Remove() stringobj.Remove(index, count)
string, starting from given index and
returns it.
Gets the part of the string starting from
Substring() given index up to end of the string and stringobj.Substring(index)
returns it.
Gets the part of the string starting from
Substring() given index based on the expected stringobj.Substring(index, length)
length and returns it.
Replaces the each occurrence of given
stringobj.Replace(old char, new
Replace() character(s) with another character(s)
char)
and returns it.
Pads out the string by adding the given stringobj.PadLeft(total width,
PadLeft()
repeated character at the left side of padding char)

.NET 4.0 and Visual Studio 2010 Page 165 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

the string and returns it.


Pads out the string by adding the given
stringobj.PadRight(total width,
PadRight() repeated character at the right side of
padding char)
the string and returns it.
Converts the string into a character
array, by treating each character in the
ToCharArray() stringobj.ToCharArray()
string as an element of the character
array, and returns it.
Splits the string based on the given
Split() separator character and finally returns a stringobj.Split(separator char)
string array.
Searches for existence of given
character(s) in the string. If it is found
IndexOf() (for the first occurrence), returns the stringobj.IndexOf(str/char)
index of the first character. If it is not
found, then returns -1.
Searches for existence of given
character(s) in the string starting from
specified index. If it is found (for the stringobj.IndexOf(str/char, start
IndexOf()
first occurrence), returns the index of index)
the first character. If it is not found,
then returns -1.
Searches for existence of given
character(s) in the string in reverse. If it
LastIndexOf() is found (for the first occurrence), stringobj.LastIndexOf(str/char)
returns the index of the first character.
If it is not found, then returns -1.
Searches for existence of given
character(s) in the string starting from
specified index in reverse. If it is found stringobj.LastIndexOf(str/char,
LastIndexOf()
(for the first occurrence), returns the start index)
index of the first character. If it is not
found, then returns -1.

.NET 4.0 and Visual Studio 2010 Page 166 of 548


Application 48: Demo on “String” Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StringDemo
{
class Program
{
static void Main(string[] args)
{
//create string object
string s = "I am a .NET Developer";
Console.WriteLine("The original string is: " + s);
Console.WriteLine("The original string's length is: " + s.Length);

//copy strings
string s1;
s1 = s;
Console.WriteLine("\nThe copied string is: " + s1);

//concatenate strings
string s2 = "I am working in Wipro.";
string s3;
s3 = s1 +". " + s2;
Console.WriteLine("\nThe concatenated string is: " + s3);

//compare strings
if (s1 == s2)
Console.WriteLine("\ns1 and s2 are equal");
else
Console.WriteLine("\ns1 and s2 are not equal");
string s4 = s1;
if (s1 == s4)
Console.WriteLine("\ns1 and s4 are equal");
else
Console.WriteLine("\ns1 and s4 are not equal");

//convert the string into lower case string s6


= s.ToLower(); Console.WriteLine("\nLower
case is: " + s6);

//convert the string into upper case string s7


= s.ToUpper(); Console.WriteLine("\nUpper
case is: " + s7);

Page 167 of 553


//string trimming
string s8 = " Hello, World ";
Console.WriteLine("\nString before trimming: " + s8);
string s9 = s8.Trim();
Console.WriteLine("\nString after trimming: " + s9);
string s10 = s8.TrimStart();
Console.WriteLine("\nString after left trimming: " + s10);
string s11 = s8.TrimEnd();
Console.WriteLine("\nString after right trimming: " + s11);

//check for the start


if (s.StartsWith("I"))
Console.WriteLine("\nString starts with 'I'");
else
Console.WriteLine("\nString doesn't starts with 'I'");
if (s.StartsWith("i"))
Console.WriteLine("\nString starts with 'i'");
else
Console.WriteLine("\nString doesn't starts with 'i'");

//check for the end


if (s.EndsWith("Developer"))
Console.WriteLine("\nString ends with 'Developer'");
else
Console.WriteLine("\nString doesn't ends with 'Developer'");
if (s.EndsWith("am"))
Console.WriteLine("\nString ends with 'am'");
else
Console.WriteLine("\nString doesn't ends with 'am'");

//insert character(s) into the string string s12 =


s.Insert(7, "ASP"); Console.WriteLine("\nString after
insetion: " + s12);

//remove character(s) from the string string s13 =


s.Remove(7); Console.WriteLine("\nString after
removal: " + s13); string s14 = s.Remove(7, 5);
Console.WriteLine("\nString after 5 characters removal: " + s14);

//get the sub string


string s15 = s.Substring(7);
Console.WriteLine("\nSub String is: " + s15);

string s16 = s.Substring(7, 4);


Console.WriteLine("\nAnother Sub String is: " + s16);

//replace the character(s)


string s17 = s.Replace("a", "x");
Console.WriteLine("\nString after replace: " + s17);

Page 168 of 553


//left padding
string s18 = s.PadLeft(26, '*');
Console.WriteLine("\nString after left padding: " + s18);

//right padding
string s19 = s.PadRight(26, '*');
Console.WriteLine("\nString after right padding: " + s19);

//split the string


string s20 = "This is first line.This is second line.This is third line.";
Console.WriteLine("\nA string for splitting:\n" + s20);
string[] s21 = s20.Split('.');
Console.WriteLine("\nThe string array after splitting:");
foreach (string temp in s21)
Console.WriteLine(temp);

//search the string for character(s) Console.WriteLine("Index of 'D' is: " +


s.IndexOf('D')); Console.WriteLine("Index of 'x' is: " + s.IndexOf('x'));
Console.WriteLine("Index of 'am' is: " + s.IndexOf("am"));
Console.WriteLine("Index of 'a' is: " + s.IndexOf('a'));
Console.WriteLine("Index of 'a' after 3rd character is: " + s.IndexOf('a', 3));

Console.WriteLine("LastIndex of 'D' is: " + s.LastIndexOf('D'));


Console.WriteLine("LastIndex of 'x' is: " + s.LastIndexOf('x'));
Console.WriteLine("LastIndex of 'am' is: " + s.LastIndexOf("am"));
Console.WriteLine("LastIndex of 'a' is: " + s.LastIndexOf('a'));
Console.WriteLine("LastIndex of 'a' after 3rd character is: " + s.LastIndexOf('a', 3));

Console.Read();
}
}
}

Page 169 of 553


Output:

Page 170 of 553


The “DateTime” Structure
 Library: System.DateTime
 To store date and time values, you require creating an instance for ―DateTime‖
structure.
 The instance for ―System.DateTime‖ class, can hold date and time value in US format:
Date and time Format: mm/dd/yyyy hh:mi:ss AM/PM

Object Implementation:
 Create an instance for “System.DateTime” structure:
DateTime dtobj;
 Assign any date&time value:
dtobj = Convert.ToDateTime(―mm/dd/yyyy hh:mi:ss AM/PM‖);
 Assign System date&tme:
dtobj = DateTime.Now;

Properties of “DateTime” Structure

Property Description Syntax


Day Gets the day (dd) dtobj.Day
Month Gets the month (mm) dtobj.Month
Year Gets the year (yy) dtobj.Year
Hour Gets the hour (hh) (in 24-hours format) dtobj.Hour
Minute Gets the minute (mi) dtobj.Minute
Second Gets the second (ss) dtobj.Second
MilliSecond Gets the milli second dtobj.MilliSecond
DayOfYear Gets the index of the current day, in the year (0 to 366) dtobj.DayOfYear
DayOfWeek Gets the current week name (Sunday, Monday,…,Saturday) dtobj.DayOfWeek

Methods of “DateTime” Structure


Method Description Syntax
Returns the date and time value as string
ToString()
in following format.

Page 171 of 553


mm/dd/yyy dtobj.ToString()
hh:mi:ss
AM/PM

Page 172 of 553


Returns the date value as string in the

ToShortDateString() following format. dtobj.ToShortDateString()


mm/dd/yyyy
Returns the date value as string in the

ToLongDateString() following format. dtobj.ToLongDateString()


Day, Month dd, yyyy
Returns the time value as string in the

ToShortTimeString() following format. dtobj.ToShortTimeString()


hh:mi AM/PM
Returns the date value as string in the

ToLongDateString() following format. dtobj.ToLongTimeString()


hh:mi:ss AM/PM
Adds the given no. of days to the date
AddDays() dtobj.AddDays(n)
object and returns it.
Adds the given no. of months to the date
AddMonths() dtobj.AddMonths(n)
object and returns it.
Adds the given no. of years to the date
AddYears() dtobj.AddYears(n)
object and returns it.
Adds the given no. of hours to the date
AddHours() dtobj.AddHours(n)
object and returns it.
Adds the given no. of minutes to the date
AddMinutes() dtobj.AddMinutes(n)
object and returns it.
Adds the given no. of seconds to the date
AddSeconds() dtobj.AddSeconds(n)
object and returns it.
Adds the given no. of milli seconds to the
AddMilliSeconds() dtobj.AddMilliSeconds(n)
date object and returns it.

Static Properties of “DateTime” Structure


Property Description Syntax
Now Gets the current system date and time DateTime.Now

Static Methods of “DateTime” Structure


Method Description Syntax

Page 173 of 553


Returns a bool value, that indicates whether
IsLeapYear()
the given year is a leap year or not. DateTime.IsLeapYear(year)

Page 174 of 553


Returns the no. of days in the given month, DateTime.DaysInMonth(year,
DaysInMonth() month)
based on the given year.

Date Comparisons

 Date comparisons are very simple in C#, because ―DateTime‖ structure overloads the
necessary relational operators such as ―==‖, ―!=‖, ―<‖, ―>‖, ―<=‖, ―>=‖.
 You can directly use these operators between two dates and get the appropriate result.

Date Difference

 To find out the difference between two dates, simply use ―-― operator, which is already
overloaded.
 When you use this, you can get the result as an ―System.TimeSpan‖ object.

Application 49: “DateTime” Structure Demo

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DateTimeDemo
{
class Program
{
static void Main(string[] args)
{
//create DateTime obj
DateTime dt1;
dt1 = Convert.ToDateTime("7/16/2009 6:23 PM");
DateTime dt2 = DateTime.Now;
//display dates
Console.WriteLine("dt1 is: " + dt1.ToString());
Console.WriteLine("dt2 is: " + dt2.ToString());

//display individual values


Console.WriteLine("\nIndividual values of dt2:");
Console.WriteLine("dd: " + dt2.Day);
Console.WriteLine("mm: " + dt2.Month);
Console.WriteLine("yyyy: " + dt2.Year);

Page 175 of 553


Console.WriteLine("hh: " + dt2.Hour);
Console.WriteLine("mi: " + dt2.Minute);

Page 176 of 553


Console.WriteLine("ss: " + dt2.Second);
Console.WriteLine("ms: " + dt2.Millisecond);

//implement user-defined date formats


string IndianFormattedDate = dt2.Day + "-" + dt2.Month + "-" + dt2.Year;
Console.WriteLine("\nDate in indian format: " + IndianFormattedDate);

//display the day index


Console.WriteLine("\nDay of year: " + dt2.DayOfYear);
Console.WriteLine("\nDay of week: " + dt2.DayOfWeek);

//long and short formatted date and time


Console.WriteLine("\nShort date format: " + dt2.ToShortDateString());
Console.WriteLine("\nLong date format: " + dt2.ToLongDateString());
Console.WriteLine("\nShort time format: " + dt2.ToShortTimeString());
Console.WriteLine("\nLong time format: " + dt2.ToLongTimeString());

//adding values
DateTime dt3 = dt2.AddDays(5);
Console.WriteLine("\ndt2 after adding 5 days: " + dt3.ToShortDateString());
DateTime dt4 = dt2.AddMonths(5);
Console.WriteLine("\ndt2 after adding 5 months: " + dt4.ToShortDateString());
DateTime dt5 = dt2.AddYears(5);
Console.WriteLine("\ndt2 after adding 5 years: " + dt5.ToShortDateString());
DateTime dt6 = dt2.AddHours(5);
Console.WriteLine("\ndt2 after adding 5 hours: " + dt6.ToLongTimeString());
DateTime dt7 = dt2.AddMinutes(5);
Console.WriteLine("\ndt2 after adding 5 minutes: " + dt7.ToLongTimeString());
DateTime dt8 = dt2.AddSeconds(5);
Console.WriteLine("\ndt2 after adding 5 seconds: " + dt8.ToLongTimeString());

//check whether this is leap year or no


if (DateTime.IsLeapYear(dt2.Year))
Console.WriteLine("\nThis is a leap year.");
else
Console.WriteLine("\nThis is not a leap year.");

//get the total no. of days in this month


Console.WriteLine("\nNo. of days in this month: " + DateTime.DaysInMonth(dt2.Year,
dt2.Month));

//date comparision
if (dt1 == dt2)
Console.WriteLine("\ndt1 and dt2 are equal.");
else if (dt1 > dt2)
Console.WriteLine("\ndt1 is greater than dt2.");
else if (dt1 < dt2)
Console.WriteLine("\ndt1 is less than dt2.");

Page 177 of 553


//date difference
TimeSpan ts = dt2 - dt1;

Page 178 of 553


Console.WriteLine("\nThe difference between dt2 and dt1 is: " + ts.Days + " days.");
Console.Read();
}
}
}

Output:

Page 179 of 553


The “Random” class
 Library: System.Random
 This class is used to generate a random number, at any time.
 In future, while performing different programming logics, this random number generation
concept may be required.

Implementation:
 Create an instance:
Random r = new Random();
 Generate the random number based on the given boundary values:
r.Next(min value, max value);

Application 50: Demo on “Random” Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RandomDemo
{
class Program
{
static void Main(string[] args)
{
Random r = new Random();
for (int i = 0; i < 300; i++)
{
Console.Write(r.Next(1, 300) + ", ");
}
Console.Read();
}
}
}

Page 180 of 553


Output:

Collections
 The concept of ―collections‖ is basically developed from ―Arrays‖.
 Already you know that, arrays are multiple value containers of fixed type.
 In order to hold different types of values on the same array, you require collections.
 Another advantage of collections is those are dynamic sizable. In other words, the array
is of fixed size and the collection is of dynamic size.
 Finally, if you don‘t know how many values are to be stored in the array at the time of its
declaration, you require to use ―collections‖; (or) if you want to store different type of
values in the same array, at that case also, you require to use ―collections‖.
 .NET offers some pre-defined classes for maintenance of collections.

Collection Classes:

 List:
1) Contains n no. of values of same type. It‘s a generic class.
2) This is member of ―System.Collections.Generic” namespace.
 ArrayList:
1) Contains n no. of values of different types.

Page 181 of 553


2) This is member of ―System.Collections” namespace.

Page 182 of 553


Implementation of “List” class:

 Import namespace:
using System.Collections.Generic;
 Create instance:
List<data type> obj = new List<data type>();
 Add values:
obj.Add(value);
 Get the currently existing no. of values in the collection:
obj.Count
 Get the individual element in the collection:
obj[index];

Implementation of “ArrayList” class:

 Import namespace:
using System.Collections;
 Create instance:
ArrayList obj = new ArrayList();
 Add values:
obj.Add(value);
 Get the currently existing no. of values in the collection:
obj.Count
 Get the individual element in the collection:
obj[index];

Application 51: Demo on “List” Class

using System.Collections.Generic;

namespace ListClass
{
class Program

Page 183 of 553


{
static void Main(string[] args)

Page 184 of 553


{
List<string> MyMessages = new List<string>();

MyMessages.Add("Good Morning");
MyMessages.Add("Good Afternoon");
MyMessages.Add("Good Evening");
MyMessages.Add("Good Night");

//MyMessages.Add(10); //error

Console.WriteLine(MyMessages.Count + " messages found.\n");


foreach (string s in MyMessages)
{
Console.WriteLine(s);
}

Console.Read();
}
}
}

Output:

Application 52: Demo on “ArrayList” Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ArrayListClass
{
class Program
{
static void Main(string[] args)
{
ArrayList al = new ArrayList();

Page 185 of 553


al.Add("Hai");

Page 186 of 553


al.Add("How r u");
al.Add(1000);
al.Add(true);
al.Add(DateTime.Now);

Console.WriteLine(al.Count + " values found.\n");


for (int i = 0; i < al.Count; i++)
Console.WriteLine(al[i]);

Console.Read();
}
}
}

Output:

Collection Initializer
 As per the previous examples with collections, we require to add the values to the
collections using ―Add()‖ method.
 Suppose you want to add so many elements to the collection. Then if you are using it
takes ―Add()‖ method (as above), it takes no. of lines of code.
 To solve this problem, ―Collection Initializer‖ can be used.
 Purpose: To initialize the elements of a collection, at the time declaration.
 Syntax:
1) “List” collection class:
List<data type> obj = new List<data type>() { val1, val2, …. };
2) “ArrayList” collection class:
ArrayList obj = new ArayList() { val1, val2, …. };

Page 180 of 553


Application 53: Demo on Collection Initializer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace CollectionInitializerDemo
{
class Program
{
static void Main(string[] args)
{
//Collection Initializer with List class
Console.WriteLine("List:");
List<string> lst = new List<string>() { "one", "two", "three", "four" }; //collection
initializer
lst.Add("five"); //add additional elements if required

foreach (string s in lst)


Console.WriteLine(s);

Console.WriteLine("\n\nArray List:");
ArrayList arrlst = new ArrayList() { "emp_001", "Srinivas", 8900, "Washington" };
//collection initializer
arrlst.Add(DateTime.Now); //add additional elements if required
foreach (object s in arrlst)
Console.WriteLine(s);

Console.Read();
}
}
}

Output:

Page 181 of 553


The “PrintDocument” class
.NET supports to print any type of documents through the printer.
Library: System.Drawing.Printing.PrintDocument
This class object represents a document (any type of file), that is ready to print.

Note: By default, ―System.Drawing‖ assembly will not be linked with the ―Console applications‖.
That‘s why you need to add a reference to that as follows:
 Click on ―Project‖ menu – ―Add Reference‖.
 Select ―System.Drawing‖ assembly.
 Click on OK. Then the ―System.Drawing‖ assembly will be linked with the current
project and it will be displayed in ―References‖ folder in the Solution Explorer.

Implementation:
 Import the namespace:
using System.Drawing.Printing;
 Construct the object:
PrintDocument obj = new PrintDocument();
 Assign the document name, that is to be printed:
obj.DocumentName = ―file path to be printed‖;
 Start Printing:
obj.Print();

Application 54: Demo on Printing

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Printing;

namespace PrintingDemo
{
class Program
{

Page 182 of 553


static void Main(string[] args)
{
PrintDocument doc = new PrintDocument();
doc.DocumentName = "c:\\SampleDocument.doc";
doc.Print();
Console.WriteLine("Printing started...");
Console.Read();
}
}
}

Output:

Page 183 of 553


The “DriveInfo”class
 .NET support to access the available drives information on the computer such as ―C: drive‖,
―D: drive‖ etc.
 This drives may include with hard disks, CD-ROM drives, DVD-ROM drives, pen drives etc.
 It offers to get the volume labels, total space and current free space of the drives etc.

Library: System.IO.DriveInfo

The ―DriveInfo‖ class object can represent a drive on the computer. It offers several properties
and methods to access the related information of the drive.

Object Construction:
Syn: DriveInfo obj = new DriveInfo(―drive letter‖);
Ex: DriveInfo obj = new DriveInfo(―c‖);

You can observe the list of all available properties, methods of this class.

Properties of “DriveInfo” class


Property Description
IsReady Indicates whether the drive is ready or not (true / false)
Name Represents the name of the drive with drive letter. (Ex: c:\)
DriveType Represents the type of the drive. (like Fixed, CD Rom, Removable)
VolumeLabel Represents the volume label.
DriveFormat Represents the file system of the drive like FAT32, NTFS, CDFS etc.
TotalSize Represents the total memory capacity of the drive in bytes.
TotalFreeSpace Represents the total free space in the drive in bytes.

Static Methods of “DriveInfo” class


Method Description
GetDrives() Returns all the currently available drive objects in the form of an array.

Application 55: Demo on “DriveInfo” class – For a Single Drive

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
Page 184 of 553
namespace DriveInfoDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the drive letter (a to z):");
string driveletter = Console.ReadLine();

DriveInfo d = new DriveInfo(driveletter);

if (d.IsReady)
{
Console.WriteLine(d.Name);
Console.WriteLine(d.DriveType);
Console.WriteLine(d.VolumeLabel);
Console.WriteLine(d.DriveFormat);
Console.WriteLine(d.TotalSize + " bytes.");
Console.WriteLine(d.TotalFreeSpace + " bytes.");
}
else
Console.WriteLine(d.Name + " - " + " Not Ready.");

Console.Read();
}
}
}

Output:

Application 56: Demo on “DriveInfo” class – For Multiple Drives

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace GetDrivesDemo
{
Page 185 of 553
class Program
{
static void Main(string[] args)
{
DriveInfo[] dinfo = DriveInfo.GetDrives();
Console.WriteLine(dinfo.Length + " drives found on this computer.");
foreach (DriveInfo d in dinfo)
{
Console.WriteLine();
if (d.IsReady)
{
Console.WriteLine(d.Name);
Console.WriteLine(d.DriveType);
Console.WriteLine(d.VolumeLabel);
Console.WriteLine(d.DriveFormat);
Console.WriteLine(d.TotalSize + " bytes.");
Console.WriteLine(d.TotalFreeSpace + " bytes.");
}
else
Console.WriteLine(d.Name + " - " + d.DriveType + " - Not Ready.");
}
Console.Read();
}
}
}

Output:

Page 186 of 553


The “DirectoryInfo”class
 The System.IO namespace necessary API to access the folders (directories) information
also.
 According to this, a folder is to be represented as an object.
 The folder object is able to get the details of the folder like folder full path, sub
directories and files etc.

Library: System.IO.DirectoryInfo

This class object represents a folder on the file system. This able to get the information
of the folder and also to perform certain operations on that folder.

Object Construction:
Syn: DirectoryInfo obj = new DirectoryInfo(―path of the directory‖);
Ex: DirectoryInfo obj = new DirectoryInfo(―c:\\windows‖);

You can observe the list of all available properties, methods of this class.

Properties of “DirectoryInfo” class


Property Description
Checks the existence of the directory. If it exists, it indicates
Exists
―true‖. Otherwise, it indicates ―false‖.
Name Gets only the name of the directory (without path)
FullName Gets the name along with full path.
CreationTime Gets the date & time, when the directory is created.
LastAccessTime Gets the date & time, when the directory is accessed last time.
LastWriteTime Gets the date & time, when the directory is modified last time.
Gets the directory object, which represents the respective parent
Parent
folder.
Root Gets the name of the drive, in which the directory exists.

Methods of “DirectoryInfo” class


Method Description
Create() Creates a new directory.
CreateSubdirectory(name) Creates a sub directory.
Delete() Deletes the directory, if it is empty.
Deletes the entire directory, along with its sub directories and
Delete(true)
files.

Page 187 of 553


GetFiles() Gets all the files in the directory as ―FileInfo‖ class object array.
Gets the files in the directory as ―FileInfo‖ class object array,
GetFiles(“search pattern”)
based on the given search pattern.
Gets all the directories in the directory as ―DirectoryInfo‖ class
GetDirectories()
object array.
GetDirectories(“search Gets the directories in the directory as ―DirectoryInfo‖ class object
pattern”) array, based on the given search pattern.

Application 57: Demo on “DirectoryInfo” class

using System.IO;

namespace DirectoryInfoDemo1
{
class Program
{
static void Main(string[] args)
{
string directorypath = "c:\\windows\\help";
DirectoryInfo dinfo = new DirectoryInfo(directorypath);

if (dinfo.Exists)
{
Console.WriteLine("Directory Name: " + dinfo.Name);
Console.WriteLine("Directory Full Path: " + dinfo.FullName);
Console.WriteLine("\nCreated on: " + dinfo.CreationTime);
Console.WriteLine("Last accessed on: " + dinfo.LastAccessTime);
Console.WriteLine("Last modified on: " + dinfo.LastWriteTime);
Console.WriteLine("\nParent: " + dinfo.Parent.FullName);
Console.WriteLine("Root: " + dinfo.Root);

Console.WriteLine("\nFiles:");
FileInfo[] fobjs = dinfo.GetFiles();
foreach (FileInfo f in fobjs)
Console.WriteLine(f.FullName);

Console.WriteLine("\nSub Directories:");
DirectoryInfo[] dobjs = dinfo.GetDirectories();
foreach (DirectoryInfo d in dobjs)
Console.WriteLine(d.FullName);
}
else
Console.WriteLine(directorypath + " is not available on the system.");

Console.Read();
}
}
}

Page 188 of 553


Output:

Application 58: Creating a Directory

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DirectoryInfoDemo2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the directory path:");
string directorypath = Console.ReadLine();
DirectoryInfo dinfo = new DirectoryInfo(directorypath);

if (!dinfo.Exists)
{
dinfo.Create();
Console.WriteLine("Directory created.");
}
else
Console.WriteLine(directorypath + " is already exists.");

Console.Read();
}
}
}

Page 189 of 553


Output:

Application 59: Deleting a Directory

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DirectoryInfoDemo3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the directory path:");
string directorypath = Console.ReadLine();
DirectoryInfo dinfo = new DirectoryInfo(directorypath);

if (dinfo.Exists)
{
dinfo.Delete(true);
Console.WriteLine("Directory deleted.");
}
else
Console.WriteLine(directorypath + " doesn't exists.");

Console.Read();
}
}
}

Output:

.NET 4.0 and Visual Studio 2010 Page 190 of 548


The“FileInfo”class
 Similar to the drives and folders, the ―System.IO‖ namespace is used to manipulate the
files also.
 The file manipulations include with checking for the file existence, get the file details like
file size, file attributes, created date, last accessed date etc., and write new content to
the files and also read content from existing files.
 Every file is to be represented as an object, created for ―System.IO.FileInfo‖ class.

Library: System.IO.FileInfo

This class object represents a file on the file system. This able to get the information of
the file and also to perform certain operations on that folder.

Object Construction:
Syn: FileInfo obj = new FileInfo(―path of the file‖);
Ex: FileInfo obj = new FileInfo(―c:\\tc\list.h‖);

You can observe the list of all available properties, methods of this class.

Properties of “FileInfo” class


Property Description
Checks the existence of the directory. If it exists, it indicates
Exists
―true‖. Otherwise, it indicates ―false‖.
Name Gets only the name of the file (without path)
FullName Gets the name along with full path.
Extension Gets the extension of the file.
DirectoryName Gets the name of the file, in which the file exists.
Length Gets the size of the file (in bytes).
CreationTime Gets the date & time, when the file is created.
LastAccessTime Gets the date & time, when the file is accessed last time.
LastWriteTime Gets the date & time, when the file is modified last time.

Methods of “FileInfo” class


Method Description
Delete() Deletes the file permanently.
Copies the file into the destination location with the specified
CopyTo(destination file name)
file name.
Moves the file into the destination location with the specified
MoveTo(destination file name)
file name.

.NET 4.0 and Visual Studio 2010 Page 191 of 548


Application 60: Demo on “FileInfo” class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace FileInfoDemo
{
class Program
{
static void Main(string[] args)
{
string filepath;
Console.WriteLine("Enter the file path:");
filepath = Console.ReadLine();

FileInfo fobj = new FileInfo(filepath);

if (fobj.Exists)
{
Console.WriteLine("\nName: " + fobj.Name);
Console.WriteLine("Full Name: " + fobj.FullName);
Console.WriteLine("Extension: " + fobj.Extension);
Console.WriteLine("Directory: " + fobj.DirectoryName);
Console.WriteLine("File Size: " + fobj.Length + " bytes");
Console.WriteLine("Created on: " + fobj.CreationTime);
Console.WriteLine("Last Accessed on: " + fobj.LastAccessTime);
Console.WriteLine("Last Modified on: " + fobj.LastWriteTime);
}
else
Console.WriteLine("File not found.");

Console.Read();
}
}
}

.NET 4.0 and Visual Studio 2010 Page 192 of 548


Output:

File Streams
 To write / read the content to / write the file, you require file streams.
 A file stream acts as a pointer for the file, which contains the memory address of the file
on the disc.
 There are two types of file streams.
1) Reading Streams
2) Writing Streams

API: System.IO.StreamReader (to read the content of the file)


System.IO.StreamWriter (to write the content into the file)

Writing content to the file


 Import the API
using System.IO;
 Create the stream writer object
StreamWriter sw = new StreamWriter(―file name‖);
 Write the content
sw.Write(―content here‖);
 Close the Writer
sw.Close();

.NET 4.0 and Visual Studio 2010 Page 193 of 548


Reading content from the file
 Import the API
using System.IO;
 Create the stream reader object
StreamReader sr = new StreamReader(―file name‖);
 Reade the content
sr.ReadToEnd();
 Close the Reader
sr.Close();

Application 61: File Writing Demo

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace FileWriteDemo
{
class Program
{
static void Main(string[] args)
{
string filepath;
Console.WriteLine("Enter the file path:");
filepath = Console.ReadLine();
FileInfo fobj = new FileInfo(filepath);

if (!fobj.Exists)
{
string content;
Console.WriteLine("\nEnter content to write:");
content = Console.ReadLine();

StreamWriter sw = new StreamWriter(filepath);


sw.Write(content);
sw.Close();

Console.WriteLine("\nWritten successfully!");
}
else
Console.WriteLine("File already exists.");

.NET 4.0 and Visual Studio 2010 Page 194 of 548


Console.Read();
}
}
}

Output:

Application 62: File Reading Demo

using System;
using System.IO;

namespace FileReadDemo
{
class Program
{
static void Main(string[] args)
{
string filepath;
Console.WriteLine("Enter the file path:");
filepath = Console.ReadLine();
FileInfo fobj = new FileInfo(filepath);

if (fobj.Exists)
{
StreamReader sr = new StreamReader(filepath);
string content = sr.ReadToEnd();
Console.WriteLine(content);

sr.Close();
}
else
Console.WriteLine("File not found.");

Console.Read();
}
}
}

.NET 4.0 and Visual Studio 2010 Page 195 of 548


Output:

.NET 4.0 and Visual Studio 2010 Page 196 of 548


Multi Threading
 ―Multi Threading‖ is one of the rich features of .NET applications.
 Using this feature, the user is able to create multi-threaded applications.
 This concept is introduced in VC++. This is also supported by Java.
 Definition of Multi Threading: The ability of an application that maintains multiple
threads at run time.
 Definition of Thread: The thread is a sub process (part of the process). That means it
has some code to execute.
 Advantage of Multi-Threading: Using ―multi threading‖, you can break a complex
task in a single application into multiple threads that execute independently and
simultaneously.
 In other words, ―multi threading‖ is the sub form of ―multi tasking‖.
 Before starting with the implementatin of Multi Threading, you should recollect the
concept of ―Multi-Tasking‖.

Multi Tasking:
 Def: Ability of the OS, that is able to perform more than one task, at-a-time
(simultaneously) is called as ―Multi-Tasking‖.
 As a part of this, OS allocates the CPU clock (CPU capacity) for each task.
Note: Just like multi-tasking, OS allocates the CPU clock for each thread.

Threading Architecture:

.NET Application

OS
Thread 1
CLR
Thread 2

Thread 3
Processor

.NET 4.0 and Visual Studio 2010 Page 197 of 548


Implementation of Multi Threading:
.NET Framework offers a namespace called “System.Threading” for implementation of
multi threading.
Library: System.Threading.Thread
This class object represents a thread.

 Import the API:


using System.Threading;
 Create the Thread Object:
Thread th = new Thread(method_name);
 Start the Thread:
th.Start();

Application 63: Simple Demo on Multi Threading

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace SimpleThreadingDemo
{
class ThreadingDemo
{
private void FirstMethod()
{
for (int i = 1; i <= 300; i++)
Console.Write("i=" + i + " ");
}
private void SecondMethod()
{
for (int j = 1; j <= 300; j++)
Console.Write("j=" + j + " ");
}
public void Display()
{
Thread th1 = new Thread(FirstMethod);
Thread th2 = new Thread(SecondMethod);

th1.Start();
th2.Start();

.NET 4.0 and Visual Studio 2010 Page 198 of 548


}
}
class Program
{
static void Main(string[] args)
{
ThreadingDemo td = new ThreadingDemo();
td.Display();
Console.Read();
}
}
}

Output:

.NET 4.0 and Visual Studio 2010 Page 199 of 548


Thread States

The thread state specifies the current status of the thread. Sometimes, the thread
automatically switches from one state to another state automatically; at some other times, you
can switch its state by using the methods offered by ―Thread‖ class.

The following diagram called ―Thread Life Cycle‖ describes the different states of a
thread.

Thread Life Cycle

Ready

Start()

Running

Automatic Automatic / Sleep()

Sleeping

Suspend()

Resume()
Suspended
Automatic / Abort()
Dead

1. Ready: This is the initial state. The thread object is created.


2. Running: The thread is currently being executed.
3. Sleeping: The thread is temporarily paused. .NET framework offers automatic switching
between ―Running‖ and ―Sleeping‖ states, when other threads are executed.

.NET 4.0 and Visual Studio 2010 Page 200 of 548


4. Suspended: The thread is temporarily suspended (paused). It will be continued, when
you call ―Resume()‖ method.
5. Dead: The thread was closed; it can‘t be restarted or continued.

“Thread”classmethods:

o thobj.Start()
This method starts-up the thread execution.

o Thread.Sleep(mille_sec)
This method puts the thread under ―Sleeping‖ state, up to a certain no. of mille
seconds. When the given no. of mille seconds are completed, automatically the
thread execution will be continued.

o thobj.Suspend()
This is similar to ―Sleep()‖ method, but here, no time limit will be given. That
means whenever the ―Suspend()‖ method is called, the thread will be put under
―Suspended‖ state, until the ―Resume()‖ method is called.

o thobj.Resume()
This is to continue the thread execution that is under ―Suspended‖ state. This
method won‘t work if the thread is not under ―Suspended‖ state.

o thobj.Abort()
This is close the thread execution completely, at any time. Once, if the ―Abort()‖
method is called, the thread can‘t be started or resumed. This is the end of every
thread life cycle.

Application 64: Demo on Thread States

.NET 4.0 and Visual Studio 2010 Page 201 of 548


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadLifeCycleDemo
{
class ThreadingDemo
{
private void FirstMethod()
{
for (int i = 1; i <= 50; i++)
{
Console.Write("i=" + i + " ");
Thread.Sleep(1000);
}
}
private void SecondMethod()
{
for (int j = 1; j <= 50; j++)
{
Console.Write("j=" + j + " ");
Thread.Sleep(1000);
if (j == 20)
th1.Suspend();
else if (j == 30)
th1.Resume();
}
}

Thread th1, th2;

public void Display()


{
th1 = new Thread(FirstMethod);
th2 = new Thread(SecondMethod);
th1.Start();
th2.Start();
}
}
class Program
{
static void Main(string[] args)
{
ThreadingDemo td = new ThreadingDemo();
td.Display();
Console.Read();
}
}
}

.NET 4.0 and Visual Studio 2010 Page 202 of 548


Output:

Anonymous Methods
 This is used to create a method, without any name.
 Syntax:
delegate()
{
//some code
}

Application 65: Demo on Anonymous Methods

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace AnonymousMethodsDemo
{
class ThreadingDemo
{
public void Display(string name)
{
Thread th1 = new Thread(delegate()
{
while (true)
{
Console.WriteLine("Welcome to " + name);
Thread.Sleep(500);
}
});
th1.Start();
}
}

.NET 4.0 and Visual Studio 2010 Page 203 of 548


class Program
{
static void Main(string[] args)
{
string name;
Console.WriteLine("Enter your name:");
name = Console.ReadLine();

ThreadingDemo td = new ThreadingDemo();


td.Display(name);

Console.Read();
}
}
}

Output:

.NET 4.0 and Visual Studio 2010 Page 204 of 548


Speech Translation
 This is to translate the text as speech.
 This makes us to listen a voice from the speakers that reads some specified text.
 Library: System.Speech.Synthesis.SpeechSynthesizer
 This class used to speak the required text through the speakers.

Implementation:
 Create the object of ―SpeechSynthesizer‖ class:
SpeechSynthesizer ss = new SpeechSynthesizer();
 Set the volume (1 to 100):
ss.Volume = n;
 Set the speed of speaking (-10 to +10):
ss.Rate = n;
 Change the voice gender and age:
ss.SelectVoiceByHints(VoiceGender.xxxx, VoiceAge.xxxx);
 Speak the text:
ss.SpeakAsync(―message‖);

Application 66: Demo on Speech Translation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Speech.Synthesis;

namespace SpeechTranslationDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter text to speak:");
string TextToSpeak = Console.ReadLine();

SpeechSynthesizer ss = new SpeechSynthesizer();

ss.Volume = 100; //1 to 100

.NET 4.0 and Visual Studio 2010 Page 205 of 548


ss.Rate = -3; // -10 to +10

ss.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Child);

ss.SpeakAsync(TextToSpeak);

Console.Read();
}
}
}

Output:

Memory Management
 Every application requires some amount of memory to run.
 That memory will be allocated in the primary memory (RAM).
 For every variable, individual memory will be allocated.
 The RAM contains two memory locations.
o Stack RAM
o Heap
 Now, we need to understand, where the
application memory is getting allocated in the Stack
RAM.
 The storage area in the RAM depends on the
―data type‖ that you are using for declaring the
Heap
variable in the program.
 The data types are two types in C#
o Value Types
o Reference Types

.NET 4.0 and Visual Studio 2010 Page 206 of 548


1) Value Types:
 Def: Whenever a data type is designed based on a structure, it can be called as
―Value Type‖.
 All the standard data types built based on structures.
 You can see the list of data types and respective structures here:

Data Type Structure Name


sbyte System.SByte
byte System.Byte
short System.Int16
ushort System.UInt16
int System.Int32
uint System.UInt32
long System.Int64
ulong System.UInt64
float System.Single
double System.Double
decimal System.Decimal
bool System.Boolean
char System.Char

 So finally, the following are value types in C#:


1) Structures
2) Enumerations
3) sbyte, byte, short, ushort, int, uint, long, ulong, float, double, decimal, bool,
char, decimal, DateTime

 Note 1: The value types can‘t be inherited.


 Note 2: All the value types (structures and enumerations), are derived from a
common base class called ―System.ValueType‖.

2) Reference Types:
 Def: Whenever a data type is designed based on a class, it can be called as
―Reference Type‖.
 The following are the reference types in C#:
1) Classes
2) Interfaces
3) String, Object
 Reference types support inheritance.

.NET 4.0 and Visual Studio 2010 Page 207 of 548


 The ―Value Type‖ variables will be allocated in the ―Stack‖.
 The ―Reference Type‖ variables (objects) will be allocated in the ―Heap‖.

The “System.Object” class:


 This class acts as super class for all other classes (pre-defined / user-defined
classes).
 So, it can be called as ―Ultimate base class‖.

Object

ValueType

Structures Enumerations Classes

 The ―Object‖ class offers the following methods.


Method Description
Equals(value) Checks the equality of the value of the object with the given
argument value. If both are equal, then returns ―true‖, otherwise
returns ―false‖.
Ex:
MyObj.Equals(AnotherObject);
In this example, ―MyObj‖ will be compared with ―AnotherObject‖.
GetType() Gets the name of the class, for which, it is declared.
Ex:
MyObj.GetType();
ToString() Converts the value of the object and returns it.
Ex:
MyObj.ToString();
In this example, the value of ―MyObj‖ will be converted as string
type, and that string value will be returned.

.NET 4.0 and Visual Studio 2010 Page 208 of 548


Application 67: Demo on System.Object class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ObjectClassMethods
{
class Program
{
static void Main(string[] args)
{
int x = 100;
int y = 100;

Console.WriteLine("x is " + x);


Console.WriteLine("y is " + y);

Console.WriteLine();

if (x.Equals(y))
Console.WriteLine("x is equal to y");
else
Console.WriteLine("x is not equal to y");

Console.WriteLine("\nx is the type of " + x.GetType());

string s = x.ToString();
Console.WriteLine("\nThe integer value after converting into string is: " + s);

Console.Read();
}
}
}

Output:

.NET 4.0 and Visual Studio 2010 Page 209 of 548


Garbage Collector:
 This is one of the components of CLR (Common Language Runtime).
 This component is dedicated for de-allocating the un-used memory of the
application, automatically.
 This uses ―Mark and Compact‖ algorithm for clearing the un-used memory.
 Mark: Markup the un-used objects and push those objects towards up.
 Compact: Clear the marked objects memory.

Object 1

Object 2

Object 3

Object 4

The Memory Heap

Note: The above functionality is in-built in ―Garbage collector‖ component. Anyhow, there is a
provision for the programmer to command the garbage collector to perform ―garbage collection‖
at run time, programmatically. Then use the following method from ―System.GC‖ class.
Syn: System.GC.Collect();

.NET 4.0 and Visual Studio 2010 Page 210 of 548


LINQ
 LINQ (pronounced link) stands for ―Language Integrated Query‖.
 This concept is introduced in .NET Framework 3.5.
 This is a ―query writing technology‖.
 This is most useful while working large amount of data in the live projects.

Introduction:

 In relational database system, data is organized in the form of tables, on which you can
write SQL queries to retrieve the required data according to the requirement in the
application.
 But you can‘t write a query on the non-database data, which in the form of objects in the
application. There, you can write the queries using the new concept called ―LINQ‖.
 You can write queries on arrays, objects, databases and XML using LINQ.
 Note: Before writing the LINQ queries, you should import the ―System.Linq‖
namespace..

The following example shows a small demo on LINQ:

Application 68: LINQ to Arrays

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQtoArrayDemo
{
class Program
{
static void Main(string[] args)
{
//data source
int[] numbers = { 2, 12, 10, 5, 15, 4, 62 };

//ling query
IEnumerable<int> result = from n in numbers where n <= 10 select n;

.NET 4.0 and Visual Studio 2010 Page 211 of 548


//output
foreach (var x in result)
Console.WriteLine(x);

Console.Read();
}
}
}

Output:

In the above application, the array contains few numbers. After executing the query, you
got only the numbers, which are less than 10. In this manner, you can execute the queries on
data sets (after learning ADO.NET) also.

LINQ Syntax:

from… in… let … where … orderby … select… group by …

 The above syntax consists of 7 clauses.


 from clause
 in clause
 let clause
 where clause
 orderby clause
 select clause
 group by clause

 Mandatory clauses:
 from clause
 in clause
 select clause

Def of Clause: A part of the query.

.NET 4.0 and Visual Studio 2010 Page 212 of 548


Understanding Clauses:

1. from clause: This is used to specify the iteration variable name. This acts as alias name
for the data source.
2. in clause: This is used to specify the main data source for the query.
3. let clause (optional): This is used to declare a new identifier with a value, that is to be
used during the query execution.
4. where clause (optional): This is most frequently used optional clause, using which
you can specify the condition in the query.
5. orderby clause (optional): This is used to specify the sorting expression if required.
6. select clause: This is used to specify the object, which is required in the query results.
7. group by (optional): This is similar to ―group by‖ clause in SQL. This retrieves grouped
data, based on a column.

Note: The result of a LINQ query should be assigned into a IEnumerable<data type> type
variable. IEnumerable is an interface.

Library: System.Collections.Generic.IEnumerable

Application 69: LINQ to Objects

Student.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQtoObjectsDemo
{
class Student
{
//fields
public int StudentID;
public string Name;
public string Course;
public int Marks;

.NET 4.0 and Visual Studio 2010 Page 213 of 548


//constructor
public Student(int StudentID, string Name, string Course, int Marks)
{
this.StudentID = StudentID;
this.Name = Name;
this.Course = Course;
this.Marks = Marks;
}
}
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQtoObjectsDemo
{
class Program
{
static void Main(string[] args)
{
//data source
Student[] stu = { new Student(101, "Prakash", "MBA", 765),
new Student(102, "Pradeep", "MBA", 471),
new Student(103, "Pushpa", "Msc", 590),
new Student(104, "Purna", "MCA", 223),
new Student(105, "Purnima", "MCA", 450)};

//linq query with where clause


IEnumerable<Student> result1 = from s in stu where s.Course == "MCA" select s;
Console.WriteLine("MCA Students:");
foreach (Student r in result1)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " +
r.Marks);

//linq query with compound where clause


IEnumerable<Student> result2 = from s in stu where s.Name.EndsWith("a") &&
s.Marks>=400 && s.Marks<=600 select s;
Console.WriteLine("\nStudents whose name ends with 'a', and marks is >=400 and
<=600:");
foreach (Student r in result2)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " +
r.Marks);

.NET 4.0 and Visual Studio 2010 Page 214 of 548


//linq query with let and where clauses
IEnumerable<Student> result3 = from s in stu let avg = s.Marks / 10 where avg < 35
select s;
Console.WriteLine("\nFailed Students:");
foreach (Student r in result3)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks);

//linq query with orderby clause


IEnumerable<Student> result4 = from s in stu orderby s.Marks select s;
Console.WriteLine("\nStudents (sort on marks):");
foreach (Student r in result4)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks);

//linq query with orderby clause (descending)


IEnumerable<Student> result5 = from s in stu orderby s.Marks descending select s;
Console.WriteLine("\nStudents (sort on marks - descending):");
foreach (Student r in result5)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks);

//linq query with group clause


IEnumerable<IGrouping<string,Student>> result6 = from s in stu group s by s.Course;
Console.WriteLine("\nStudents with grouping:");
foreach (IGrouping<string, Student> StuGrp in result6)
{
Console.WriteLine(StuGrp.Key + ":");
foreach (Student r in StuGrp)
Console.WriteLine(" " + r.StudentID + ", " + r.Name + ", " + r.Course + ", " +
r.Marks);
}

Console.Read();
}
}
}

.NET 4.0 and Visual Studio 2010 Page 215 of 548


Output:

LINQ with Lambda Expressions


 LINQ queries can be written in two syntaxes:
1) General Query Syntax
2) Lambda Expression Syntax
 The previously written applications are written with ―General Query Syntax‖.
 Syntax for Lambda Expression:
DataSource.Clause(DataAliasName => Expression)
 Ex:
stu.Where(s => s.Marks < 300)

goes to

.NET 4.0 and Visual Studio 2010 Page 216 of 548


Application 70: LINQ with Lambda Expressions

Student.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQtoObjectsDemo
{
class Student
{
//fields
public int StudentID;
public string Name;
public string Course;
public int Marks;
//constructor
public Student(int StudentID, string Name, string Course, int Marks)
{
this.StudentID = StudentID;
this.Name = Name;
this.Course = Course;
this.Marks = Marks;
}
}
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQwithLambaExpressions
{
class Program
{
static void Main(string[] args)
{
//data source
Student[] stu = { new Student(101, "Prakash", "MBA", 765),
new Student(102, "Pradeep", "MBA", 471),
new Student(103, "Pushpa", "Msc", 590),
new Student(104, "Purna", "MCA", 223),
new Student(105, "Purnima", "MCA", 450)};

.NET 4.0 and Visual Studio 2010 Page 217 of 548


//linq query with where clause
IEnumerable<Student> result1 = stu.Where(s => s.Course == "MCA");
Console.WriteLine("MCA Students:");
foreach (Student r in result1)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks);

//linq query with compound where clause


IEnumerable<Student> result2 = stu.Where(s => s.Name.EndsWith("a") && s.Marks
>= 400 && s.Marks <= 600);
Console.WriteLine("\nStudents whose name ends with 'a', and marks is >=400 and
<=600:");
foreach (Student r in result2)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks);

//linq query with orderby clause


IEnumerable<Student> result4 = stu.OrderBy(s => s.Marks);
Console.WriteLine("\nStudents (sort on marks):");
foreach (Student r in result4)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks);

//linq query with orderby clause (descending)


IEnumerable<Student> result5 = stu.OrderByDescending(s => s.Marks);
Console.WriteLine("\nStudents (sort on marks - descending):");
foreach (Student r in result5)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks);

//linq query with group clause


IEnumerable<IGrouping<string, Student>> result6 = stu.GroupBy(s => s.Course);
Console.WriteLine("\nStudents with grouping:");
foreach (IGrouping<string, Student> StuGrp in result6)
{
Console.WriteLine(StuGrp.Key + ":");
foreach (Student r in StuGrp)
Console.WriteLine(" " + r.StudentID + ", " + r.Name + ", " + r.Course + ", " +
r.Marks);
}

Console.Read();
}
}
}

.NET 4.0 and Visual Studio 2010 Page 218 of 548


Output:

.NET 4.0 and Visual Studio 2010 Page 219 of 548


Exception Handling
 This is one of the major features of OOP languages like C++, VC++, VB.NET, C#.NET,
Java etc.
 Def: "The process of handling the run time exceptions" is called as "Exception
handling".
Note: Exception = Run time error

Types of Errors:
1) Compile Time Errors: The errors occurred after compiling the program, are called as
―compile time errors‖.
2) Run Time Errors: The errors occurred during the execution of the program, are called
as ―run time errors‖.

Overview of Exception Handling:


 The exception may occur at run time, based on the mistake of the user / programmer /
system problem also.
 When exception is raised, automatically it leads to "abnormal application termination".
 The cause of the exception may be anything; the project developer should take care
about the exceptions.
 As a part of this exception handling, the programmer has to display "particular error
message" to the user.
 Purpose of Exception Handling: To avoid "abnormal application termination", even
though exception occurs.

Types of Application Termination:

 Normal Application Termination: Whenever the program execution controls executes


all the statements in the program and reaches to end of the code, the application will be
terminated automatically. It can be called as ―Normal Application Termination‖.

 Abnormal Application Termination: Whenever an exception occurred at run time,


the application will be terminated automatically. It can be called as ―Abnormal Application
Termination‖.

.NET 4.0 and Visual Studio 2010 Page 220 of 548


If the application was terminated abnormally, if will be most inconvenience for the user. So being
a programmer, you are responsible to avoid that kind of abnormal application termination, even
though exception is occurred at run time.

A small demo on exceptions:

Application 71: Simple Demo on Exceptions

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExceptionDemo1
{
class Program
{
static void Main(string[] args)
{
string[] Cities = { "Vijayawada", "New Delhi", "Banglore", "Hyderabad" };
Console.WriteLine(Cities[3]);
Console.WriteLine(Cities[4]);
Console.Read();
}
}
}

In the above code, the highlighted line contains an error, because it is trying to access an
array element which is in out of range of the array. So, it leads to abnormal application
termination at run time.

.NET 4.0 and Visual Studio 2010 Page 221 of 548


Then screen looks like this:

To avoid this, we have to implement exception handling for this code.

Syntax of Exception Handling:

try
{
---------------------;
---------------------;
---------------------;
---------------------;
}
catch (Exception ex)
{
--------------------;
--------------------;
}
finally
{
--------------------;
--------------------;
}

.NET 4.0 and Visual Studio 2010 Page 222 of 548


In the above syntax, we can observe to blocks.
1) try block
2) catch block
3) finally block

1) try block:
 The try block contains the actual code, which
is to be executed. try
{
 After every try block, there should catch
---------------------;
block without fail. ---------------------;
 The system tries to execute the code in the ---------------------;
---------------------;
try block. }
 During the execution, if any exception
occurs, then the execution control automatically goes to catch block.
 At the same time, the ―try‖ block throws the exception to the catch block in the
form of an object. That object is called as ―exception object‖.

2) catch block:
 This is also known as ―error handler‖.
 This is followed by the try block.
 The catch block will be executed if any
exception is occurred during the execution catch (Exception ex)
of try block. {
--------------------;
 The catch block contains necessary code --------------------;
which displays an error message to the }
user.
 This receives the exception, thrown by the try block, in the form of an object. In
the following syntax, ―ex‖ is the ―Exception object‖. The ―Exception‖ is the class
for the exception object.
 Library: System.Exception

.NET 4.0 and Visual Studio 2010 Page 223 of 548


3) finally block:
finally
 This block will be executed automatically and
{
compulsorily, after executing ―try block‖ / ―catch --------------------;
block‖. --------------------;
}
 That means even though exception is raised or
not raised, the ―finally‖ block will be executed without fail.
 This is optional block. You can write the exception handling syntax only with
―try‖ and ―catch‖ blocks, without ―finally‖ block.

Application 72: Demo Exception Handling

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExceptionDemo2
{
class Program
{
static void Main(string[] args)
{
try
{
string[] Cities = { "Vijayawada", "New Delhi", "Banglore", "Hyderabad" };
Console.WriteLine(Cities[3]);
Console.WriteLine(Cities[4]);
}
catch (Exception ex)
{
Console.WriteLine("Error occurred.");
}
finally
{
Console.WriteLine("This is 'finally' block.");
Console.Read();
}
}
}
}

.NET 4.0 and Visual Studio 2010 Page 224 of 548


Output:

Types of Catch Block Messages:

Already we have discussed that the catch block generates an error message, when an exception
occurs. That error message can be of two types.
1. User Defined Message
2. System Defined Message

1. User Defined Message: Your own message can be written.


Ex: ―Error Occurred.‖
―Operation is not successful‖.
etc.
2. System Defined Message: The system provides the description of the error, so that
you can print that on the output directly. To access the system defined message, you can
use the exception object as follows:
Syn: ex.Message
Example:

catch (Exception ex)


{
Console.WriteLine(ex.Message);
}

.NET 4.0 and Visual Studio 2010 Page 225 of 548


Exceptional Classes

 Already you know that C# recognizes the exception as an object.


 To declare the exception object, we have used a class called ―System.Exception‖, in
the previous examples.
 The ―Exception‖ class recognizes any type of exceptions. In order to catch the particular
type of error, C# provides other exceptional classes. Some of them are given here.

Sl. No Exceptional Class Description


Occurs when a large value is

1 System.OverflowException assigned to a variable, which is not


fit in that variable.
Occurs when the casting is failed
System.FormatException /
2 from one data type of another data
System.InvalidCastException
type.
Occurs when any number is divided
3 System.DivideByZeroException
by 0.
Occurs when an index is accessed in
4 System.IndexOutOfRangeException
out of range.
Occurs when there is no sufficient

5 System.InsufficientMemoryException memory in RAM for the execution of


the application.
Occurs when a non-existing file is
6 System.IO.FileNotFoundException
accessed.
Occurs when a non-existing directory
7 System.IO.DirectoryNotFoundException
is accessed.
Occurs when any error occurred
8 System.IO.FileLoadException
during the opening of any file.
Occurs when any error occurred
9 System.IO.IOException
during file read or writing.
Occurs when any error occurred
10 System.Threading.ThreadInterruptedException
during the execution of the thread.

.NET 4.0 and Visual Studio 2010 Page 226 of 548


Occurs when any error occurred
11 System.Threading.ThreadStartException
while starting the thread.
Occurs when any error occurred

12 System.InvalidOperationException while opening the database


connection.
Occurs when any error occurred

13 System.Data.OleDb.OleDbException while performing query or non-query


transactions on OleDb databases.
Occurs when any error occurred

14 System.Data.SqlClient.SqlException while performing query or non-query


transactions on SqlServer database.
Occurs when you try to run the

15 System.EntryPointNotFoundException application, without defining any


entry point (main() method).
Occurs when the system has an

16 System.InvalidTimeZoneException invalid time zone setting the date &


time settings.

Note: Based on the situation, the above specified exception classes could be used.

Application 73: Demo on Exceptional Classes

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExceptionDemo3
{
class Program
{
static void Main(string[] args)
{
try
{
int n1, n2, n3;

Console.WriteLine("Enter first value:");


n1 = Convert.ToInt32(Console.ReadLine());

.NET 4.0 and Visual Studio 2010 Page 227 of 548


Console.WriteLine("Enter second value:");
n2 = Convert.ToInt32(Console.ReadLine());

n3 = n1 / n2;

Console.WriteLine("Result is: " + n3);


}
catch (DivideByZeroException ex)
{
Console.WriteLine("Can't divide the number with zero.");
}
Console.Read();
}
}
}

Output:

Note: If you want to handle more than one type of exception for the same try block, then you
need to write multiple catch blocks.

Application 74: Demo on Multiple Catch Blocks

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExceptionDemo4
{
class Program
{
static void Main(string[] args)
{
try
{
int n1, n2, n3;

Console.WriteLine("Enter first value:");


n1 = Convert.ToInt32(Console.ReadLine());

.NET 4.0 and Visual Studio 2010 Page 228 of 548


Console.WriteLine("Enter second value:");
n2 = Convert.ToInt32(Console.ReadLine());

n3 = n1 / n2;
Console.WriteLine("Result is: " + n3);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("This is divide by zero exception.");
}
catch (OverflowException ex)
{
Console.WriteLine("This is overflow excpetion.");
}
catch (FormatException ex)
{
Console.WriteLine("This is invalid cast exception.");
}
Console.Read();
}
}
}

Output:

The“EventLog”

 ―EventLog‖ is a service, offered by Microsoft Windows.


 It is used to store the exceptions / warnings / any messages permanently, even though
the application is closed.
 Let us imagine you have done a live project and issue it to the client.
 At run time there may be so many exceptions. But after few days, you went to the client
location, and want to know what kind of run time errors were coming in your application.
 Then no information is available with you.
 So, in this case, you require some thing, that stores the exceptions information
automatically, for further information, which helps you while you want to debug your
application and develop a next version.
 That kind of service is ―EventLog‖.
 To open ―EventLog‖ and view the current events:
Start – Control Panel – Administrative Tools – Event Viewer.

.NET 4.0 and Visual Studio 2010 Page 229 of 548


Writing a new entry programmatically:
System.Diagnostics.EventLog.WriteEntry("project name", ―message‖, EventLogEntryType.Error);

Application 75: Demo on Event Log

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace EventLogDemo
{
class Program
{
static void Main(string[] args)
{
try
{
string filename = "c:\\sample.txt";
StreamReader sr = new StreamReader(filename);

string content = sr.ReadToEnd();


Console.WriteLine("The file content is:\n");
Console.WriteLine(content);
}
catch (Exception ex)
{
string EventMsg = ex.Message + "\n\n" + ex.StackTrace;
EventLog.WriteEntry("My Sample Project 1.0", EventMsg,
EventLogEntryType.Error);
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("Press any key to exit..");
Console.Read();
}
}
}
}

.NET 4.0 and Visual Studio 2010 Page 230 of 548


Output:

Debugging
 Bug: An error.
 Debugging: Removing the bugs.

.NET offers more features for debugging. To start with the .NET application debugging, you
should create the break points.

Break Points

i) Definition: A break point is a point in the program, where the application execution
control pauses until you press ―F10‖ key. In the code, that line is highlighted with red
color.

ii) Creating a break point: Just click on the left side margin of the required line.

.NET 4.0 and Visual Studio 2010 Page 231 of 548


iii) Running the Application with Break Points: Just press ―F5‖ key. The
application will be executed normally. But whenever the execution control reaches to
the break point line, automatically the execution will be paused and the break point
line will be highlighted with yellow color. To continue with the execution to the next
statement, press “F10” key.

iv) Observing the values of variables or objects: While you are executing the
application with break points, to know the current value of any variable or object,
just place the mouse pointer over it.

Application 76: Demo on Break Points

.NET 4.0 and Visual Studio 2010 Page 232 of 548


Immediate window

 The ―Immediate‖ window resides at bottom side of Visual Studio IDE. It will automatically
appear at run time. If not, press ―Ctrl + Alt + I‖.
 This window is used to know the current values of the required variables, objects or data
members, which is not possible to find the value by just placing the mouse pointer over
it.

.NET 4.0 and Visual Studio 2010 Page 233 of 548


Application 77: Demo on Immediate window

Locals window

 It automatically displays all the current local variables along with their values.
 To open this window, while running the application, get into the Visual Studio and press
―Ctrl+D‖ and the ―L‖.

.NET 4.0 and Visual Studio 2010 Page 234 of 548


Assemblies

 Def: An assembly is the container of compiled code of .NET applications.


 It contains the code in MSIL (Microsoft Intermediate Language) language.
 At run time, it will be compiled by CLR‘s JIT compiler into machine language.
 The assembly file (with .exe or .dll extension) will be generated in the ‖project folder‖ \
―bin‖ folder, after compilation.

Types of Assemblies (based on extension):

1. Executable Assemblies / Process Assemblies / Private Assemblies (with .EXE


extension)
 This is generated with
A. Console Applications
B. Smart Device Applications
C. Windows Applications
 These files are ready for execution. You can execute those by simply double clicking.
 Limitation: The code in this assembly is not accessible from other projects.

2. Library Assemblies / Re-usable Assemblies / Shared Assemblies (with .DLL


extension)
 This is generated with
. Class Library
B. Windows Forms Control Library
 These are non-executable files.
 Advantage: The code is this assembly is accessible from other projects.

Overviewof“ClassLibrary”Project

 A ―class library‖ project is meant for the development of ―Shared Assemblies‖.


 The shared assemblies are re-usable in other applications also.

.NET 4.0 and Visual Studio 2010 Page 235 of 548


 That means the class library‘s code is re-usable in other applications, whenever required.
 Class library project contains only user-defined classes.
 Whenever the class library project is compiled, a library assembly file (with .DLL
extension) will be generated in the ―bin\Debug‖ folder.
 The class library project can‘t be executed directly unlike console applications, windows
applications etc.

Global Assembly Cache (GAC): All the shared assemblies should be saved in the GAC. GAC
offers the following advantages.
 Unique identification of the shared assemblies.
 Avoids the DLL hell (replacement of an assembly related to one application, by another
application).
 Faster accessibility.

.NET 4.0 and Visual Studio 2010 Page 236 of 548


To view the currently installed assemblies in the GAC, open the following folder.
C:\windows\assembly
The above folder is able to contain multiple dll files with same name, with different
versions.

Strong Name Keys (SNK): The ―strong name key‖ is a file, which acts as a unique
identifier, for the shared assemblies, stored in the GAC. In other words, GAC recognizes the
assembly with this strong name only.

Implementation Steps of Shared Assemblies

1. Create a Class Library Project.


 Create a new ―Class Library‖ project.
 Write the required code in the project.

2. Create a strong name key.


 Right click on the project in the ―Solution Explorer‖ and choose ―Properties‖.
 In the project properties, select the check box ―Sign the assembly‖.
 In the ―Choose a strong name key file‖ drop down, select ―<New>‖ option.
 In the ―Create strong name key‖ dialog box, enter the name of the strong name key
file.
 If password security is not required, uncheck the ―Protect my key file with a
password‖ checkbox.
 Click on OK.

3. Customize the “Assembly Information” (AssemblyInfo.cs).


 This is optional step.
 To change the additional details of the assembly like displayed name, version,
company, copy right, description etc., open “AssemblyInfo.cs” file from the
―Properties‖ folder in the Solution Explorer.

.NET 4.0 and Visual Studio 2010 Page 237 of 548


4. Generate the DLL File.
 Build the class library project.
 Then the ―.dll‖ file will be generated in the ―bin\debug‖ folder of your class library
project.

5. Write the assembly into GAC (Global Assembly Cache).


 Open the following folder.
C:\Windows\Assembly
 Drag and drop the ―.DLL file‖ from ―bin\Debug‖ folder into the
―c:\windows\assembly‖ folder.
 After dragging, the name of your shared assembly will appear in the existing list.
 Now, the shared assembly is ready. The rest of your work involved with the usage of
the shared assembly.

6. Invoke the Shared Assembly.


 Create the executable project (Console application / windows application).
 Click on ―Project‖ – ―Add Reference‖.
 Click on ―Browse‖ tab.
 Open the class library project‘s ―bin\Debug‖ folder.
 Select the ―dll file‖ and click on OK.
 Then the reference of the selected shared assembly will be added to the current
project.
 Then you can construct objects for the required class in the class library and perform
required activities on that.

Demo on Shared Assemblies

Application 78: Demo on Shared Assemblies

In this example,
Class Library Project: SharedAssemblyLibrary
Console Application Project: SharedAssemblyDemo

.NET 4.0 and Visual Studio 2010 Page 238 of 548


1. Create a Class Library Project.
 Open Visual Studio 2008.
 Click on ―File‖ – ―New‖ – ―Project‖.
 Select the language as ―Visual C#‖ and project template as ―Class Library‖.
 Enter the name as ―SharedAssemblyLibrary‖.
 Click on OK. It creates a new class library project. Initially it contains a new class
called ―class1‖.
 In the solution explorer, rename the ―class1.cs‖ as “MyLibraryClass.cs”.
 Then type the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SharedAssemblyLibrary
{
public class MyLibraryClass
{
public bool IsValidLogin(string Username, string Password)
{
if (Username == "system" && Password == "manager")
return true;
else
return false;
}
}
}

2. Create a strong name key.


 Right click on the
project in the
―Solution Explorer‖
and choose
―Properties‖.
 In the project
properties, select
the check box ―Sign
the assembly‖.

Page 240 of 553


 In the ―Choose a strong name key file‖ drop down, select ―<New>‖ option.
 In the ―Create strong name key‖ dialog box, enter the name of the strong name key
file as “MyKeyFile”.
 Uncheck the ―Protect my key file with a password‖ checkbox.
 Click on OK.

3. Customize the “Assembly Information” (AssemblyInfo.cs).


 Change the assembly version as “1.5.0.0”.

4. Generate the DLL File.


 Build the class library project by clicking on ―Build‖ menu – ―Build Solution‖.

5. Write the assembly into GAC (Global Assembly Cache).


 Open the following folder.
C:\Windows\Assembly
 Drag and drop the “SharedAssemblyLibrary.DLL‖ file from ―bin\Debug‖ folder
into the ―c:\windows\assembly‖ folder.

6. Invoke the Shared Assembly.


 Create a new Console Application. Name: SharedAssemblyDemo
 Click on ―Project‖ – ―Add Reference‖.
 Click on ―Browse‖ tab.
 From the class library project‘s
―bin\Debug‖ folder, select the
“SharedAssemblyLibrary.dll‖
file and click on OK. Then the
.dll file reference will be added.

Page 241 of 553


 Enter the code as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharedAssemblyLibrary;

namespace SharedAssemblyDemo
{
class Program
{
static void Main(string[] args)
{
MyLibraryClass mlc = new MyLibraryClass();

string Username, Password;


Console.Write("Enter Username: ");
Username = Console.ReadLine();
Console.Write("Enter Password: ");
Password = Console.ReadLine();

bool result = mlc.IsValidLogin(Username, Password);


if (result == true)
Console.WriteLine("\nLogin successful!");
else
Console.WriteLine("\nInvalid Username / Password!");

Console.Read();
}
}
}

Output:

Page 242 of 553

You might also like