Você está na página 1de 28

1

C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET


VIK
UNIT-1 The Philosophy of .NET
Understanding the Previous State of Affairs
Life As a C!in"# API Progra$$er%
Developing software for the Windows family of operating systems involved using
the C programming language in conjunction with the Windows application
programming interface.
C is a very terse language, in developers does manual memory management,
ugly pointer arithmetic, and ugly syntactical constructs.
C is a structured language; it lacks the benefits provided by the objectoriented
approach.
Life As a C&&'(C Progra$$er%
C!! can be thought of as an objectoriented layer on top of C. "hus, even though
C!! programmers benefit from the famed #pillars of $$%& 'encapsulation,
inheritance, and polymorphism(, they are still at the mercy of the painful aspects
of the C language 'e.g., manual memory management, ugly pointer arithmetic,
and ugly syntactical constructs(.
"he )icrosoft *oundation Classes ')*C( provides the developer with a set of C!
! classes that facilitate the construction of Win+, applications. "he main role of
)*C is to wrap a #sane subset& of the raw Win+, -%. behind a number of
classes, magic macros, and numerous codegeneration tools 'aka wizards(.
C!! programming remains a difficult and errorprone e/perience, given its
historical roots in C.
Life As a )isual *asi+ ,.- Progra$$er%
012 is popular due to its ability to build comple/ user interfaces, code libraries
'e.g., C$) servers(, and data access logic with minimal fuss and bother.
2
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
3ven more than )*C, 012 hides the comple/ities of the raw Win+, -%. from
view using a number of integrated code wi4ards, intrinsic data types, classes,
and 01specific functions
012 is not a fully objectoriented language; rather, it is #object aware.&
*or e/ample, 012 does not allow the programmer to establish #isa& relationships
between types 'i.e., no classical inheritance( and has no intrinsic support for
parameteri4ed class construction.
012 doesnt provide the ability to build multithreaded applications unless you are
willing to drop down to lowlevel Win+, -%. calls.
Life As a .ava.#EE Progra$$er
"he 5ava programming language is 'almost( completely object oriented and has
its syntactic roots in C!!.
.ts support for platform independence.
5ava 'as a language( cleans up many unsavory syntactical aspects of C!!. 5ava
'as a platform( provides programmers with a large number of predefined
#packages& that contain various type definitions.
6sing these types, 5ava programmers are able to build #7889 %ure 5ava&
applications complete with database connectivity, messaging support, web
enabled front ends, and a rich user interface.
5ava is a very elegant language; one potential problem is you must use 5ava
fronttoback during the development cycle.
Life As a C/' Progra$$er%
"he Component $bject )odel 'C$)( was )icrosofts previous application
development framework.
C$) is an architecture that says in effect, #.f you build your classes in
accordance with the rules of C$), you end up with a block of reusable binary
code.&
3
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
"he beauty of a binary C$) server is that it can be accessed in a language
independent manner.
C!! programmers can build C$) classes that can be used by 012. Delphi
programmers can use C$) classes built using C.
C$) is its locationtransparent nature 6sing constructs such as application
identifiers '-pp.Ds(, stubs, pro/ies, and the C$) runtime environment,
programmers can avoid the need to work with raw sockets, :%C calls, and other
lowlevel details.
Life As a !indo0s 1NA Progra$$er%
1uilding a web application using C$)based Windows 1istri2uted interNet
Appli+ations
Ar+hite+ture 31NA4 is also ;uite comple/.
<ome of this comple/ity is due to the simple fact that Windows D=- re;uires the
use of numerous technologies and languages '-<%, >")?, @)?, 5ava<cript,
01<cript, and C$)'!(, as well as a data access -%. such as -D$(. $ne problem
is that many of these technologies are completely unrelated from a syntactic
point of view
The .NET Solution
"he .=3" *ramework is a completely new model for building systems on the Windows
family of operating systems, as well as on numerous non)icrosoft operating systems
such as )ac $< @ and various 6ni/A?inu/ distributions.
So$e +ore features provided +ourtesy of .NET%
7. Full interoperability with existing code% "his is 'of course( a good thing.
3/isting C$) binaries can commingle 'i.e., interop( with newer .=3" binaries
and vice versa. -lso, %latform .nvocation <ervices '%.nvoke( allows you to call C
based libraries from .=3" code.
4
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
,. Complete and total language integration% 6nlike C$), .=3" supports cross
language inheritance, crosslanguage e/ception handling, and crosslanguage
debugging.
+. A common runtime engine shared by all .NET-aware languages% $ne aspect
of this engine is a welldefined set of types that each .=3"aware language
#understands.&
B. A base class library% "his library provides shelter from the comple/ities of raw
-%. calls and offers a consistent object model used by all .=3"aware languages.
C. No more COM plumbing% .Class*actory, .6nknown, .Dispatch, .D? code, and
the evil 0-:.-="compliant data types '1<":, <-*3-::-D, and so forth( have
no place in a native .=3" binary.
2. A truly simpliied deployment model% 6nder .=3", there is no need to register
a binary unit into the system registry. *urthermore, .=3" allows multiple versions
of the same 5.dll to e/ist in harmony on a single machine.
Introdu+ing the *uilding *lo+6s of the .NET Platfor$ 3the
CL78 CTS8 and CLS4
<ome of the benefits provided by .=3", lets preview three key 'and interrelated( entities
that make it all possibleE the C?:, C"<, and C?<.
Common language runtime8 or C!"E
"he primary role of the C?: is to locate, load, and manage .=3" types on your
behalf. "he C?: also takes care of a number of lowlevel details such as memory
management and performing security checks.
Common Type #ystem or CT#%
"he C"< specification fully describes all possible data types and programming
constructs supported by the runtime, specifies how these entities can interact
with each other, and details how they are represented in the .=3" metadata
format.
Common !anguage #peciication or C!#E
"he C?< is a related specification that defines a subset of common types and
programming constructs that all .=3" programming languages can agree on.
5
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
"hus, if you build .=3" types that only e/pose C?<compliant features, you can
rest assured that all .=3"aware languages can consume them.
The 7ole of the *ase Class Li2raries
"he .=3" platform provides a base class library that is available to all .=3"
programming languages.
1ase class library encapsulate various primitives such as threads, file
inputAoutput '.A$(, graphical rendering, and interaction with various e/ternal
hardware devices, but it also provides support for a number of services re;uired
by most realworld applications.
*or e/ample, the base class libraries define types that facilitate database access,
@)? manipulation, programmatic security, and the construction of webenabled
front ends.
"he relationship between the C?:, C"<, C?<, and the base class library, as shown in
*igure.
!hat C9 *rings to the Ta2le:
CFs syntactic constructs are modeled after various aspects of 01 2.8 and C!!.
6
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
*or e/ample, like 012, CF supports the notion of formal type properties and the
ability to declare methods taking varying number of arguments 'via parameter
arrays(.
?ike C!!, CF allows you to overload operators, to create structures,
enumerations, and callback functions 'via delegates(.
CF is a hybrid of numerous languages, syntactically clean, provides power and
fle/ibility.
"he C9 language offers the follo0ing features 'many of which are shared by other
.=3"aware programming languages(E
7. =o pointers re;uiredG CF programs typically have no need for direct pointer
manipulation
,. -utomatic memory management through garbage collection, <o CF does not
support a delete keyword.
+. *ormal syntactic constructs for enumerations, structures, and class properties.
B. "he C!!like ability to overload operators for a custom type, without the
comple/ity.
C. "he ability to build generic types and generic members using a synta/ very
similar to C!! templates.
2. *ull support for interfacebased programming techni;ues.
H. *ull support for aspectoriented programming '-$%( techni;ues via attributes.
An /vervie0 of .NET Asse$2lies
5.dll .=3" binaries do not e/port methods to facilitate communications with the
C$)
.=3" binaries are not described using C$) type libraries and are not registered
into the system registry.
.=3" binaries do not contain platformspecific instructions, but rather platfor$-
agnosti+ intermediate language 3$!4 and type $etadata.
When a I.dll or I.e/e has been created using a .=3"aware compiler, the
resulting module is bundled into an assembly.
7
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
-n assembly contains C.? code, which is conceptually similar to 5ava bytecode in
that it is not compiled to platformspecific instructions until absolutely necessary.
-ssemblies also contain metadata. .=3" metadata is a dramatic improvement to
C$) type metadata. .=3" metadata is always present and is automatically
generated by a given .=3"aware compiler.
-ssemblies themselves are also described using metadata, which is officially
termed a maniest
"he manifest contains information about the current version of the assembly,
culture information 'used for locali4ing string and image resources(, and a list of
all e/ternally referenced assemblies that are re;uired for proper e/ecution.
Single-(ile and 'ultifile Asse$2lies
#ingle-ile assembly .f an assembly is composed of a single I.dll or I.e/e
module, called as single-file assembly. <inglefile assemblies contain all the necessary
C.?, metadata, and associated manifest in an autonomous, single, welldefined
package.
Multiile assemblies are composed of numerous .=3" binaries, each of which
is termed a module. When building a multifile assembly, one of these modules 'termed
8
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
the primary module( must contain the assembly manifest 'and possibly C.? instructions
and metadata for various types(. "he other related modules contain a module level
manifest, C.?, and type metadata.
The 7ole of the Co$$on Inter$ediate Language
C.? is a language that sits above any particular platformspecific instruction set.
:egardless of which .=3"aware language you choose, the associated compiler emits
C.? instructions.
(or e;a$ple8
Cal+.+s
using Syste$<
na$espa+e Cal+ulatorE;a$ple
=
This +lass +ontains the app>s entry point.
pu2li+ +lass Cal+App
=
stati+ void 'ain34
=
Cal+ + ? ne0 Cal+34<
int ans ? +.Add31-8 @A4<
Console.!riteLine3B1- & @A is =-C.B8 ans4<
!ait for user to press the Enter 6ey 2efore shutting do0n.
Console.7eadLine34<
C
C
The C9 +al+ulator.
pu2li+ +lass Cal+
=
pu2li+ int Add3int ;8 int y4
= return ; & y< C
C
C
9
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
$nce the CF compiler 'csc.e/e( compiles this source code file, you end up with a single
file I.e/e assembly that contains a manifest, C.? instructions, and metadata describing
each aspect of the Calc and Calc-pp classes.
*or e/ample, if you were to open this assembly using ildasm.e/e, you would find that
the -dd'( method is represented using C.? such as the followingE
.$ethod pu2li+ hide2ysig instan+e int"# Add3int"# ;8 int"# y4 +il $anaged
=
Code siDe @ 3-;@4
.$a;sta+6 #
.lo+als init 3E-F int"# CSG1G----4
ILH----% ldarg.1
ILH---1% ldarg.#
ILH---#% add
ILH---"% stlo+.-
ILH---A% 2r.s ILH---,
ILH---,% ldlo+.-
ILH---I% ret
C end of $ethod Cal+%%Add
"he CF compiler emits C.?, not platformspecific instructions.
*enefits of CIL%
3ach .=3"aware compiler produces nearly identical C.? instructions. "herefore,
all languages are able to interact within a welldefined binary arena.
C.? is platformagnostic, the .=3" *ramework itself is platformagnostic,
providing the same benefits 5ava developers have grown accustomed to 'i.e., a
single code base running on numerous operating systems(.
Co$piling CIL to Platfor$-Spe+ifi+ Instru+tions%
10
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
Due to the fact that assemblies contain C.? instructions, rather than platform
specific instructions, C.? code must be compiled before use.
"he entity that compiles C.? code into meaningful C%6 instructions is termed a
just-in-time 'JIT( compiler or Jitter
"he .=3" runtime environment leverages '6se to ma/imum advantage( a 5."
compiler for each C%6 targeting the runtime, each optimi4ed for the underlying
platform.
*or e/ample,
7. .f you are building a .=3" application that is to be deployed to a handheld
device 'such as a %ocket %C(, the corresponding 5itter is well e;uipped to run
within a low memory environment.
,. .f you are deploying your assembly to a backend server 'where memory is
seldom an issue(, the 5itter will be optimi4ed to function in a high memory
environment.
.n this way, developers can write a single body of code that can be efficiently 5."
compiled and e/ecuted on machines with different architectures.
5itter compiles C.? instructions into corresponding machine code, it will cache the
results in memory in a manner suited to the target operating system.
.n this way, if a call is made to a method named %rintDocument'(, the C.?
instructions are compiled into platform specific instructions on the first invocation
and retained in memory for later use. "herefore, the ne/t time %rintDocument'( is
called, there is no need to recompile the C.?.
The 7ole of .NET Type 'etadata
a .=3" assembly contains full, complete, and accurate metadata, which
describes each and every type 'class, structure, enumeration, and so forth(
11
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
defined in the binary, as well as the members of each type 'properties, methods,
events, and so on(.
1ecause .=3" metadata is so wickedly meticulous, assemblies are completely
selfdescribing entities and .=3" binaries have no need to be registered into the
system registry.
"o illustrate the format of .=3" type metadata, look the metadata that has been
generated for the -dd'( method of the CF Calc class.
Type1ef 9# 3-#-----"4
-------------------------------------------------------
Typ1efNa$e% Cal+ulatorE;a$ple.Cal+ 3-#-----"4
(lags % EPu2li+F EAutoLayoutF EClassF
EAnsiClassF E*efore(ieldInitF 3--1----14
E;tends % -1-----1 EType7efF Syste$./2Je+t
'ethod 91 3-,-----"4
-------------------------------------------------------
'ethodNa$e% Add 3-,-----"4
(lags % EPu2li+F EKide*ySigF E7euseSlotF 3------@,4
7)A % -;----#-L-
I$pl(lags % EILF E'anagedF 3--------4
CallCnvntn% E1E(AULTF
hasThis
7eturnType% IA
# Argu$ents
Argu$ent 91% IA
Argu$ent 9#% IA
# Para$eters
314 Para$To6en % 3-@-----14 Na$e % ; flags% EnoneF 3--------4
3#4 Para$To6en % 3-@-----#4 Na$e % y flags% EnoneF 3--------4
)etadata is used by numerous aspects of the .=3" runtime environment, as well
as by various development tools.
*or e/ample, the IntelliSense feature provided by 0isual <tudio ,88C is made
possible by reading an assemblys metadata at design time.
12
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
)etadata is also used by various object browsing utilities, debugging tools, and
the CF compiler itself.
)etadata is the backbone of numerous .=3" technologies including remoting,
reflection, late binding, @)? web services, and object seriali4ation.
The 7ole of the Asse$2ly 'anifest
.=3" assembly also contains metadata that describes the assembly itself
'technically termed a manifest(.
"he manifest documents all e/ternal assemblies re;uired by the current
assembly to function correctly, the assemblys version number, copyright
information, and so forth. ?ike type metadata, it is always the job of the compiler
to generate the assemblys manifest.
*or e/ample,
CSharpCal+ulator.e;e $anifest%
.asse$2ly e;tern $s+orli2
=
.pu2li+6eyto6en ? 3*I IA MC M, 1L "A E- @L4
.ver #%-%-%-
C
.asse$2ly CSharpCal+ulator
=
.hash algorith$ -;----@--A
.ver -%-%-%-
C
.$odule CSharpCal+ulator.e;e
.i$age2ase -;--A-----
.su2syste$ -;-------"
.file align$ent M1#
.+orflags -;-------1
Understanding the Co$$on Type Syste$
13
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
Common "ype <ystem 'C"<( is a formal specification that documents how types must
be defined in order to be hosted by the C?:.
"here are five types defined by the C"< in their language.
1. CTS Class Types
#. CTS Stru+ture Types
". CTS Interfa+e Types
A. CTS Enu$eration Types
M. CTS 1elegate Types
CTS Class Types
3very .=3"aware language supports, at the very least, the notion of a class
type, which is the cornerstone of objectoriented programming '$$%(.
- class may be composed of any number of members 'such as properties,
methods, and events( and data points 'fields(.
.n CF, classes are declared using the class keywordE
A C9 +lass type.
public class Calc
J
public int -dd'int /, int y(
J return / ! y; K
K
CT# Class Characteristics
7. #ealed classes cannot function as a base class to other classes.
,. "he C"< allows a class to implement any number of interfa+es.L an interace is
a collection of abstract members that provide a contract between the object and
object user.
+. Abstract +lasses cannot be directly created, but are intended to define common
behaviors for derived types. Concrete +lasses can be created directly.
14
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
B. 3ach class must be configured with a %isibility attribute. 1asically, this trait
defines if the class may be used by e/ternal assemblies, or only from within the
defining assembly.
CTS Stru+ture Types
- structure can be thought of as a lightweight class type having valuebased
semantics
<tructures are best suited for modeling geometric and mathematical data, and
are created in CF using the struct keywordE
A C9 stru+ture type.
stru+t Point
=
Stru+tures +an +ontain fields.
pu2li+ int ;Pos8 yPos<
Stru+tures +an +ontain para$eteriDed +onstru+tors.
pu2li+ Point3int ;8 int y4
= ;Pos ? ;< yPos ? y<C
Stru+tures $ay define $ethods.
pu2li+ void 1isplay34
=
Console.!riteLine3B3=-C8 =1CB8 ;Pos8 yPos4<
C
C
CTS Interfa+e Types
$nteraces are nothing more than a named collection of abstract member
definitions, which may be supported 'i.e., implemented( by a given class or
structure.
.n CF, interface types are defined using the interfa+e 6ey0ord.
(or e;a$ple%
15
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
A C9 interfa+e type.
pu2li+ interfa+e I1ra0
=
void 1ra034<
C
$n their own, interfaces are of little use. >owever, when a class or structure implements
a given interface in its uni;ue way, you are able to re;uest access to the supplied
functionality using an interface reference in a polymorphic manner.
CTS Enu$eration Types
Enumerations are a handy programming construct that allows you to group
nameAvalue pairs.
*or e/ample, assume you are creating a videogame application that allows the
player to select one of three character categories 'Wi4ard, *ighter, or "hief(.
:ather than keeping track of raw numerical values to represent each possibility,
you could build a custom enumeration using the enu$ 6ey0ordE
A C9 enu$eration type.
pu2li+ enu$ Chara+terType
=
!iDard ? 1--8
(ighter ? #--8
Thief ? "--
C
1y default, the storage used to hold each item is a +,bit integer; however, it is
possible to alter this storage slot if need be 'e.g., when programming for a low
memory device such as a %ocket %C(.
-lso, the C"< demands that enumerated types derive from a common base
class, <ystem.3num.
CTS 1elegate Types
16
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
Delegates are the .=3" e;uivalent of a typesafe Cstyle function pointer.
"he key difference is that a .=3" delegate is a class that derives from
<ystem.)ulticastDelegate, rather than a simple pointer to a raw memory
address.
.n CF, delegates are declared using the delegate 6ey0ordE
This C9 delegate type +an >point to> any $ethod
returning an integer and ta6ing t0o integers as input.
pu2li+ delegate int *inary/p3int ;8 int y4<
Delegates are useful when you wish to provide a way for one entity to forward a
call to another entity, and provide the foundation for the .=3" event architecture
Delegates have intrinsic support for multicasting 'i.e., forwarding a re;uest to
multiple recipients( and asynchronous method invocations.
CTS Type 'e$2ers
A type member is constrained by the set Jconstructor, finali4er, static
constructor, nested type, operator, method, property, inde/er, field, read only
field, constant, eventK.
*or e/ample,
o 3ach member has a given visibility trait 'e.g., public, private, protected,
and so forth(.
<ome members may be declared as abstract to enforce a polymorphic behavior
on derived types as well as virtual to define a canned 'but overridable(
implementation.
-lso, most members may be configured as static 'bound at the class level( or
instance 'bound at the object level(.
Intrinsi+ CTS 1ata Types
17
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
6ni;ue keyword used to declare an intrinsic C"< data type, all language keywords
ultimately resolve to the same type defined in an assembly named $s+orli2.dll.
Understanding the Co$$on Language Spe+ifi+ation
Different languages e/press the same programming constructs in uni;ue,
language specific terms.
*or e/ample, in CF you denote string concatenation using the plus operator '!(,
while in 01 .=3" you typically make use of the ampersand 'M(.
> )* .NET $ethod returning nothing.
%ublic <ub )y)ethod'(
> So$e interesting +ode...
3nd <ub
C9 $ethod returning nothing.
public void )y)ethod'(
J A So$e interesting +ode.. . K
-s .=3" runtime, compilers 'vbc.e/e or csc.e/e( emit a similar set of C.? instructions.
The Common !anguage #peciication &C!#' is a set of rules that
describe in vivid detail the minimal and complete set of features a given .=3"
aware compiler must support to produce code that can be hosted by the C?:,
18
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
while at the same time be accessed in a uniform manner by all languages that
target the .=3" platform.
"he C?< is ultimately a set of rules that compiler builders must conform too thier
function seamlessly within the .=3" universe. 3ach rule is assigned a simple
name 'e.g.,#C?< :ule 2&( and describes how this rule affects those who build the
compilers as well as those who 'in some way( interact with them.
Rule 1E C?< rules apply only to those parts of a type that are e/posed outside the
defining assembly.
"he only aspects of a type that must conform to the C?< are the member
definitions themselves 'i.e., naming conventions, parameters, and return types(.
"o illustrate, the following -dd'( method is not C?<compliant, as the parameters
and return values make use of unsigned data 'which is not a re;uirement of the
C?<(E
pu2li+ +lass Cal+
=
E;posed unsigned data is not CLS +o$pliantN
pu2li+ ulong Add3ulong ;8 ulong y4
= return ; & y<C
C
>owever, if you were to simply make use of unsigned data internally as followsE
pu2li+ +lass Cal+
=
pu2li+ int Add3int ;8 int y4
=
As this ulong varia2le is only used internally80e are still CLS +o$pliant.
ulong te$p<
...
19
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
return ; & y<
C
C
Ensuring CLS Co$plian+e
.nstruct cF compiler to check the code for C?< compliance using a single .=3" attributeE
Tell the C9 +o$piler to +he+6 for CLS +o$plian+e.
NassemblyE <ystem.C?<Compliant'true(O
ECLSCo$pliantF attri2ute will instruct the CF compiler to check each and every line of
code against the rules of the C?<. .f any C?< violations are discovered, you receive a
compiler error and a description of the offending code.
Understanding the Co$$on Language 7unti$e
.=3" runtime provides a single welldefined runtime layer that is shared by all
languages and platforms that are .=3"aware.
"he cru/ of the C?: is physically represented by a library named mscoree.dll
'aka the Common $bject :untime 3/ecution 3ngine(. When an assembly is
referenced for use, mscoree.dll is loaded automatically, which in turn loads the
re;uired assembly into memory. "he runtime engine is responsible for a number
of tasks.
"hey areE
7. .t is the entity in charge of resolving the location of an assembly and finding
the re;uested type within the binary by reading the contained metadata.
,. "he C?: then lays out the type in memory, compiles the associated C.? into
platformspecific instructions, performs any necessary security checks, and
then e/ecutes the code in ;uestion.
20
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
+. "he C?: will also interact with the types contained within the .=3" base class
libraries when re;uired. -lthough the entire base class library has been
broken into a number of discrete assemblies, the key assembly is mscorlib.dll.
$s+orli2.dll contains a large number of core types that encapsulate a wide variety of
common programming tasks as well as the core data types used by all .=3" languages.
When you build .=3" solutions, you automatically have access to this particular
assembly.
"he workflow that takes place between your source code 'which is making use of base
class library types(, a given .=3" compiler, and the .=3" e/ecution engine.
21
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
22
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
The Asse$2lyNa$espa+eType 1istin+tion
- namespace is a grouping of related types contained in an assembly.
Peep all the types within the base class libraries well organi4ed, the .=3"
platform makes possible by of the namespace concept.
*or e/ample,
o "he <ystem..$ namespace contains file .A$ related types;
o "he <ystem.Data namespace defines basic database types
0ery important single assembly 'such as mscorlib.dll( can contain any number of
namespaces, each of which can contain any number of types.
"he key difference between this approach and a languagespecific library such
as )*C is that any language targeting the .=3" runtime makes use of the same
namespaces and same types.
*or e/ample, the following three programs all illustrate the #>ello World&
application, written in CF, 01 .=3", and )anaged 3/tensions for C!!E
Kello 0orld in C9
using Syste$<
pu2li+ +lass 'yApp
=
stati+ void 'ain34
=
Console.!riteLine3BKi fro$ C9B4<
C
C
23
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
> Kello 0orld in )* .NET
I$ports Syste$
Pu2li+ 'odule 'yApp
Su2 'ain34
Console.!riteLine3BKi fro$ )* .NETB4
End Su2
End 'odule
Kello 0orld in 'anaged E;tensions for C&&
9in+lude Bstdaf;.hB
using na$espa+e Syste$<
int $ain3arrayOSyste$%%String PQ Pargs4
=
Console%%!riteLine3LBKi fro$ $anaged C&&B4<
return -<
C
=otice that each language is making use of the Console class defined in the
Syste$ na$espa+e.
1eyond minor syntactic variations, these three applications look and feel very
much alike, both physically and logically.
"he most fundamental namespace to get your hands around is named <ystem.
"his namespace provides a core body of types that you will need to leverage
time and again as a .=3" developer.
.n below table we shown many namespaces which are used commonly.
24
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
25
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
A++essing a Na$espa+e Progra$$ati+ally
Consider <ystem namespace assume that <ystem.Console represents a class
named Console that is contained within a namespace called ystem.
.n CF, the using keyword simplifies the process of referencing types defined in a
particular namespace.
"he main window renders a bar chart based on some information obtained from
a backend database and displays your company logo, for this we need
namespaces.
Kere are all the na$espa+es used to 2uild this appli+ation.
using Syste$< Reneral 2ase +lass li2rary types.
using Syste$.1ra0ing< Rraphi+al rendering types.
using Syste$.!indo0s.(or$s< RUI 0idget types.
using Syste$.1ata< Reneral data-+entri+ types.
using Syste$.1ata.SSlClient< 'S STL Server data a++ess types.
$nce you have specified some number of namespaces 'and set a reference to
the assemblies that define them(, you are free to create instances of the types
they contain.
*or e/ample, an instance of the 1itmap class created as 'defined in the
<ystem.Drawing namespace(, you can writeE
E;pli+itly list the na$espa+es used 2y this file.
using Syste$<
using Syste$.1ra0ing<
+lass 'yApp
=
pu2li+ void 1isplayLogo34
= Create a #-H#- pi;el 2it$ap.
*it$ap +o$panyLogo ? ne0 *it$ap3#-8 #-4< U
C
C
26
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
1ecause your application is referencing <ystem.Drawing, the compiler is able to
resolve the 1itmap class as a member of this namespace. .f you did not specify
the <ystem.Drawing namespace, you would be issued a compiler error.
Dou can declare variables using a fully !ualified name as wellE
Not listing Syste$.1ra0ing na$espa+eN
using Syste$<
+lass 'yApp
=
pu2li+ void 1isplayLogo34
=
Using fully Sualified na$e.
Syste$.1ra0ing.*it$ap +o$panyLogo ?
ne0 Syste$.1ra0ing.*it$ap3#-8 #-4<
...
C
C
While defining a type using the fully ;ualified name provides greater readability, .
think youd agree that the CF using keyword reduces keystrokes.
>owever, always remember that this techni;ue is simply a shorthand notation for
specifying a types fully ;ualified name, and each approach results in the e"act
same underlying C.? 'given the fact that C.? code always makes use of fully
;ualified names( and has no effect on performance or the si4e of the assembly.
7eferen+ing E;ternal Asse$2lies
.n addition to specifying a namespace via the CF using keyword, you also need to tell
the CF compiler the name of the assembly containing the actual C.? definition for the
referenced type.
- vast majority of the .=3" *ramework assemblies are located under a specific
directory termed the global assembly cache 3(AC4.
$n a Windows machine, this can be located under V0indirVWAsse$2ly.
27
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
1eploying the .NET 7unti$e
>owever, if you deploy an assembly to a computer that does not have .=3" installed, it
will fail to run. *or this reason, )icrosoft provides a setup package named dotnetf/.e/e
that can be freely shipped and installed along with your custom software. "his
installation program is included with the .=3" *ramework ,.8 <DP, and it is also freely
downloadable from )icrosoft.
$nce dotnetf/.e/e is installed, the target machine will now contain the .=3" base class
libraries, .=3" runtime 'mscoree.dll(, and additional .=3" infrastructure 'such as the
Q-C(.
Note Do be aware that if you are building a .=3" web application, the end users
machine does not need to be configured with the .=3" *ramework, as the browser will
simply receive generic >")? and possibly clientside 5ava<cript.
$M)O"TANT *+E#T$ON#
7. 1riefly e/plain the history of .=3". 3/plain the building components of .=3" and
their responsibilities. or 2)
,. What are the building blocks of .=3" frame workR <how their relationship, with a
neat block diagram. 3/plain C"< in detail. or 78)
+. 3/plain features and building blocks of .=3" framework. or 78)
B. What are the building blocks of .=3" platformR Qive the relationship between
.=3" runtime layer and the base class ?ibrary. S)
C. 3/plain 5itter, along with its benefits. 3/plain how C?: host an application on
.=3" platform .Qive the block diagram. 2)
2. What is an assemblyR 3/plain each component of an assembly. Differentiate bAn
singlefile assembly and multifile assembly. S)
H. What is .=3" assemblyR What does it containR 3/plain each of them. 78)
S. Write a note on .=3" =amespace. B)
T. 3/plain the role of the common intermediate ?anguage 2)
28
C# PROGRAMMING AND .NET UNIT-1The Philosophy of .NET
VIK
78. 3/plain the limitations and comple/ities found within the technologies prior to
.=3". 1riefly e/plain how .=3" attempts to simplify the same. 78)
77. 3/plain the formal definitions of all possible C"< types. 78)
7,. What is the role of .=3" type )etadataR Qive an e/ample. B)
7+. 3/plain the C?:. .llustrate the workflow that takes place bAn the source code,
given .=3" compiler and the .=3" e/ecution engine. S)

Você também pode gostar