Вы находитесь на странице: 1из 81

Programming using C# .

NET

Mr. Prashant Ankalkoti


Asst.Prof, Dept. Of MCA
J N N C E, Shivamogga.
Email : prashantsa@jnnce.ac.in
Mob : 9886363246 1
Module 1
Getting started with .NET Framework 4.0 and C#
Introduction:
• .NET Framework is an essential component of the Windows operating system,
which helps in creating applications by integrating different programming
languages, such as C#, Visual Basic, J#, and Visual C++.
• This framework consists of a virtual execution system called the Common
Language Runtime (CLR) and a set of class libraries. CLR is a Microsoft product of
the common creating execution and development environments in which
languages and libraries work together.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 2


.NET, .NET Framework, and .NET Core ?
.NET is a developer platform made up of tools, programming languages, and libraries for
building many different types of applications.
There are various implementations of .NET. Each implementation allows .NET code to
execute in different places—Linux, macOS, Windows, iOS, Android, and many more.

 .NET Framework is the original implementation of .NET. It supports running websites,


services, desktop apps, and more on Windows.

 .NET Core is a cross-platform implementation for running websites, services, and


console apps on Windows, Linux, and macOS. .NET Core is open source on GitHub.

 Xamarin / Mono is a .NET implementation for running apps on all the major mobile
operating systems, including iOS and Android.
https://dotnet.microsoft.com/learn/dotnet/what-is-dotnet-framework

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 3


Evolution of .NET:-
• At the time of mid ninety, java was so popular to develop the application because of its
platform independent technique and open source policy of Sun Microsystems.
• Around 2002, Sun Microsystems introduced the Java 2 Enterprise Edition (J2EE) to
create the distributed application.
• As the J2EE was gaining popularity, the market share of Microsoft ultimately led to the
turn down.
• Therefore, Microsoft starts working on a project known as Next Generation Windows
Services (NGWS) to recover the market share.
• The project took around three years to build up, which is now known as .NET. Microsoft
released the different version of .NET with the different names.
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 4
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 5
Overview of .NET Framework Release History

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 6


Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 7
CLS [Common Language Specification]:
 The Common Language Specification (CLS) is a set of rules that a given .NET-aware
compiler must support to produce code that can be hosted by the CLR, while at the same
time be accessed in a uniform manner by all languages that target the .NET platform. In
many ways, the CLS can be viewed as a subset of the full functionality defined by the
CTS.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 8


Common Language Runtime (CLR)

.NET Framework provides runtime


environment called Common Language
Runtime (CLR).It provides an environment
to run all the .NET Programs. The code
which runs under the CLR is called
as Managed Code.
Programmers need not to worry on
managing the memory if the programs are
running under the CLR as it provides
memory management and thread
management.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 9


1.1 Understanding Previous Technologies:
Let’s begin with a brief discussion on limitations of the previous state of affairs.

a) C / Win32 Language:
Disadvantages:
i. Concept of Pointers is the powerful feature. But, they are highly insecure and makes it vulnerable.
ii. The concept of reusability is achieved only through functions, so it makes more complex for coding big
projects and hence lot of time is wasted.
iii. C developers have to concentrate on memory management as there is no automatic Memory
management.
iv. Since C is structured language, it lacks all the benefit of object oriented programming
v. C doesn't perform Run Time Type Checking. It only does compile time type checking.
vi. Besides all these, C is a powerful language, that's why, a majority of Operating Systems are built using C.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 10


Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 11
b) C++ / MFC Language:
Advantages:
 Stronger type checking
 Support for data abstraction, object-oriented programming and generic programming

Drawbacks:
 Not truly object oriented
 Not suitable for developing web technologies
 It does not support versioning i.e., creation and management of multiple versions of
Software.
 It is not type-safe. It means the following
• Arrays are unbound.
• Compile time errors are not generated when uninitialized arrays are used
• It still support pointers which will leads to major errors in programs and also it makes highly insecure
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 12
c) Visual Basic 6.0:

Advantages:
 VB was originally designed as a programming language for non-programmers. To that
end, the syntax was designed to read more like natural language sentences than
instructions to a computer.
 There is no need to specify the type of a variable, or even declaring the variable itself.

Drawbacks of VB are:

 VB is not fully object oriented


 Developing multi-threading applications using VB is a bit complex as we have to call the
low level WIN32 API calls.
 No need to declare the data type of variables prior to its usage, there will be more
chances to get runtime errors.
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 13
d) JAVA / J2EE:
Advantages:
a) Platform Independent
b) It contains large number of pre-defined packages that contain various type definitions.
c) Java programmer can build pure Java applications complete with database connectivity, messaging
support, web-enabled front ends, and a richer user interface.
d) Java eliminates pointers which is major concern in C and C++
e) Garbage collection is one of the powerful features, which automatically cleans the memory.
Disadvantages:
• Java is a very elegant language that means must use of Java front-to-back during development cycle
• Java applets are not supported by all the browsers and they need separate plug-in to be installed
• Java developers have less control over on garbage collection to free objects
• Primary goal of Java is to make Java as a single programming language for every need. So Java offers
a little chance for language integration.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 14


1.2 Benefits of .NET Framework:
The following are the benefits of .NET Framework:

 Consistent Programming Model: Provides a consistent object-oriented programming model


across different language. You can use this model to create programs for performing different
tasks, such as connecting to and retrieving data from databases, and reading and writing in
files.

 Cross-Platform Support: Specifies that any windows platform that supports CLR can execute
.NET application, that is, .NET application enables interoperability between multiple Windows
operating systems.

 Language Interoperability: Enables code written in different languages to interact with each
other. This allows reusability of code and improves the efficiency of the development process.
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 15
 Automatic Management of Resource: In .NET, no need to manually free the application
resources, such as files, memory, network, and database connection because .NET
Framework provides a feature called CLR that automatically tracks the resource usage
and helps you in performing the task of manual resource management.

 Ease of Deployment: In most cases, to install an application, you need to copy the
application along with its components on the target computer. But in .NET, applications
are deployed in the form of assemblies that’s why, do not affect the existing
applications. Therefore, registry entries are not required to store information about
applications and also version problem is eliminated in .NET Framework.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 16


1.3 Architecture of .NET Framework 4.0:
The latest version of .NET framework provides:

a) In developing portable, scalable, and robust applications.

b) Developed applications can be executed in a distributed environment.

Therefore, you can say that the .NET Framework 4.0 is designed to address the latest needs
of the developers.

The architecture of .NET Framework 4.0 mainly consists of components of .NET Framework
2.0 and 3.0 with few enhancement as shown in figure 1.1.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 17


Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE Figure 1.1: .NET Execution Engine 18
1.4 .NET Execution Engine:
The following figure summarizes the workflow between a .NET source code, a .NET compiler,
and the .NET execution engine:

The .NET execution process completes as given below:

i. When you compile source code by selecting .NET aware compilers such as Visual Basic, C#,
Visual C++, J#, or any of the third party compilers, such as COBOL, Perl or Eiffel.

ii. The .NET aware compiler converts source code in to binaries that are called as assemblies.
The assembly can be either *.dll or *.exe depending on the entry point defined in the
application.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 19


iii. Assembly contains IL code, Metadata and Manifest data.

NOTE: IL(Intermediate Language) code is also known as MSIL(Microsoft IL) / CIL(Common IL)

has a machine-readable instruction sets.

iv. The next level of compilation happen just before the application is executed. At this point, if
loader detects an IL code it loads mscoree.dll which denotes Runtime Execution Engine(CLR).

v. Then loaded IL code must be converted to Platform-specific code by a Just-in-Time(JIT)


compiler at runtime.

vi. Base class Library (mscorlib.dll): This library encapsulates various primitives such as file
IO, Data Access, Threading, XML/SOAP etc. When building .NET binaries you always make use
of this particular assembly.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 20


Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE Figure 1.2: .NET Execution Engine 21
1.5 Components of .NET Framework 4.0:
The .NET Framework provides all the necessary components to develop and run an
application. The components of .NET Framework 4.0 architecture are as follows:

 Common Language Runtime (CLR)  Windows Communication Foundation


 Common Type System (CTS)  Windows CardSpace
 Metadata and Assemblies  LINQ
 .NET Framework class library
 Windows Forms
 ASP.NET and ASP.NET AJAX
 ADO.NET
 Windows Workflow Foundation
 Windows Presentation Foundation

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 22


1.6 CLR[Common Language Runtime]:
“CLR is an Execution Engine for .NET Framework applications”.
CLR is a heart of the.NET Framework. It provides a run-time environment to run the code
and various services to develop the application easily.
The services provided by CLR are –
 Memory Management  Code execution
 Exception Handling  Language Integration
 Debugging  Code safety
 Security  Verification
 Thread execution  Compilation

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 23


The following figure shows the process of compilation and execution of the code by the JIT Compiler:

Figure 1.3: Compilation and execution by the JIT


Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 24
i.When you compile your source code by selecting .NET aware compilers; that compiler
converts source code in to bytecode known as IL / MSIL / CIL. This code is referred to as
Assembly.
ii. After compiling, the code is passed to the CLR at the runtime; which may take some action.
iii. CLR uses the rules to examine the code which are stated in the CLS and CTS.
iv. After verifying, a JIT [Just-In-Time] compiler extracts the metadata from the file to
translate that verified IL code into CPU-specific code or native code. These type of IL Code is
called as managed code.
v. The source code which is directly compiles to the machine code and runs on the machine
where it has been compiled such a code called as unmanaged code. It does not have any
services of CLR.
vi. Automatic garbage collection, exception handling, and memory management are also the
responsibility of the CLR.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 25


Let’s now explore the managed code, unmanaged code, and memory management in CLR.
Managed Code: Managed code is the code that is executed directly by the CLR. The
application that are created using managed code automatically have CLR services, such as
type checking, security, and automatic garbage collection.
The process of executing a piece of managed code is as follows:
 Selecting a language compiler
 Compiling the code to IL [ This intermediate language is called managed code ]
 Compiling IL to native code
 Executing the code

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 26


Unmanaged Code: Unmanaged Code directly compiles to the machine code and runs on
the machine where it has been compiled. It does not have services, such as security or
memory management, which are provided by the runtime. If your code is not security-
prone, it can be directly interpreted by any user, which can prove harmful.

Automatic Memory Management: CLR calls various predefined functions of .NET


framework to allocate and de-allocate memory of .NET objects. So that, developers need
not to write code to explicitly allocate and de-allocate memory.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 27


1.7 CTS [Common Type Specifications]:
The CTS defines the rules for declaring, using, and managing types at runtime. It is an
integral part of the runtime for supporting cross-language communication.
The common type system performs the following functions:
• Enables cross-language integration, type safety, and high-performance code execution.
• Provides an object-oriented model for implementation of many programming languages.
• Defines rules that every language must follow which runs under .NET framework like C#,
VB.NET, F# etc. can interact with each other.
The CTS can be classified into two data types, are
i. Value Types
ii. Reference Types

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 28


The base class of all the types is the System.Object class. The hierarchy of the types as shown figure 1.4:

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 29


Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 30
1.8 Metadata and Assemblies:
A metadata is binary information that describes your program, stored in a CLR Portable
Executable (PE) file or the memory.
The metadata contains the following:
• Assembly information, which includes the metadata identity that can be name, version,
culture, public key, the types of assemblies, other reference assemblies, and security
permissions.
• Information about types, such as name, visibility, base class, interfaces used, and
members (methods, fields, properties, events, and nested types)
• Attribute information that modifies the types and members of a class.
An assembly contains a self-describing binary file that can be either Dynamic Link Library
(DLL) or Executable (EXE). It also contains a collection of types, such as classes, interfaces
and structures.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 31


There are two types of assembly:
i. Single file assembly: Single assembly can contain multiple code files of single code file
can have more than one assembly. It contains the type information and implementation
as well as the assembly’s manifest into a single physical file. Example: Class Libraries,
Windows Forms / WPF applications, Console applications and Windows Services.

Figure 1.5: Structure of Single-File Assembly


Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 32
ii. Multi-file assembly: An assembly can consist of one or more files called modules.
Exactly one of these modules contains the assembly manifest.
The most common reason for multi-file assemblies is when a single assembly combines
code from multiple programming languages.

Figure 1.6: Structure for Multi-file Assembly


Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 33
Assemblies can stored in two types:
Static assemblies: Static assemblies include interfaces, classes and resources. These
assemblies are stored in PE (Portable executable) files on a disk.
Dynamic assemblies: Dynamic assemblies run directly from the memory without being
saved to disk before execution. However, after execution you can save the dynamic
assemblies on the disk.
Assembly Content:
Assembly is a logical unit that consists of 4 elements as follows:
• Manifest: The manifest, also known as assembly manifest, contains the assembly
metadata needed for providing the assembly’s version requirements and security
identity.
• Metadata
• IL code(static or dynamic)
• Set of resources[bitmaps, jpeg]

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 34


Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 35
Global Assembly Cache:
The Global Assembly Cache (GAC) is a folder in Windows directory to store the .NET
assemblies that are specifically designated to be shared by all applications executed on a
system.
• The assemblies must be sharable by registering them in the GAC, only when needed;
otherwise, they must be kept private.
• Each assembly is accessed globally without any conflict by identifying its name, version,
architecture, culture and public key.
You can deploy an assembly in GAC by using any one of the following:
• An installer that is designed to work with the GAC
• The GAC tool known as Gacutil.exe
• The Windows Explorer to drag assemblies into the cache.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 36


Strong Name Assembly:
A Strong Name contains the assembly’s identity, that is, the information about the
assembly’s name, version number, architecture, culture and public key.
• Using Microsoft Visual Studio .NET and other tools, you can provide a strong name to an
assembly.
• By providing strong names to the assembly, you can ensure that assembly is globally
unique.
Benefits:
 Provides uniqueness to the names by generating a private key.
 Ensures that a version of the assembly you are using comes from the same publisher
that created the version the application was built with.
 Facilitates integrity check, which ensures that the contents of the assembly do not
change since its last build.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 37


Private and Shared Assembly:
A single application uses an assembly, then it is called as a private assembly.
Example: If you have created a DLL assembly containing information about your business
logic, then the DLL can be used by your client application only. Therefore, to run the
application, the DLL must be included in the same folder in which the client application has
been installed. This makes the assembly private to your application.
Assemblies that are placed in the Global Assembly cache so that they can be used by
multiple applications, then it is called as a shared assembly.
Example: Suppose the DLL needs to be reused in different applications. In this scenario,
instead of downloading a copy of the DLL to each and every client application, the DLL can
be placed in the global assembly cache by using the Gacutil.exe tool, from where the
application can be accessed by any client application.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 38


Side-by-Side Execution Assembly:
The process of executing multiple versions of an application or an assembly is known as
side-by-side execution. Support for side-by-side storage and execution of different
versions of the same assembly is an integral part of creating a strong name for an
assembly.
 Strong naming of .NET assembly is used to provide unique assembly identity by using
the sn.exe command utility.
 The strong-named assembly’s version number is a part of its identity, the runtime can
store multiple
 versions of the same assembly in the GAC.
 Load these assemblies at runtime.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 39


1.9 .NET Framework Class Library:
The .NET Framework helps in speeding up the application development process and provide
access to system functionality.
To facilitate interoperability between languages, most .NET Framework types are CLS-
compliant and can be used from any programming language whose compiler conforms to
the common language specification (CLS).
The .NET Framework types are the foundation on which .NET applications, components,
and controls are built.
These entities perform the following functions:
• Represent base data types and • Provide data access, rich client-side
exceptions GUI, and server-controlled, client-side
GUI
• Encapsulate data structures
• Access information about loaded types
• Perform I/O
• Invoke .NET Framework security
checks
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 40
1.10 Windows Forms (WF):
Windows forms is the graphical representation of any window displayed in an application.

• It is included as a part of Microsoft’s .NET Framework.

• Create an application using Window Forms in any CLR supported language.

• Used to either accept input from or display information to the user.

• Add controls to the forms and raise events, such as mouse-click, which is handled by
event handlers in an application.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 41


1.11 ASP .NET and ASP .NET AJAX:
ASP.NET is a web development mode, which is used to deliver interactive and data-driven
web application over the internet. It also consists of a large number of controls, such as
text boxes, buttons, and labels for assembling, configuring, and manipulating code to
create Hyper Text Markup Language (HTML).
Advantages of ASP.NET:
 Better Performance: Specifies that when you request a web page for the first time after
compiling ASP.NET code, the CLR compiles the code and stores the cached copy of the
result. Now, for any subsequent calls to the same page, the cached copy of the result is
retrieved instead of going back to the server.
 Improved Security: Refers to the different methods of authentication included in
ASP.NET:
 Forms: Allows the ASP.NET application to use its own custom business logic for
authentication.
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 42
 Windows: Checks the identity of a user against the Windows user accounts that are
stored on the Web Server. If the credentials of a user match with that of a Windows user
account, then the user is authenticated.

 Greater Scalability: Specifies that the session states in ASP.NET are maintained in a
separate process on a different machine or database. This enables cross-server sessions
to occur, solving the problem of web forms when more web servers need to be added as
the traffic grows.
 Cookie-less Sessions: Specifies that ASP.NET stores the session even when the cookies in
a Web browser are disabled. In such a case, the session ID is passed as a part of the
Uniforms Resource Locator (URL).
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 43
AJAX, which is also known as Atlas, is used as an extension for ASP.NET to develop and
implement the AJAX functionality. ASP.NET AJAX has both side client and server components
to develop the Web applications, which can update the information on a Web application
without reloading the page completely.
Advantages of using AJAX:
• Asynchronous: Enables asynchronous calls to the Web server without making the users
wait for the data.
• Minimal transfer of data: Helps in sending only a part of the modified data to the web
server to minimize the network traffic and perform the operations quicker.
• Minimal processing on the Web server: Minimizes the processing on the Web server as only
the necessary data needs to be sent. Now, the server is not required to send a full page
back to the user.
• Context: Reduces burden on the server by sending a request back to the server through the
client-side script. AJAX-based applications implement partial page post backs instead of
full page post backs, which reduce the data traffic between the client and server.
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 44
1.12 ADO .NET:
ADO.NET is a technology used for working with data and databases of all types.
It provides access to data sources, such as Microsoft SQL Server, data sources exposed
through OLE DB, and Extensible Markup Language (XML).
Advantages:
• Disconnected Data Architecture: Implies that applications connect to the database only
when data needs to be retrieved or modified. After the database operation has been
performed, the connection to the database is closed. To perform any database operation
again, the connection with the database will have to be re-established.
 Cached Data in Datasets: Follows a disconnected architecture for accessing or modifying
data. The data is accessed and later stored in the datasets. A dataset is a cached set of
database records, which is independent of data source. Even when you are disconnected from
the database on which you are working, you can make modifications in the database.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 45


 Scalability: Reduces the traffic on the database and saves the resources to make the
database more efficient. ADO.NET help in attaining scalability by performing all database
operations on the dataset instead of on the database.

 Transfer of Data in XML Format: Transfers data from a database into a dataset and from
the dataset to another components using XML, which is the standard format used for
transferring data in ADO.NET.

 Interaction with the Database through Data Commands: All operations on database are
performed, such as retrieving, modifying, or updating of data using data commands. A data
command is either a

 Structured Query Language (SQL) statement or a stored procedure.


Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 46
1.13 Windows Workflow Foundation (WF):
WF is a technology introduced by Microsoft, which provides a programming model for
building workflow based applications on Windows.
It includes activities, workflow runtime, workflow designer, and a rules engine. WF is a part
of .NET Framework 3.0, 3.5 and 4.0.
Features

 Activities: Receives some parameters from the developer, execute the actions specified in
the parameters, and then the flow is transferred to the next activity.

 Workflow Designer: Designs workflows by placing activities within the workflow model.
One interesting feature is that it can be re-hosted within any Windows Forms application.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 47


 Workflow Runtime: Executes the activities in a workflow. It is a lightweight and
extensible engine that resides within a .NET process, facilitating the developers to bring
workflow to anything from a Windows Forms application to an ASP.NET website or a
Windows Service.

 Rules Engine: Enables declarative, rule-based development for workflows and any
.NET application to be used.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 48


Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 49
1.14 Windows Presentation Foundation(WPF):
WPF provides the base for building applications and a clear separation between the user
interface and the business logic. WPF helps in building interfaces that include documents,
media, two or three dimensional graphics, animations and web-like characteristics. The
architecture of WPF shown below:
WPF provides document services, such as XML Paper Specification (XPS) documents and
packaging services.
• XPS documents are shown with an XML-based schema that defines the layout and
visual appearance of a page.
• The WPF namespace System.IO.Packaging helps in organizing data, content, and
resources of your application into a single, portable, easy to access, and
distributable .zip document.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 50


Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 51
1.15 Windows Communication Foundation (WCF):
WCF is one of the new technologies introduced by Microsoft in .NET Framework 3.0 for
building and running connected systems.
It is a service-oriented technology for developing applications in a distributed system that
provides services to the client applications.
The enhancements of WCF as compared to the previous technologies are as follows:
 Merges technologies, such as Web services, remoting, distributed transactions, and
message queuing in one place and reduces development time.
 Consists of many powerful enterprise features.
 Integrates easily with other technologies and consequently, enables greater
interoperability.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 52


Figure 1.9: Architecture of WCF

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 53


1.16 Windows CardSpace (WCS):
Windows CardSpace is a client software provided by Microsoft that improves the safety of
accessing resources and helps in sharing personal information on the internet. It helps
programmers in developing websites and software that are less prone to identity-related
attacks, such as phishing.
Advantages:
 Reducing the problems of traditional online security mechanisms by relying on separate
desktop and cryptographically strong authentication rather than on user names and
passwords.
 It facilitates secure online transactions, such as online shopping, banking, and bill
payment.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 54


Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 55
1.17 LINQ:
LINQ is an acronym for Language Integrated Query, which is one of the components of
.NET Framework 4.0 that adds native data querying capabilities to .NET languages by
using syntax similar to SQL.
The following are simple LINQ query in different language:
When you execute the preceding query, it returns the names of all the male students and is
stored in the variable query.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 56


Introducing C#
Module 1 – Chapter 2

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 57


2.1 Creating a Simple C# Console Application:
A class declaration in C# is composed of attributes, modifiers, the class name, base class
and interfaces, and a body. Attributes, modifiers, and bases are all optional.
 It is declared inside a class. It must be static
and it should not be public.
 C# executable program must include the
Main() method in any one of the classes.
 public: is an access modifier that tells the
main method is accessible by anyone.
 static: the Main method is a global one
and can be called without creating an
instance of the class.
 void: is a type modifier, that the Main
method does not return any value.
 string[] args: method has single
parameter which happens to be an array
of strings and also contain any number of
incoming command – line – arguments. 58
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Variation on the Main() method:
 The execution of C# program begins with Main method. In C#, we are having four
overloaded forms of Main method.
 When a program starts, it looks for an entry point. This is the role of the Main() method. In
fact, a program, that is an executable program, starts by, and stops with, the Main()
method.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 59


2.2 Identifiers and Keywords:
 An Identifiers is a sequence of character used to identify a variable, constant, or any
user-defined programming element.

Rules:
Starts with a letter or an underscore and ends with a character.
 Can have letters, digits and underscores.
 Must not be a reserved word.
 Must be a complete word without any blank spaces.
Example: sum, SUM, _sum

Keywords are the reserved words whose meanings are predefined to the C# compiler.
• You cannot use keywords as variable, methods and properties
• If you want to use the keywords as identifiers, prefix the keyword with @ character.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 60


Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 61
2.3 System Data Types:
The C# language provides a rich set of built-in data types.
Points:
o All variables, whether user-defined or built-in (intrinsic), can be used as objects
anywhere in a program,
o All variables in a program are automatically initialized to default values by the system
when they are declared.
C# variables are categorized in to three:
i. Value Types: which include all numerical data types, as well as enumerations and
structures, are allocated on the stack.
ii. Reference Types: which include reference of an objects, are allocated on the heap.
iii. Pointer Types: which holds the memory address of a variable.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 62


2.4 Variables and Constants:

2.5 Value Types:


Allow you to store the data directly into the variable. They are derived from
System.ValueType
The value type and their content are stored at the same location memory. The default
values of value types are stored on stack.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 63


Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 64
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 65
Struct Type:
Struct types are a special form of classes having the properties of value types. As you know
that the value type are stored on the stack, inherently the struct types are also stored on
the stack.
You can create struct types by using the “struct” keyword. When you create a struct object
and assign it to variable, the variable holds the value of the struct object.
Syntax:
 Can apply only public, private and internal access modifiers to a struct and member
definition.
 Cannot use the protected and protected internal access modifiers in structs because
structs are implicitly sealed. This means that a struct cannot be a parent class of other
classes.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 66


The struct types are divided into the following 5 categories:
 Integral Type: C# provides a set of basic data types which are known as integral types
such as sbyte, byte, short, ushort, int, uint, long, ulong & char
 Floating-Point Type: It is divided into two types; they are, single and double floats.
• Single float holds – is similar to the float data type, hold values up to 10308.
• Double float holds – is similar to the double data type, hold values up to 10308.
 Decimal Type: It is equivalent to a long integer
 Boolean Type: true or false
 Nullable Type: when dealing with databases or when a user does not want to assign a
value to a variable of any data type.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 67


Enum Type:
Enumerations are the user-defined integer data types that are declared using the “enum”
keyword. You can define a set of named integral constants that can be assigned to a variable.
Example 2.2:

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 68


2.6 Reference Types:
C# also provides types that are passed by references to calling functions, known as reference
types. Variables that refer to the objects store the reference of the actual data. The reference
types use heap to store the references instead of the actual data.
Reference types can be categorized into 2 parts:
i. Pre-defined reference types: Dynamic type, Object type, String type
ii. User-defined reference types: Classes, Interfaces, Delegates, Arrays
Pre-defined reference types:
C# provides you some built-in reference types, which are as follows:
• Dynamic type
• Object type
• String type
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 69
Dynamic type:
You can store any type of value in the dynamic type variable. It performs the type checking
of the dynamic type variable at run time.
Syntax: dynamic dyn=10;
Object type:
You can assign values of any type to the variable of object type. It performs the type
checking of the variable of object type at compile time.
Object type is base class for the other types such as value types, reference types,
predefined types, user-defined types. The object type can be assigned a value of any other
types, but requires the type conversion.
o A value type converted to the object type, the process is known as boxing
o An object type converted to the value type, the process is known as unboxing.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 70


String type:
It enables you to assign string values to the variables of string type. The string type is an alias
for the System.String class. String type is directly derived from the object type. You cannot
change its value.
The value for a string type can be assigned using the string literals in 2 forms: quoted and
@quoted.
Where, @- Verbatim string literals: String literals are embed escape characters

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 71


User-defined reference types:
C# provides you some user-defined reference types, which are as follows:
• Classes
• Interfaces Classes:
All classes are user-defined data types and are considered as objects. All
• Delegates objects are derived from a single base class, known as System.Object.
• Arrays
Interface:
Interface define a set of functionalities that can be related to
any class or struct. You cannot instantiate an object through an
interface. Interface have method declarations, these are known
as abstract ie, they do not have implementation part.
A class that implements all the methods which is declared in the
interface; otherwise, the compiler raise an error.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 72


Delegates:
A delegates is almost equivalent to function pointer in C++ or C. C# contains two kinds of
objects – those that create a change and respond to the change.
A delegate acts as the tunnel between the two kinds of objects:
• Moving information from one side to another
• C# delegates are class methods and can be either static or instance class methods.
A delegate can keep a track of its own state by maintaining information in the object to
which it belongs. You can create a delegate by using delegate keyword, as shown below:

public delegate int intDelegate(int i);

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 73


Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 74
Arrays:
An array is used to store the number of elements or variables of the same data type at
contiguous memory locations in an ordered manner.
Array cannot be created on the stack, but on the heap. This means you cannot create an
array statically in a method.
Length Property: This property returns the total number of elements in an array.
Example: int[ , ] a = new int[5,5];
Console.WriteLine(“Total no. of element:” +a.Length);//25

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 75


Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 76
2.7 Understanding Type Conversions:
While writing C# applications, you often need to perform a typical task; that is to convert
one data type to another. For this type of conversion, type casting is used. Type casting has
two forms:
• Implicit
• Explicit
Implicit Conversion:
Implicit conversions are the conversions that are performed by the compiler, in a type-safe
manner.
Explicit Conversion:
When one data type is converted explicitly to another data type, with the help or pre-
defined functions.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 77


2.8 Boxing and UnBoxing:
Boxing is the process of converting a value type to the object type or any interface type
implemented by this value type. Boxing is implicit.
int i = 10;
object o = i; //performs boxing

Unboxing is the reverse of boxing. It is the process of converting a reference type to value
type. Unboxing extract the value from the reference type and assign it to a value type.
Unboxing is explicit. It means we have to cast explicitly.

object o = 10;
int i = (int)o; //performs unboxing

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 78


2.9 Namespaces:
A namespaces is wrapper that is wrapped around one or more structural elements to make
them unique and differentiated from other elements.
• To declare namespace in C# .NET has a reserved keyword “namespace”.
• If a new project is created in Visual Studio .NET it automatically adds some global
namespaces.
• These namespaces can be different in different projects. But each of them should be placed
under the base namespace “System”.
• All namespaces should import by using keyword, which can tell the compiler which
namespaces and libraries of the code you want to use in the system.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 79


2.10 The System namespace:
Within System we can find numerous useful types dealing with built in data, mathematical
computations, random number generation, environment variables, and garbage collection, as
well as a number of commonly used exceptions and attributes. So System is a root
namespace.
The following are some of the common namespaces provided by the .NET Framework class
library:

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 80


2.11 .NET Array Types:
In .Net, array you create is automatically derived from System.Array. This class defines a
number of helpful methods that make working with arrays much more palatable.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 81

Вам также может понравиться