Unit 1
Unit 1
C#[Link] [Link]
UNIT-1 [Link]
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 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.
[Link] 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.
[Link]:
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 [Link].
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
[Link]-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#[Link] [Link]
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.
Some of the benefits provided by .NET, the three key (and interrelated) entities that make it all
possible: the CLR,CTS, andCLS.
Thus, if you build .NET types that only expose CLS-compliant features, you can rest
assured that [Link]-aware languages can consume them.
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#[Link] [Link]
[Link]
*.[Link]
.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*.[Link]-awarecompiler,the
resultingmodule isbundledintoanassembly.
AnassemblycontainsCILcode,whichisconceptuallysimilartoJavabytecodeinthatitisnotcom
piledtoplatform-specificinstructionsuntilabsolutelynecessary.
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#[Link] [Link]
and metadata for various types). The other related modules contain a module
levelmanifest,CIL,andtype metadata.
TheRole oftheCommonIntermediateLanguage
[Link] of
which .NET-aware language you choose, the associated compiler emitsCILinstructions.
Forexample,
//
[Link]
System;
namespaceCalculatorExample
{
//Thisclass
containstheapp'[Link]
CalcApp
{
staticvoidMain()
{
Calcc=newCalc();int
ans=[Link](10,84);
[Link]("10+ 84is{0}.",ans);
//WaitforusertopresstheEnter
[Link]();
}
}
//TheC#calculator.
publicclassCalc
{
publicintAdd(intx,int y)
{returnx+y; }
}
}
Once the C# compiler ([Link]) 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#[Link] [Link]
Forexample,[Link],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,[Link]-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#[Link] [Link]
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.
[Link]
[Link],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#[Link] [Link]
[Link],lookthemetadatathathasbeengeneratedfortheAdd()meth
odof theC# Calc class.
TypeDef#2(02000003)
-------------------------------------------------------
TypDefName:[Link](02000
003)Flags:[Public][AutoLayout] [Class]
[AnsiClass] [BeforeFieldInit]
(00100001)Extends:01000001[TypeRef]S
[Link]#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)
.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,
[Link]:
.assemblyexternmscorlib
{
.publickeytoken =(B7 7A5C561934 E089)
.ver[Link]
}
.assemblyCSharpCalculator
{
.hashalgorithm0x00008004
.ver[Link]
}
.[Link]
.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#[Link] [Link]
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
[Link].
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#[Link] [Link]
//AC#
[Link]
oint
{
// Structures can contain
[Link],yPos;
// Structures can contain parameterized
[Link](intx,inty)
{xPos= x;yPos=y;}
//
[Link]
icvoidDisplay()
{
[Link]("({0},{1}",xPos,yPos);
}
}
CTSInterfaceTypes
Interfacesarenothingmorethananamedcollectionofabstractmemberdefinitions,whichmay
besupported(i.e., implemented) by agivenclassorstructure.
InC#,interfacetypesaredefinedusingthe interfacekeyword.
For example:
// A C# interface
[Link]
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#[Link] [Link]
CTSEnumerationTypes
Enumerationsareahandyprogrammingconstructthatallowsyoutogroupname/valuepairs.
Forexample,assumeyouarecreatingavideo-gameapplicationthatallowstheplayerto
selectoneofthree character categories(Wizard, Fighter,orThief).
Ratherthankeepingtrackofrawnumericalvaluestorepresenteachpossibility,youcould
buildacustom enumerationusingtheenumkeyword:
// A C# enumeration
[Link]
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,[Link].
CTSDelegateTypes
[Link]-safeC-stylefunctionpointer.
[Link],r
atherthanasimplepointertoarawmemoryaddress.
In C#,delegates aredeclaredusingthedelegatekeyword:
//This C#delegatetype can'pointto'anymethod
// returning an integer and taking two integers as
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
[Link].
15
C#[Link] [Link]
UnderstandingtheCommonLanguageSpecification
Differentlanguagesexpressthesameprogrammingconstructsinunique,languagespecificterm
s.
For example, in C# you denote string concatenation using the plus operator
(+),whileinVB .NET you typicallymake useof theampersand (&).
'[Link].
PublicSubMyMethod()
'Someinterestingcode...
EndSub
//C#methodreturningnothing.
publicvoidMyMethod()
{//Someinterestingcode.. .}
[Link] runtime,compilers ([Link])emitasimilarsetof CILinstructions.
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#[Link] [Link]
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
[Link];
...
returnx+y;
}
}
EnsuringCLSCompliance
Instructc#[Link]:
//TelltheC#compilertocheckforCLS compliance.
[assembly:[Link](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#[Link] [Link]
UnderstandingtheCommonLanguageRuntime
.NETruntimeprovidesasinglewell-definedruntimelayerthatissharedbyall
[Link]-aware.
The crux of the CLR is physically represented by a library named [Link](aka the
Common Object Runtime Execution Engine). When an assembly isreferenced for use,
[Link] 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
[Link]
berof discreteassemblies,[Link].
[Link] 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
[Link],youautomaticallyhaveaccesstothisparticularassembly.
The workflow that takes place between your source code (which is making use of
baseclasslibrarytypes),agiven .NETcompiler,andthe .NETexecutionengine.
18
C#[Link] [Link]
19
C#[Link] [Link]
TheAssembly/Namespace/TypeDistinction
Anamespaceisagroupingof relatedtypescontainedinanassembly.
Keepallthetypeswithinthebaseclasslibrarieswellorganized,[Link]
byofthenamespaceconcept.
Forexample,
o [Link]/Orelatedtypes;
o [Link]
Very important single assembly (such as [Link]) 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#,[Link],andManagedExtensionsforC++:
// Hello world in
C#using
System;publicclas
sMyApp
{
staticvoidMain()
{
[Link]("HifromC#");
}
}
20
C#[Link] [Link]
'[Link]
TImportsSystem
PublicModuleMyA
ppSubMain()
[Link]("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.
[Link] namespace
provides a core body of types that you will need to leveragetimeandagainas [Link]
developer.
Inbelowtableweshownmanynamespaceswhichareusedcommonly.
21
C#[Link] [Link]
22
C#[Link] [Link]
AccessingaNamespaceProgrammatically
Consider System namespace assume that [Link] represents a
classnamedConsolethatiscontained withinanamespacecalledSystem.
In C#, the using keyword simplifies the process of referencing types defined in
aparticularnamespace.
Themainwindowrendersabarchartbasedonsomeinformationobtainedfromaback-
enddatabaseanddisplaysyourcompanylogo,forthisweneednamespaces.
//Hereareallthenamespacesusedtobuildthis application.
usingSystem;
//[Link];
//[Link]; // GUIwidget
types.
[Link]; //Generaldata-centrictypes.
[Link]; //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([Link]
e), you can write:
//
[Link]
ngSystem;
[Link]
g;classMyApp
{
publicvoidDisplayLogo()
{ //Createa20_20pixelbitmap.
BitmapcompanyLogo =new Bitmap(20,20);…
}
}
23
C#[Link] [Link]
Because your application is referencing [Link], the compiler is able toresolve
the Bitmap class as a member of this namespace. If you did not
[Link],youwouldbeissuedacompilererror.
Youcandeclarevariablesusingafullyqualifiedname aswell:
//
[Link]!
usingSystem;
classMyApp
{
publicvoidDisplayLogo()
{
// Using fully qualified
[Link]
nyLogo=
[Link](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.
[Link]
lassemblycache (GAC).
Ona Windows machine, this can be located under %windir%\Assembly.
24
C#[Link] [Link]
[Link]
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
[Link]
program is included with the .NET Framework 2.0 SDK, and it is also
freelydownloadablefromMicrosoft.
Once [Link] is installed, the target machine will now contain the .NET base
classlibraries, .NET runtime ([Link]), 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. [Link]
lities. or 6M
2. [Link]?
Showtheirrelationship,[Link]. or 10M
3. [Link] 10M
4. [Link]?Givetherelationshipbetween
.NET runtimelayerandthebaseclassLibrary. 8M
5. ExplainJitter,[Link]
.[Link] theblockdiagram. 6M
6. Whatisanassembly?[Link]/
nsinglefileassemblyandmultifileassembly. 8M
7. [Link]?Whatdoesitcontain?Explaineachofthem. 10M
8. Write anote on .NETNamespace. 4M
9. ExplaintheroleofthecommonintermediateLanguage 6M
25
C#[Link] [Link]
10. Explainthelimitationsandcomplexitiesfoundwithinthetechnologiespriorto
.[Link] simplifythesame. 10M
11. Explaint
heformaldefinitionsof allpossibleCTStypes. 10M
12. Whatist
[Link]?Giveanexample. 4M
13. Explai
[Link]/
nthesourcecode,[Link]. 8M