c#.net material
DESCRIPTION
C#.Net MaterialTRANSCRIPT
-
.NET 4.0 and Visual Studio 2010 Page 1 of 548
D. HARSHA VARDHAN
MMiiccrroossoofftt ..NNEETT FFrraammeewwoorrkk 44..00
AAnndd
CC##..NNEETT
AAuutthhoorr:: MMrr.. HHaarrsshhaa VVaarrddhhaann
-
.NET 4.0 and Visual Studio 2010 Page 2 of 548
D. HARSHA VARDHAN
.NET Framework 4.0 and Visual Studio 2010
C#.NET Training Program Schedule
Trainer: D. Harsha Vardhan Duration: 50 Hours
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 Statements, Enumerations
Page 60
Hour 9 Arrays, Command Line Arguments Page 74
Chapter III: Object Oriented Programming
Hour 10 Introduction to OOP, Access Modifiers, Principles of OOP, Classes, Objects, Fields, Methods
Page 86
Hour 11 Read-only Fields, Ref parameters, Out parameters, this keyword, Named Parameters
Page 96
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 Overriding
Page 130
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 3 of 548
D. HARSHA VARDHAN
Chapter IV: Utility Programming
Hour 18 Array Class, Math Class, String Class Page 159
Hour 19 DateTime Structure, Random Class, Collections, Collection Initializer, PrintDocument Class
Page 171
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, DomainUpdown, DateTimePicker, MonthCalendar
Page 290
Hour 31 TrackBar, Timer, ProgressBar, MenuStrip, ContextMenuStrip Page 307
Hour 32 ColorDialog, FontDialog, OpenFileDialog, SaveFileDialog, PrintDialog, RichTextBox, NotifyIcon
Page 319
Hour 33 TabControl, TreeView, MDI Applications, ToolStrip, StatusStrip, MessageBox, Adding Controls Programmatically
Page 336
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 4 of 548
D. HARSHA VARDHAN
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, DataRow and DataColumn
Page 416
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, installutil.exe
Page 483
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: FAQs
-
.NET 4.0 and Visual Studio 2010 Page 5 of 548
D. HARSHA VARDHAN
AAnn IInnttrroodduuccttiioonn ttoo ..NNEETT FFrraammeewwoorrkk
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.
Its a Network enabled technologies collection. Thats 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 cant store the data. Thats 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 6 of 548
D. HARSHA VARDHAN
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 todays competitive
programming world.
It offers much advanced security features never before.
Its not a single language; its a collection of multiple languages and multiple
technologies. Thats 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
5. WWF Windows Workflow Foundation
6. AJAX Asynchronous JavaScript And Xml
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
Introduced in .NET 3.0
Introduced in .NET 3.5
-
.NET 4.0 and Visual Studio 2010 Page 7 of 548
D. HARSHA VARDHAN
database related applications, you have another technology called ADO.NET. Bu the
technology doesnt offer any specific rules for writing the programs. But it offers some
library. Thats why; a technology cant 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 8 of 548
D. HARSHA VARDHAN
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
Microsoft
Visual C#.NET Visual Basic.NET Visual C++.NET
Languages from other
vendors
VJ#.NET, Python.NET, 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 9 of 548
D. HARSHA VARDHAN
Superior of all previous languages and technologies:
Microsofts target is to be at the top of all the development technologies
/ languages. Thats 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 Microsofts recommended language for beginners of windows programming.
-
.NET 4.0 and Visual Studio 2010 Page 10 of 548
D. HARSHA VARDHAN
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 Microsofts 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 Microsofts 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 Microsofts database technology.
It offers necessary programming libraries to access the local / server databases.
It is the new version to another Microsofts 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 11 of 548
D. HARSHA VARDHAN
AApppplliiccaattiioonnss ooff ..NNEETT
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.
Doesnt 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 12 of 548
D. HARSHA VARDHAN
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.
Doesnt contain user interface or doesnt 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 13 of 548
D. HARSHA VARDHAN
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 14 of 548
D. HARSHA VARDHAN
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 15 of 548
D. HARSHA VARDHAN
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 16 of 548
D. HARSHA VARDHAN
WWhhaatt yyoouu nneeeedd ttoo lleeaarrnn ..NNEETT
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)
PPrroommiisseess bbyy MMiiccrroossoofftt::
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 cant be
hacked or robbed by others.
-
.NET 4.0 and Visual Studio 2010 Page 17 of 548
D. HARSHA VARDHAN
VVeerrssiioonnss ooff ..NNEETT
.NET Framework Version
Exact Version Number
Date of Release Visual Studio
.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
AAddvvaannttaaggeess ooff ..NNEETT
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 PDAs, 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 18 of 548
D. HARSHA VARDHAN
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 and 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 19 of 548
D. HARSHA VARDHAN
..NNEETT ((vvss)) JJaavvaa Microsofts .NET and SUNs Java are strong competitors.
Similarities
Sl. No
.NET and Java
1 Both of these support to develop console applications, windows applications, web sites, web services etc.
2 Both use their own intermediate language. Java calls it as byte code and .NET 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.
8 Both support Garbage collection, which automatically clears the un-used memory.
9 Both support to develop the applications for small devices like PDAs, mobile phones, smart phones etc.
10 Both offer better security features in their own style.
Differences
Sl. No
.NET Java
1 It is cost effective. Costs more than $700 (nearly Rs. 35,000)
It is open source product, which can be freely downloaded on the Internet.
2 Its a collection of multiple languages Its itself is a language.
3
Its partially platform independent (as .NET applications can run on Windows and LINUX operating
systems)
Its fully platform independent.
4 Offers IDE as Visual Studio by Microsoft.
Doesnt offer any IDE. But other IDEs by other vendors such as Eclipse etc.
5 Offers easiest and fastest application development, which indirectly reduces the cost of the software.
Requires much time for the application development, which indirectly increases the cost of the software.
6 Designing the UI is very much easy with Drag and Drop technique.
UI Design requires much programmers effort and stress.
7 AJAX is implementation is much easy. AJAX is implementation is much time taking process, requires much code to write.
-
.NET 4.0 and Visual Studio 2010 Page 20 of 548
D. HARSHA VARDHAN
..NNEETT FFrraammeewwoorrkk TTyyppeess::
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 21 of 548
D. HARSHA VARDHAN
CCoommppoonneennttss ooff ..NNEETT FFrraammeewwoorrkk
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.
11.. ..NNEETT FFrraammeewwoorrkk CCllaassss LLiibbrraarryy ((FFCCLL))
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 librarys 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 22 of 548
D. HARSHA VARDHAN
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).
NNaammiinngg CCoonnvveennttiioonn
We have to follow these naming conventions for good practice of programming:
11.. FFoorr NNaammeessppaaccee,, CCllaasssseess,, SSttrruuccttuurreess aanndd MMeetthhooddss:: Each world in the name space should be started with upper case character.
Ex: WebControls, Threading, OleDbClient, InitializeComponent() etc.
22.. FFoorr VVaarriiaabblleess aanndd oobbjjeeccttss::
This is programmers 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 23 of 548
D. HARSHA VARDHAN
TThhee ..NNEETT FFrraammeewwoorrkk CCllaassss LLiibbrraarryy ((FFCCLL)) AArrcchhiitteeccttuurree
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 Data Xml Linq Threading IO
Configuration
Printing Forms UI
HtmlControls WebControls
OleDb SqlClient
Text Speech Runtime
Remoting
-
.NET 4.0 and Visual Studio 2010 Page 24 of 548
D. HARSHA VARDHAN
22.. CCoommmmoonn LLaanngguuaaggee RRuunn TTiimmee ((CCLLRR))
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 CLRs JIT (just - in - time) compiles the bytecode into the
processors native code and executes the application.
AAsssseemmbblliieess aanndd MMiiccrroossoofftt IInntteerrmmeeddiiaattee LLaanngguuaaggee ((MMSSIILL))
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 25 of 548
D. HARSHA VARDHAN
TTyyppeess ooff AAsssseemmbblliieess
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:
The following VB.NET 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();
} }
}
Module Module1
Sub Main()
Console.WriteLine(Hello, World!)
Console.ReadLine()
End Sub
End Module
-
.NET 4.0 and Visual Studio 2010 Page 26 of 548
D. HARSHA VARDHAN
The Main method of the C# MSIL looks like this:
The Main method of the VB.NET MSIL looks like this:
Conclusion: The Main method of the VB.NET MSIL looks very similar to that of the C#.NETs
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).
.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
.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
-
.NET 4.0 and Visual Studio 2010 Page 27 of 548
D. HARSHA VARDHAN
TThhee RRTTEE ((RRuunn TTiimmee EEnnvviirroonnmmeenntt)) ooff aa ..NNEETT AApppplliiccaattiioonn
Code in C#.NET
Code in VB.NET Code in another .NET
Language
Just-in Time Compiler
VB.NET Compiler (vbc)
Another Compiler
MSIL Code
Common Language Run Time
C#.NET Compiler (csc)
Native Machine Code
01010101010111010 01010101010111010 01010101010111010 01010101010111010
Operating System
Assembly (.exe)
-
.NET 4.0 and Visual Studio 2010 Page 28 of 548
D. HARSHA VARDHAN
CCoommppoonneennttss ooff CCLLRR
The CLR contains the following components.
Security Manager / Code safety verifier
JIT Compiler
Memory Manager
Garbage Collector
Exception Manager
11.. SSeeccuurriittyy MMaannaaggeerr // CCooddee SSaaffeettyy VVeerriiffiieerr
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 29 of 548
D. HARSHA VARDHAN
22.. JJIITT CCoommppiilleerr
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.
33.. MMeemmoorryy MMaannaaggeerr
The Memory Manager component of CLR, allocates necessary memory for the
variables and objects that are to be used by the application.
44.. GGaarrbbaaggee CCoolllleeccttoorr
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.
55.. EExxcceeppttiioonn MMaannaaggeerr
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 30 of 548
D. HARSHA VARDHAN
IInnttrroodduucciinngg VViissuuaall SSttuuddiioo
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 31 of 548
D. HARSHA VARDHAN
-
.NET 4.0 and Visual Studio 2010 Page 32 of 548
D. HARSHA VARDHAN
Then the screen appears like this:
-
.NET 4.0 and Visual Studio 2010 Page 33 of 548
D. HARSHA VARDHAN
Finally, Visual Studio 2010 will be opened. The initial screens looks like this:
SSyysstteemm RReeqquuiirreemmeennttss ooff VViissuuaall SSttuuddiioo 22000088
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 34 of 548
D. HARSHA VARDHAN
Hard disk free space:
4.2 GB (on system drive ( C: ))
Internet Connection (optional)
(To get latest news and updates from Microsofts web site)
SSyysstteemm RReeqquuiirreemmeennttss ooff VViissuuaall SSttuuddiioo 22001100
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 Microsofts web site)
-
.NET 4.0 and Visual Studio 2010 Page 35 of 548
D. HARSHA VARDHAN
GGeettttiinngg SSttaarrtteedd wwiitthh VViissuuaall SSttuuddiioo 22001100
II)) OOppeenniinngg VViissuuaall SSttuuddiioo 22001100
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 36 of 548
D. HARSHA VARDHAN
IIII)) TThhee VViissuuaall SSttuuddiioo 22001100 BBaassiiccss
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:
Namespace: Its 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 cant be defined individually, without a namespace. In .NET, all of the
classes related one application should be defined with a user defined namespace.
class class1
{
int mydatamember;
void mymethod()
{
}
}
-
.NET 4.0 and Visual Studio 2010 Page 37 of 548
D. HARSHA VARDHAN
Ex:
IIIIII)) CCrreeaattiinngg aa nneeww pprroojjeecctt
To create a new project in Visual Studio, follow the steps given below.
Open Microsoft Visual Studio 2010.
Click on File New Project.
namespace MyApplication
{ class class1 {
} class class2 {
}
}
-
.NET 4.0 and Visual Studio 2010 Page 38 of 548
D. HARSHA VARDHAN
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 39 of 548
D. HARSHA VARDHAN
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.
IIVV)) PPrroojjeecctt DDiirreeccttoorryy SSttrruuccttuurree
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 40 of 548
D. HARSHA VARDHAN
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.
Solution Folder:
Project Folder Solution File
-
.NET 4.0 and Visual Studio 2010 Page 41 of 548
D. HARSHA VARDHAN
Project Folder:
bin: This folder contains the EXE file after compiling the project.
obj: This folder contains 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 42 of 548
D. HARSHA VARDHAN
CCoommppoonneennttss ooff VViissuuaall SSttuuddiioo IIDDEE
In this section, we make a closer look to the IDE offered by Visual Studio.
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.
Menu Bar Tool Bars Form Designer Solution Explorer
Toolbox Properties window
Tabs
-
.NET 4.0 and Visual Studio 2010 Page 43 of 548
D. HARSHA VARDHAN
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.
VV)) CCrreeaattiinngg CCoonnssoollee AApppplliiccaattiioonnss
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 44 of 548
D. HARSHA VARDHAN
Then enter the project name and location (with your choice) and click on OK.
-
.NET 4.0 and Visual Studio 2010 Page 45 of 548
D. HARSHA VARDHAN
C#.NET
OOvveerrvviieeww
Its 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#.
FFiillee EExxtteennssiioonnss iinn CC##
Project File Extension: .csproj (means C Sharp Project)
Code File Extension: .cs (means C Sharp)
BBaassiicc TTeerrmmiinnoollooggyy iinn CC##
Statement: Its a line in the program.
--------------;
Keyword: Its a reserved word, which has some pre-defined meaning. Ex: void, class,
struct, using, while, do, for, if, else etc.
Data type: Its 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: Its a named memory location, which contains a particular type value and
which value can be changed during the program execution.
Constant: Its a fixed value, which value cant be changed during the program
execution. Ex: 1, 10, a, abcd.
Operator: Its a symbol, which performs some operation. Ex: +, -, *, /, ++ etc.
Condition: Its an expression, which can have a result (True / False).
data_type variable_name;
-
.NET 4.0 and Visual Studio 2010 Page 46 of 548
D. HARSHA VARDHAN
Array: Its a collection of multiple values, of same data type.
Enumeration: Its a collection of multiple constants. For each constant, one integer
value will be associated automatically, starting from 0.
Class: Its a collection of fields, properties and methods (member functions).
Object: Its 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:
Field / Data Member: Its a variable, declared inside of the class.
Property: Its 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. Its 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: Its a collection of few classes. A namespace can also contain sub
namespaces.
SSaammppllee AApppplliiccaattiioonn DDeevveellooppmmeenntt iinn CC##
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:
class { //fields //properties //methods }
classname objname = new classname();
(x == y)
-
.NET 4.0 and Visual Studio 2010 Page 47 of 548
D. HARSHA VARDHAN
To run the application, simply press F5 key on the keyboard. Then the application will
be executed and output will be as follows.
Application 1: A simple C# program
-
.NET 4.0 and Visual Studio 2010 Page 48 of 548
D. HARSHA VARDHAN
AA cclloosseerr llooookk aatt tthhee ssyynnttaaxx
11.. IImmppoorrttiinngg sseeccttiioonn:: 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;
Importing section Namespace Declaration Class Declaration
Main() method
-
.NET 4.0 and Visual Studio 2010 Page 49 of 548
D. HARSHA VARDHAN
using System.IO;
using System.Data;
etc.
22.. NNaammeessppaaccee ddeeccllaarraattiioonn:: 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.
22.. CCllaassss ddeeccllaarraattiioonn:: 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 cant
change it.
A startup class nothing but a class, which contains Main() method.
Syn:
class classname
{
}
33.. MMaaiinn(()) mmeetthhoodd:: 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 50 of 548
D. HARSHA VARDHAN
Syn:
Features of Main() Method:
void: It cant 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. Thats 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.
CCoommppiilliinngg aanndd RRuunnnniinngg tthhee aapppplliiccaattiioonn
Compile:
Click on Build menu Build Solution. (or) Press Ctrl+Shift+B.
Run:
Click on Debug menu Start Debugging. (or) Press F5.
Specifies that Main() is a static method; which
allows to directly call Main() method, without
creating an instance of Program class. Means no return value
Receives arguments sent
to the Main() method in a
string array format.
-
.NET 4.0 and Visual Studio 2010 Page 51 of 548
D. HARSHA VARDHAN
II)) BBaassiicc PPrrooggrraammmmiinngg TTeecchhnniiqquueess iinn CC##
11)) KKeeyywwoorrddss
You can observe the available keywords in C#.
22)) TThhee CCoonnssoollee ccllaassss::
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 52 of 548
D. HARSHA VARDHAN
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 53 of 548
D. HARSHA VARDHAN
33)) CCoommmmeennttss
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 54 of 548
D. HARSHA VARDHAN
OOuuttppuutt::
AAfftteerr pprreessssiinngg EEnntteerr
44)) SSkkiipp wwrriittiinngg tthhee iimmppoorrtteedd nnaammeessppaacceess
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.
//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(); } } }
-
.NET 4.0 and Visual Studio 2010 Page 55 of 548
D. HARSHA VARDHAN
55)) DDaattaa TTyyppeess
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 in the 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
long 64-bit signed integer -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
8
ulong 64-bit unsigned integer 0 to 18,446,744,073,709,551,615 8
float Single-precision float 1.510-45 to 3.41038 4
double Double-precision float 510-324 to 1.710308 8
decimal Decimal value with 28-significant-digit precision
1.01028 to 7.91028 16
bool Boolean true, false 1
char Unicode character Any one character 2
string Group of characters 2 billion characters No. of chars X 2
(Initially 0)
object Any type of value ---- Based on the
value
-
.NET 4.0 and Visual Studio 2010 Page 56 of 548
D. HARSHA VARDHAN
66)) VVaarriiaabblleess
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 57 of 548
D. HARSHA VARDHAN
Output:
77)) EEssccaappee SSeeqquueennccee CChhaarraacctteerrss
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.");
Console.Read(); } } }
-
.NET 4.0 and Visual Studio 2010 Page 58 of 548
D. HARSHA VARDHAN
OOuuttppuutt::
88)) CCoonnssttaannttss
Constants look just like variables, but concept wise, they differ from variables.
The main differences between constants and variables are:
The value of constants cant 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 {
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(); } } }
-
.NET 4.0 and Visual Studio 2010 Page 59 of 548
D. HARSHA VARDHAN
OOuuttppuutt::
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(); } } }
-
.NET 4.0 and Visual Studio 2010 Page 60 of 548
D. HARSHA VARDHAN
99)) TTyyppee ccaassttiinngg
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.
IImmpplliicciitt CCaassttiinngg
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 61 of 548
D. HARSHA VARDHAN
Implicit Casting in C#:
EExxpplliicciitt CCaassttiinngg
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 62 of 548
D. HARSHA VARDHAN
OOuuttppuutt::
EExxpplliicciitt CCaassttiinngg uussiinngg CCoonnvveerrssiioonn MMeetthhooddss
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.
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(); } } }
-
.NET 4.0 and Visual Studio 2010 Page 63 of 548
D. HARSHA VARDHAN
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 64 of 548
D. HARSHA VARDHAN
OOuuttppuutt::
IIMMPP NNoottee::
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.
1100)) BBooxxiinngg aanndd UUnnbbooxxiinngg
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
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(); } } }
-
.NET 4.0 and Visual Studio 2010 Page 65 of 548
D. HARSHA VARDHAN
OOuuttppuutt::
1111)) VVaarriiaabbllee SSccooppeess
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#.
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(); } } }
-
.NET 4.0 and Visual Studio 2010 Page 66 of 548
D. HARSHA VARDHAN
Scope Description Accessibility Example
1) Class level scope
A variable declared within the class.
This is known as data member, which accessibility is based on the access modifier you use. (like private, public etc.)
class sample { private int x; }
2) Method level scope
A variable declared within the method
Accessible only within the method only.
void sample() { int x; //some code }
3) Block level scope
A variable declared within a block. Ex: if block, else block, for block, try block, catch block etc. Note: A block can be specified when you use curly braces. { }
Accessible only within the block only.
if (x==y) { int x; //some code }
Strong Rule to follow: Multiple variables with same name within the same scope
cant be declared anywhere.
1122)) OOppeerraattoorrss
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 67 of 548
D. HARSHA VARDHAN
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 68 of 548
D. HARSHA VARDHAN
Operator Precedence:
1133)) FFllooww CCoonnttrrooll wwiitthh CCoonnttrrooll SSttaatteemmeennttss
C# supports several types control statements.
These are almost all similar to C.
TTyyppeess ooff CCoonnttrrooll SSttaatteemmeennttss
Branching Control Statements
if
switch-case
break
continue
goto
Looping Control Statements
while
do-while
for
-
.NET 4.0 and Visual Studio 2010 Page 69 of 548
D. HARSHA VARDHAN
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 70 of 548
D. HARSHA VARDHAN
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 71 of 548
D. HARSHA VARDHAN
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 72 of 548
D. HARSHA VARDHAN
for
for (initialization; condition; increment/decrement) { ----------;
----------; ----------; }
Note: You can also implement nested loops as you implemented in C/C++.
1144)) EEnnuummeerraattiioonnss
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 73 of 548
D. HARSHA VARDHAN
OOuuttppuutt::
static void Main(string[] args) { Console.WriteLine(Months.March); Console.WriteLine((int)Months.March); Console.Read(); } } }
-
.NET 4.0 and Visual Studio 2010 Page 74 of 548
D. HARSHA VARDHAN
1155)) AArrrraayyss
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:
Without initialization:
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]
Single-dim array
Double-dim array
-
.NET 4.0 and Visual Studio 2010 Page 75 of 548
D. HARSHA VARDHAN
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 76 of 548
D. HARSHA VARDHAN
OOuuttppuutt::
if (Marks[i] >= 0 && 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(); } } }
-
.NET 4.0 and Visual Studio 2010 Page 77 of 548
D. HARSHA VARDHAN
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 78 of 548
D. HARSHA VARDHAN
OOuuttppuutt::
ffoorreeaacchh LLoooopp
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 79 of 548
D. HARSHA VARDHAN
Note: The arrayname.Length property gets the size of the array. We discuss about the Array
class in future.
JJaaggggeedd AArrrraayyss
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 80 of 548
D. HARSHA VARDHAN
OOuuttppuutt::
1166)) EExxeeccuuttiinngg ..NNEETT AApppplliiccaattiioonnss ffrroomm CCoommmmaanndd WWiinnddooww::
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.
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(); } } }
-
.NET 4.0 and Visual Studio 2010 Page 81 of 548
D. HARSHA VARDHAN
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
1177)) PPaassssiinngg AArrgguummeennttss ttoo MMaaiinn(()) MMeetthhoodd
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.
For example, Let us create this application on D:
Application 13: Demo on Main() method arguments
-
.NET 4.0 and Visual Studio 2010 Page 82 of 548
D. HARSHA VARDHAN
OOuuttppuutt::
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(); } } }
-
.NET 4.0 and Visual Studio 2010 Page 83 of 548
D. HARSHA VARDHAN
1188)) MMuullttiippllee MMaaiinn(()) MMeetthhooddss
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 84 of 548
D. HARSHA VARDHAN
When this program is compiled, the compiler shows 2 compile time errors.
Its because, two Main() methods are found in MySample class and Program class;
So that the compiler cant 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 85 of 548
D. HARSHA VARDHAN
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 86 of 548
D. HARSHA VARDHAN
II) Object Oriented Programming Features of C#
IIII..aa)) AAnn iinnttrroodduuccttiioonn ttoo OObbjjeecctt OOrriieenntteedd PPrrooggrraammmmiinngg::
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 ca