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

C-.NET-Unit-1

Uploaded by

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

C-.NET-Unit-1

Uploaded by

Sheela Mense
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

1

C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET

UNIT-1 ThePhilosophyof.NET

Introducing the Building Blocks of the .NET Platform (CLR, CTS, and CLS),
Anatomy of C# program, The System. Environment Class, The System.
Console Class, Understanding Value Types and Reference Types, The System
Data types, Operators, Decision Constructs, Iteration Constructs, , The System.
String data types, String Builder, .NET Array Types, Defining Classes and
Creating objects, Pillars of OOP, C#‟s Inheritance Support, C #‟s Polymorphic
Support, Understanding C# Partial types, Understanding Boxing and Unboxing
Operations.

UnderstandingthePreviousStateofAffairs

Life AsaC/Win32APIProgrammer:

 Developing software for the Windows family of operating systems involved usingthe C
programming language in conjunction with the Windows applicationprogramminginterface.

Advantages:
 Simple to develop applications.
 System Programming is easily done using C

Disadvantages
 Manual memorymanagement,uglypointer arithmetic,anduglysyntactical constructs.
 C is a structured language; it lacks the benefits provided by the object-
orientedapproach.

Life As a C++/MFC Programmer:


 C++ can be thought of as an object-oriented layer on top of C. Thus, even though C++
programmers benefit from the famed “pillars of OOP”(encapsulation,inheritance, and
polymorphism), they are still at the mercy of the painful aspectsof the C language (e.g.,
manual memory management, ugly pointer arithmetic,anduglysyntactical constructs).
 The Microsoft Foundation Classes (MFC) provides built in classes the developer with a
set ofC++ classes that facilitate the construction of Win32 applications. The main roleof
MFC is to wrap a “sane subset” of the raw Win32 API behind a number
ofclasses,magicmacros,andnumerouscode-generationtools(aka wizards).
 C++ programming remains a difficult and error-pron eexperience,given its historical
roots in C.

Life As a Visual Basic 6.0 Programmer:


 VB6 is popular due to its ability to build complex user interfaces, code
libraries(e.g.,COMservers), and data access logic with minimal fuss and bother.
 Even more than MFC, VB6 hides the complexities of the raw Win32 API from view
using a number ofintegratedcode wizards,intrinsic data types,classes,andVB-
specificfunctions
2
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET
 VB6 is not a fully object-oriented language;rather,it is“objectaware.”
 For example, VB6 does not allow the programmer to establish “is-a”
relationshipsbetween types (i.e., no classical inheritance) and has no intrinsic support
forparameterizedclass construction.
 VB6 doesn’t provide the ability to build multithreaded applications unless you
arewillingto dropdown tolow-levelWin32 API calls.

Life AsaJava/J2EEProgrammer
 The Java programming language is (almost) completely object oriented and
hasitssyntactic roots inC++.
 It supports platform independence.
 Java (as a language) cleans up many unsavory syntactical aspects of C++.
Java(asaplatform)provides programmers with a large number of predefined “packages”
that contain various type definitions.
 Using these types, Java programmers are able to build “100% Pure Java” applications
complete with database connectivity,messaging support,web-enabled frontends, and a
rich user interface.

The.NET Solution
The .NET Framework is a completely new model for building systems on the Windows family of
operating systems, as well as on numerous non-Microsoft operating systems such as Mac OSX
and various Unix/Linux distributions.

Somecorefeaturesprovidedcourtesyof.NET:
1. Full interoperability with existing code:.Existing COM binariescan commingle (i.e.,
interop) with newer .NET binaries and vice versa. Also, Platform Invocation Services
(PInvoke) allows you to call C-based libraries from.NETcode.

2. Complete and total language integration: Unlike COM, .NET supports cross-language
inheritance, cross-language exception handling, and cross-languagedebugging.
3. A common runtime engine shared by all .NET-aware languages: One aspect of this
engine is a well-defined set of types that each .NET-aware language“understands.”

4. A base class library: This library provides shelter from the complexities of
rawAPIcallsandoffersaconsistentobjectmodelusedbyall.NET-awarelanguages.

5. No more COM plumbing: IClassFactory, IUnknown, IDispatch, IDL code, and the evil
VARIANTcompliant data types (BSTR, SAFEARRAY, and so forth) have no place in a
native .NET binary.
3
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET

6. A truly simplified deployment model: Under .NET, there is no need to register a binary
unit into the system registry. Furthermore, .NET allows multiple versions of the same
*.dll to exist in harmony on a single machine.

Introducingthe BuildingBlocks ofthe.NETPlatform(theCLR,CTS,and CLS)

Some of the benefits provided by .NET, the three key (and interrelated) entities that make it all
possible: the CLR,CTS, andCLS.

Common language runtime,orCLR:


 The primary role of the CLR is to locate, load, and manage .NET types on yourbehalf.
 The CLR also takes care of a number of low-level details such as memory management
and performing security checks.

Common Type System or CTS:


 The CTS specification fully describes all possible data types and
programmingconstructssupported by the run time,specifie show these entities can inter
act with each other, and details how they are represented in the .NET meta data format.

Common Language Specification or CLS:


 The CLS is a related specification that defines a subset of common types and
programming constructs that all.NETprogramming languages can agree on.

 Thus, if you build .NET types that only expose CLS-compliant features, you can rest
assured that all.NET-aware languages can consume them.

The Role of the Base Class Libraries


 The .NET platform provides a base class library that is available to all .NET
programming languages.
 Base class library encapsulate various primitives such as threads,file input/output(I/O),
graphical rendering,and interaction with various external hardware devices, but it also
provides support for a number of services required by most real-world applications.
 For example, the base class libraries define types that facilitate database access,XML
manipulation, programmatic security, and the construction of web-enabled front ends.
The relationship between the CLR, CTS, CLS, and the base class library, as shown in Figure.
4
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET

WhatC#Brings totheTable?
 C#’ssyntacticconstructsaremodeledaftervariousaspectsofVB6.0andC++.
 For example, like VB6, C# supports the notion of formal type properties and theability to
declare methods taking varying number of arguments (via parameterarrays).
 Like C++, C# allows you to overload operators, to create
structures,enumerations,and callbackfunctions (via delegates).
 C#isahybridofnumerouslanguages,syntacticallyclean,providespowerandflexibility.
TheC#languageoffersthefollowingfeatures(manyofwhicharesharedbyother
.NET-awareprogramminglanguages):
1. Nopointersrequired!C#programstypicallyhavenoneedfordirectpointermanipulation
2. Automaticmemorymanagementthroughgarbagecollection,SoC#doesnotsupport adelete
keyword.
3. Formalsyntacticconstructsforenumerations,structures,andclassproperties.
4. TheC++-likeabilitytooverloadoperatorsforacustomtype,withoutthecomplexity.
5. TheabilitytobuildgenerictypesandgenericmembersusingasyntaxverysimilartoC+
+templates.
6. Fullsupportforinterface-basedprogrammingtechniques.
7. Fullsupportforaspect-orientedprogramming(AOP)techniquesviaattributes.
5
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET
AnOverviewof.NETAssemblies
 *.dll.NETbinariesdonotexportmethodstofacilitatecommunicationswiththeCOM
 .NET binaries are not described using COM type libraries and are not registeredintothe
systemregistry.
 .NET binaries do not contain platform-specific instructions, but rather platform-agnostic
intermediate language(IL) andtypemetadata.
 Whena*.dllor*.exehasbeencreatedusinga.NET-awarecompiler,the

resultingmodule isbundledintoanassembly.
 AnassemblycontainsCILcode,whichisconceptuallysimilartoJavabytecodeinthatitisnotcom
piledtoplatform-specificinstructionsuntilabsolutelynecessary.

 Assemblies also contain metadata. .NET metadata is a dramatic improvement


toCOMtypemetadata. .NETmetadataisalwayspresentandisautomaticallygeneratedbyagive
n .NET-aware compiler.
 Assemblies themselves are also described using metadata, which is officiallytermeda
manifest
 The manifest contains information about the current version of the assembly,culture
information (used for localizing string and image resources), and a list
ofallexternallyreferencedassembliesthatarerequiredfor properexecution.

Single-FileandMultifile Assemblies
Single-file assembly If an assembly is composed of a single *.dll or *.exemodule, called as
single-file assembly. Single-file assemblies contain all the
necessaryCIL,metadata,andassociatedmanifestinanautonomous,single,well-definedpackage.
Multifile assemblies are composed ofnumerous .NETbinaries, each ofwhichis termed a module.
When building a multifile assembly, one of these modules (termedthe primary module) must
contain the assembly manifest (and possibly CIL instructions
6
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET
and metadata for various types). The other related modules contain a module
levelmanifest,CIL,andtype metadata.
TheRole oftheCommonIntermediateLanguage

CILisalanguagethatsitsaboveanyparticularplatform-specificinstructionset.Regardless of
which .NET-aware language you choose, the associated compiler emitsCILinstructions.
Forexample,
//
Calc.csusing
System;
namespaceCalculatorExample
{
//Thisclass
containstheapp'sentrypoint.publicclass
CalcApp
{
staticvoidMain()
{
Calcc=newCalc();int
ans=c.Add(10,84);
Console.WriteLine("10+ 84is{0}.",ans);
//WaitforusertopresstheEnter
keybeforeshuttingdown.Console.ReadLine();
}
}
//TheC#calculator.

publicclassCalc
{
publicintAdd(intx,int y)
{returnx+y; }
}
}

Once the C# compiler (csc.exe) compiles this source code file, you end up with a single-file
*.exe assembly that contains a manifest, CIL instructions, and metadata describingeachaspect of
the Calc andCalcAppclasses.
7
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET

Forexample,ifyouweretoopenthisassemblyusingildasm.exe,youwouldfindthattheAdd()method
isrepresentedusingCIL such asthefollowing:

.methodpublichidebysiginstanceint32 Add(int32x,int32y)cilmanaged
{
//Codesize8(0x8)
.maxstack2
.localsinit([0]int32CS$1$0000
)IL_0000:ldarg.1
IL_0001:
ldarg.2IL_0002:
addIL_0003:
stloc.0IL_0004:br.s
IL_0006
IL_0006:
ldloc.0IL_000
7:ret
}//endof methodCalc::Add

TheC#compileremitsCIL,notplatform-specificinstructions.

BenefitsofCIL:
 Each .NET-aware compiler produces nearly identical CIL instructions.
Therefore,alllanguages areabletointeract withina well-defined binaryarena.
 CILisplatform-agnostic,the.NETFrameworkitselfisplatform-agnostic,providing the same
benefits Java developers have grown accustomed to (i.e., asinglecodebaserunningon
numerousoperatingsystems).
CompilingCILtoPlatform-SpecificInstructions:

 Due to the fact that assemblies contain CIL instructions, rather than platform-
specificinstructions, CIL codemustbe compiledbeforeuse.
 TheentitythatcompilesCILcodeintomeaningfulCPUinstructionsistermeda
just-in-time(JIT)compiler orJitter
8
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET
 The .NET runtime environment leverages (Use to maximum advantage) a JITcompiler
for each CPU targeting the runtime, each optimized for the underlyingplatform.

 Forexample,
1. If you are building a .NET application that is to be deployed to a handhelddevice
(such as a Pocket PC), the corresponding Jitter is well equipped to
runwithinalowmemoryenvironment.
2. If you are deploying your assembly to a back-end server (where memory isseldom an
issue), the Jitter will be optimized to function in a high memoryenvironment.

 In this way, developers can write a single body of code that can be efficiently JIT-
compiledandexecutedonmachineswith differentarchitectures.
 Jitter compiles CIL instructions into corresponding machine code, it will cache
theresultsinmemoryin amannersuitedto thetarget operatingsystem.
 In this way, if acall is made to a method named PrintDocument(), the CILinstructions are
compiled into platform specific instructions on the first invocationand retained in
memory for later use. Therefore, the next time PrintDocument() iscalled,there isnoneed
torecompile the CIL.

TheRoleof.NETTypeMetadata

 a.NETassemblycontainsfull,complete,andaccuratemetadata,whichdescribeseachandeveryt
ype(class,structure,enumeration,andsoforth)defined in the binary, as well as the members
of each type (properties, methods,events,and so on).
 Because .NET metadata is so wickedly meticulous, assemblies are completelyself-
describing entities and .NET binaries have no need to be registered into thesystem
registry.
9
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET
Toillustratetheformatof.NETtypemetadata,lookthemetadatathathasbeengeneratedfortheAdd()meth
odof theC# Calc class.

TypeDef#2(02000003)
-------------------------------------------------------
TypDefName:CalculatorExample.Calc(02000
003)Flags:[Public][AutoLayout] [Class]
[AnsiClass] [BeforeFieldInit]
(00100001)Extends:01000001[TypeRef]S
ystem.ObjectMethod#1(06000003)
-------------------------------------------------------
MethodName:Add(06000003)
Flags:[Public][HideBySig][ReuseSlot]
(00000086)RVA: 0x00002090
ImplFlags:[IL][Managed]
(00000000)CallCnvntn:
[DEFAULT]
hasThisRetur
nType: I42
Arguments
Argument#1:I4
Argument#2:I4
2Parameters
(1)ParamToken:(08000001)Name:xflags:[none](00000000)
(2)ParamToken:(08000002)Name:yflags:[none](00000000)

 Metadataisusedbynumerousaspectsofthe.NETruntime environment, aswellasbyvarious


development tools.
 For example, theIntelliSensefeatureprovided by Visual Studio 2005is
madepossiblebyreadinganassembly’smetadataatdesign time.
 Metadataisalsousedbyvariousobjectbrowsingutilities,debuggingtools,andtheC#compiler
itself.
 Metadataisthebackboneofnumerous.NETtechnologiesincludingremoting,reflection,latebin
ding, XMLwebservices, andobject serialization.
10
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET
TheRoleoftheAssemblyManifest

 .NETassemblyalsocontainsmetadatathatdescribestheassemblyitself(technicallytermed
amanifest).
 Themanifestdocumentsallexternalassembliesrequiredbythecurrentassemblytofunctioncorr
ectly,theassembly’sversionnumber,copyrightinformation, and so forth. Like type
metadata, it is always the job of the compilerto generatetheassembly’smanifest.
Forexample,
CSharpCalculator.exemanifest:
.assemblyexternmscorlib
{
.publickeytoken =(B7 7A5C561934 E089)
.ver2:0:0:0
}
.assemblyCSharpCalculator
{
.hashalgorithm0x00008004
.ver0:0:0:0
}
.moduleCSharpCalculator.exe
.imagebase0x00400000
.subsystem0x00000003
.filealignment512
.corflags0x00000001

UnderstandingtheCommonTypeSystem

CommonTypeSystem(CTS)isaformalspecificationthatdocumentshowtypesmustbedefined inorder
tobe hosted bytheCLR.
TherearefivetypesdefinedbytheCTSintheirlanguage.
1. CTSClassTypes
4. CTSEnumerationTypes
2. CTSStructureTypes
5. CTSDelegateTypes
3. CTSInterfaceTypes
11
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET

CTSClassTypes
 Every .NET-awarelanguagesupports, atthevery least,thenotion ofaclasstype,whichis
thecornerstoneof object-orientedprogramming(OOP).
 Aclassmaybecomposedofanynumberofmembers(suchasproperties,methods,andevents)
anddata points (fields).
 InC#,classesaredeclaredusingtheclasskeyword:

//AC#classtype.
publicclass Calc
{
publicintAdd(intx,inty)
{returnx+y;}
}

CTSClassCharacteristics
1. Sealedclassescannotfunctionasabaseclasstootherclasses.
2. The CTS allows a class to implement any number of interfaces._ an interface isa
collection of abstract members that provide a contract between the object andobjectuser.
3. Abstract classes cannot be directly created, but are intended to define
commonbehaviorsforderivedtypes.Concreteclassescanbecreateddirectly.
4. Each class must be configured with a visibility attribute. Basically, this traitdefines if the
class may be used by external assemblies, or only from within thedefiningassembly.

CTSStructureTypes
 A structure can be thought of as a lightweight class type having value-basedsemantics
 Structures arebestsuited for modeling geometric and mathematical data,andarecreated
inC# usingthe struct keyword:
12
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET

//AC#
structuretype.structP
oint
{
// Structures can contain
fields.publicintxPos,yPos;
// Structures can contain parameterized
constructors.publicPoint(intx,inty)
{xPos= x;yPos=y;}
//
Structuresmaydefinemethods.publ
icvoidDisplay()
{
Console.WriteLine("({0},{1}",xPos,yPos);
}
}

CTSInterfaceTypes
 Interfacesarenothingmorethananamedcollectionofabstractmemberdefinitions,whichmay
besupported(i.e., implemented) by agivenclassorstructure.
 InC#,interfacetypesaredefinedusingthe interfacekeyword.
For example:
// A C# interface
type.publicinterfaceI
Draw
{
voidDraw();
}
On their own, interfaces are of little use. However, when a class or structure implementsa given
interface in its unique way, you are able to request access to the suppliedfunctionalityusingan
interfacereferencein apolymorphicmanner.
13
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET
CTSEnumerationTypes
 Enumerationsareahandyprogrammingconstructthatallowsyoutogroupname/valuepairs.
 Forexample,assumeyouarecreatingavideo-gameapplicationthatallowstheplayerto
selectoneofthree character categories(Wizard, Fighter,orThief).
 Ratherthankeepingtrackofrawnumericalvaluestorepresenteachpossibility,youcould
buildacustom enumerationusingtheenumkeyword:
// A C# enumeration
type.publicenumCharact
erType
{
Wizard=100,
Fighter=200,
Thief=300
}
 By default, the storage used to hold each item is a 32-bit integer; however, it ispossible to
alter this storage slot if need be (e.g., when programming for a low-memorydevice suchas
aPocketPC).
 Also, the CTS demands that enumerated types derive from a common
baseclass,System.Enum.

CTSDelegateTypes
 Delegatesarethe.NETequivalentofatype-safeC-stylefunctionpointer.
 Thekeydifferenceisthata.NETdelegateisaclassthatderivesfromSystem.MulticastDelegate,r
atherthanasimplepointertoarawmemoryaddress.
 In C#,delegates aredeclaredusingthedelegatekeyword:
//This C#delegatetype can'pointto'anymethod
// returning an integer and taking two integers as

input.public delegate intBinaryOp(int x, inty);


14
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET
 Delegates are useful when you wish to provide a way for one entity to forward
acalltoanotherentity,andprovidethefoundationforthe.NET eventarchitecture
 Delegates have intrinsic support for multicasting (i.e., forwarding a request
tomultiplerecipients) and asynchronousmethod invocations.

CTSTypeMembers
 Atypememberisconstrainedbytheset{constructor,finalizer,staticconstructor, nested type,
operator, method, property, indexer, field, read onlyfield,constant,event}.
 Forexample,
o Each member has a givenvisibility trait(e.g.,public,private, protected,andsoforth).
 Some members may be declared as abstract to enforce a polymorphic
behavioronderivedtypesaswellasvirtualtodefineacanned(butoverridable)implementation.
 Also, most members may be configured as static (bound at the class level)
orinstance(boundattheobject level).
IntrinsicCTSDataTypes
Uniquekeywordused todeclareanintrinsicCTS datatype,all languagekeywordsultimatelyresolveto
thesametypedefinedinanassemblynamedmscorlib.dll.
15
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET

UnderstandingtheCommonLanguageSpecification
 Differentlanguagesexpressthesameprogrammingconstructsinunique,languagespecificterm
s.
 For example, in C# you denote string concatenation using the plus operator
(+),whileinVB .NET you typicallymake useof theampersand (&).

'VB.NETmethodreturningnothing.
PublicSubMyMethod()
'Someinterestingcode...
EndSub
//C#methodreturningnothing.
publicvoidMyMethod()
{//Someinterestingcode.. .}
As.NET runtime,compilers (vbc.exeorcsc.exe)emitasimilarsetof CILinstructions.

 The Common Language Specification (CLS) is asetofrulesthatdescribe in vivid detail


the minimal and complete set of features 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 thattargetthe.NETplatform.

 The CLS is ultimately a set of rules that compiler builders must conform too thierfunction
seamlessly within the .NET universe. Each rule is assigned a simplename (e.g.,“CLS
Rule 6”) and describes how this rule affects those who build thecompilersas wellas those
who(in someway)interact withthem.

Rule1:CLSrulesapplyonlytothosepartsofatypethatareexposedoutsidethedefiningassembly.
TheonlyaspectsofatypethatmustconformtotheCLSarethememberdefinitionsthemselves(i.e.,
namingconventions,parameters,andreturntypes).
16
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET

To illustrate, the following Add() method is not CLS-compliant, as the parametersand


return values make use of unsigned data (which is not a requirement of theCLS):

publicclassCalc
{
// Exposed unsigned data is not CLS
compliant!publiculongAdd(ulongx,ulongy)
{return x+y;}
}
However, ifyouweretosimplymakeuseof unsigneddatainternallyasfollows:
publicclassCalc
{
publicintAdd(intx,inty)
{
// As this ulong variable is only used internally,we are still CLS
compliant.ulongtemp;
...
returnx+y;
}
}

EnsuringCLSCompliance
Instructc#compilertocheckthecodeforCLScomplianceusingasingle.NETattribute:

//TelltheC#compilertocheckforCLS compliance.

[assembly:System.CLSCompliant(true)]
[CLSCompliant] attribute will instruct the C# compiler to check each and every line ofcode
against the rules of the CLS. If any CLS violations are discovered, you receive acompilererror
and adescriptionoftheoffendingcode.
17
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET
UnderstandingtheCommonLanguageRuntime
 .NETruntimeprovidesasinglewell-definedruntimelayerthatissharedbyall
languagesandplatformsthatare.NET-aware.
 The crux of the CLR is physically represented by a library named mscoree.dll(aka the
Common Object Runtime Execution Engine). When an assembly isreferenced for use,
mscoree.dll is loaded automatically, which in turn loads therequired assembly into
memory. The runtime engine is responsible for a numberoftasks.

 Theyare:
1. It is the entity in charge of resolving the location of an assembly and
findingtherequestedtypewithin thebinarybyreadingthecontainedmetadata.
2. The CLR then lays out the type in memory, compiles the associated CIL
intoplatform-specific instructions, performs any necessary security checks,
andthenexecutesthecode in question.
3. The CLR will also interact with the types contained within the .NET base
classlibrarieswhenrequired.Althoughtheentirebaseclasslibraryhasbeenbrokenintoanum
berof discreteassemblies,thekeyassemblyismscorlib.dll.

mscorlib.dllcontains a large number of core types that encapsulate a wide variety ofcommon
programming tasks as well as the core data types used by all .NET
languages.Whenyoubuild.NETsolutions,youautomaticallyhaveaccesstothisparticularassembly.
The workflow that takes place between your source code (which is making use of
baseclasslibrarytypes),agiven .NETcompiler,andthe .NETexecutionengine.
18
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET
19
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET

TheAssembly/Namespace/TypeDistinction
 Anamespaceisagroupingof relatedtypescontainedinanassembly.
 Keepallthetypeswithinthebaseclasslibrarieswellorganized,the.NETplatformmakespossible
byofthenamespaceconcept.

 Forexample,
o TheSystem.IOnamespacecontainsfileI/Orelatedtypes;
o TheSystem.Datanamespacedefinesbasicdatabasetypes

 Very important single assembly (such as mscorlib.dll) can contain any number
ofnamespaces,each ofwhich cancontainanynumberoftypes.
 Thekeydifferencebetweenthisapproachandalanguage-specificlibrarysuchas MFC is that
any language targeting the .NET runtime makes use of the
samenamespacesandsametypes.

 Forexample,thefollowingthreeprogramsallillustratethe“HelloWorld”application,writtenin
C#,VB.NET,andManagedExtensionsforC++:

// Hello world in
C#using
System;publicclas
sMyApp
{
staticvoidMain()
{
Console.WriteLine("HifromC#");
}
}
20
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET

'HelloworldinVB.NE
TImportsSystem
PublicModuleMyA
ppSubMain()
Console.WriteLine("HifromVB.N
ET")EndSub
EndModule

//HelloworldinManagedExtensionsforC+
+#include "stdafx.h"
usingnamespaceSystem;
intmain(array<System::String^>^args)
{
Console::WriteLine(L"HifrommanagedC+
+");return0;
}

 NoticethateachlanguageismakinguseoftheConsoleclassdefinedinthe
Systemnamespace.
 Beyondminorsyntacticvariations,thesethreeapplicationslookandfeelverymuchalike,both
physicallyand logically.
 ThemostfundamentalnamespacetogetyourhandsaroundisnamedSystem.This namespace
provides a core body of types that you will need to leveragetimeandagainas a.NET
developer.
 Inbelowtableweshownmanynamespaceswhichareusedcommonly.
21
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET
22
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET
AccessingaNamespaceProgrammatically
 Consider System namespace assume that System.Console represents a
classnamedConsolethatiscontained withinanamespacecalledSystem.
 In C#, the using keyword simplifies the process of referencing types defined in
aparticularnamespace.
 Themainwindowrendersabarchartbasedonsomeinformationobtainedfromaback-
enddatabaseanddisplaysyourcompanylogo,forthisweneednamespaces.

//Hereareallthenamespacesusedtobuildthis application.
usingSystem;

//Generalbaseclasslibrarytypes.usingSystem.Drawing;

//Graphicalrenderingtypes.usingSystem.Windows.Forms; // GUIwidget
types.
usingSystem.Data; //Generaldata-centrictypes.
usingSystem.Data.SqlClient; //MSSQLServerdataaccesstypes.

 Once you have specified some number of namespaces (and set a reference tothe
assemblies that define them), you are free to create instances of the typestheycontain.
 Forexample,aninstanceoftheBitmapclasscreatedas(definedintheSystem.Drawingnamespac
e), you can write:
//
Explicitlylistthenamespacesusedbythisfile.usi
ngSystem;
usingSystem.Drawin
g;classMyApp
{
publicvoidDisplayLogo()
{ //Createa20_20pixelbitmap.
BitmapcompanyLogo =new Bitmap(20,20);…
}
}
23
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET
 Because your application is referencing System.Drawing, the compiler is able toresolve
the Bitmap class as a member of this namespace. If you did not
specifytheSystem.Drawingnamespace,youwouldbeissuedacompilererror.

Youcandeclarevariablesusingafullyqualifiedname aswell:
//
NotlistingSystem.Drawingnamespace!
usingSystem;
classMyApp
{
publicvoidDisplayLogo()
{
// Using fully qualified
name.System.Drawing.Bitmapcompa
nyLogo=
newSystem.Drawing.Bitmap(20,20);
...
}
}

 While defining a type using the fully qualified name provides greater readability,
Ithinkyou’d agreethat theC#usingkeyword reduceskeystrokes.
 However, always remember that this technique is simply a shorthand notation
forspecifying a type’s fully qualified name, and each approach results in the exactsame
underlying CIL (given the fact that CIL code always makes use of
fullyqualifiednames)andhasnoeffectonperformanceorthesizeoftheassembly.

ReferencingExternal Assemblies
In addition to specifying a namespace via the C# using keyword, you also need to tellthe C#
compiler the name of the assembly containing the actual CIL definition for thereferencedtype.
Avastmajorityofthe.NETFrameworkassembliesarelocatedunderaspecificdirectorytermedthegloba
lassemblycache (GAC).
Ona Windows machine, this can be located under %windir%\Assembly.
24
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET
Deployingthe.NETRuntime
However, if you deploy an assembly to a computer that does not have .NET installed, itwill fail
to run. For this reason, Microsoft provides a setup package named
dotnetfx.exethatcanbefreelyshippedandinstalledalongwithyourcustomsoftware.Thisinstallation
program is included with the .NET Framework 2.0 SDK, and it is also
freelydownloadablefromMicrosoft.
Once dotnetfx.exe is installed, the target machine will now contain the .NET base
classlibraries, .NET runtime (mscoree.dll), and additional .NET infrastructure (such as theGAC).
Note Do be aware that if you are building a .NET web application, the end user’smachine does
not need to be configured with the .NET Framework, as the browser willsimplyreceive generic
HTML andpossiblyclient-sideJavaScript.

IMPORTANTQUESTIONS

1. Brieflyexplainthehistoryof.NET.Explainthebuildingcomponentsof.NETandtheirresponsibi
lities. or 6M
2. Whatarethebuildingblocksof.NETframework?
Showtheirrelationship,withaneatblockdiagram.ExplainCTSindetail. or 10M
3. Explainfeaturesandbuildingblocksof.NETframework.or 10M
4. Whatarethebuildingblocksof.NETplatform?Givetherelationshipbetween
.NET runtimelayerandthebaseclassLibrary. 8M
5. ExplainJitter,alongwithitsbenefits.ExplainhowCLRhostanapplicationon
.NETplatform.Give theblockdiagram. 6M
6. Whatisanassembly?Explaineachcomponentofanassembly.Differentiateb/
nsinglefileassemblyandmultifileassembly. 8M
7. Whatis.NETassembly?Whatdoesitcontain?Explaineachofthem. 10M
8. Write anote on .NETNamespace. 4M
9. ExplaintheroleofthecommonintermediateLanguage 6M
25
C#PROGRAMMINGAND.NET UNIT-1ThePhilosophyof.NET
10. Explainthelimitationsandcomplexitiesfoundwithinthetechnologiespriorto
.NET.Brieflyexplainhow.NETattemptsto simplifythesame. 10M
11. Explaint
heformaldefinitionsof allpossibleCTStypes. 10M
12. Whatist
heroleof.NETtypeMetadata?Giveanexample. 4M
13. Explai
ntheCLR.Illustratetheworkflowthattakesplaceb/
nthesourcecode,given.NETcompilerandthe.NETexecutionengine. 8M

You might also like