Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 95

.

NET Framework FAQ


Andy McMullan The .NET Framework FAQ was first posted in July 2000 and is re!ularly updated. "t co#ers the fundamentals of the .NET Framework includin! assem$lies !ar$a!e collection security interop with %&M and remotin!. Newcomers to the .NET framework may wish to read the FAQ from top to $ottom as a tutorial. More e'perienced practitioners may prefer to consult the contents list for topics of particular interest. This FAQ was inspired $y discussions on the (&TNET mailin! list. The list has now $een split into se#eral (&TNET)* lists ) for details see http+,,discuss.de#elop.com,. %hristophe -auer has translated the FAQ into French. .oyal has translated the FAQ into %hinese. "f you like this FAQ you mi!ht $e interested in my %/ FAQ for %00 1ro!rammers.

Latest updates: 27-Jan-2005+ .ewritten 2hould " implement Finali3e on my class4 2hould " implement "(isposa$le4 25-Jan-2005+ 5hat6s new in the .NET 2.0 class li$rary4 21-Jan-2005+ 5hat si3e is a .NET o$7ect4 18-Jan-2005+ 5hen do " need to call 8%.9eepAli#e4 1 -Jan-2005+ 5hat is the lapsed listener pro$lem4 08-Jan-2005+ 5hat is the difference $etween an e#ent and a dele!ate4 0!-Jan-2005+ New section on .NET 2.0

"ontents

:. "ntroduction

o o o o o o

:.: 5hat is .NET4 :.2 5hen was .NET announced4 :.; 5hat #ersions of .NET are there4 :.< 5hat operatin! systems does the .NET Framework run on4 :.= 5hat tools can " use to de#elop .NET applications4 :.> 5hy did they call it .NET4

2. Terminolo!y

o o o o o o

2.: 5hat is the %-"4 "s it the same as the %-.4 2.2 5hat is the %T2 and how does it relate to the %-24 2.; 5hat is "-4 2.< 5hat is %/4 2.= 5hat does 6mana!ed6 mean in the .NET conte't4 2.> 5hat is reflection4

;. Assem$lies

o o o o o o

;.: 5hat is an assem$ly4 ;.2 ?ow can " produce an assem$ly4 ;.; 5hat is the difference $etween a pri#ate assem$ly and a shared assem$ly4 ;.< ?ow do assem$lies find each other4 ;.= ?ow does assem$ly #ersionin! work4 ;.> ?ow can " de#elop an application that automatically updates itself from the we$4

<. Application (omains

o o o

<.: 5hat is an application domain4 <.2 ?ow does an App(omain !et created4 <.; %an " write my own .NET host4

=. 8ar$a!e %ollection

o o o o o o o o o

=.: 5hat is !ar$a!e collection4 =.2 "s it true that o$7ects don6t always !et destroyed immediately when the last reference !oes away4 =.; 5hy doesn6t the .NET runtime offer deterministic destruction4 =.< "s the lack of deterministic destruction in .NET a pro$lem4 =.= 2hould " implement Finali3e on my class4 2hould " implement "(isposa$le4 =.> (o " ha#e any control o#er the !ar$a!e collection al!orithm4 =.@ ?ow can " find out what the !ar$a!e collector is doin!4 =.A 5hat is the lapsed listener pro$lem4 =.B 5hen do " need to use 8%.9eepAli#e4

>. 2eriali3ation

o o o o o o o o

>.: 5hat is seriali3ation4 >.2 (oes the .NET Framework ha#e in)$uilt support for seriali3ation4 >.; " want to seriali3e instances of my class. 2hould " use *ml2eriali3er 2oapFormatter or CinaryFormatter4 >.< %an " customise the seriali3ation process4 >.= 5hy is *ml2eriali3er so slow4 >.> 5hy do " !et errors when " try to seriali3e a ?ashta$le4 >.@ *ml2eriali3er is throwin! a !eneric DThere was an error reflectin! My%lassD error. ?ow do " find out what the pro$lem is4 >.A 5hy am " !ettin! an "n#alid&perationE'ception when " seriali3e an Array-ist4

@. Attri$utes

@.: 5hat are attri$utes4

o o

@.2 %an " create my own metadata attri$utes4 @.; %an " create my own conte't atti$utes4

A. %ode Access 2ecurity

o o o o o o o o

A.: 5hat is %ode Access 2ecurity E%A2F4 A.2 ?ow does %A2 work4 A.; 5ho defines the %A2 code !roups4 A.< ?ow do " define my own code !roup4 A.= ?ow do " chan!e the permission set for a code !roup4 A.> %an " create my own permission set4 A.@ "6m ha#in! some trou$le with %A2. ?ow can " trou$leshoot the pro$lem4 A.A " can6t $e $othered with %A2. %an " turn it off4

B. "ntermediate -an!ua!e E"-F

o o o o o

B.: %an " look at the "- for an assem$ly4 B.2 %an source code $e re#erse)en!ineered from "-4 B.; ?ow can " stop my code $ein! re#erse)en!ineered from "-4 B.< %an " write "- pro!rams directly4 B.= %an " do thin!s in "- that " can6t do in %/4

:0. "mplications for %&M

o o o o o o

:0.: (oes .NET replace %&M4 :0.2 "s (%&M dead4 :0.; "s %&M0 dead4 :0.< %an " use %&M components from .NET pro!rams4 :0.= %an " use .NET components from %&M pro!rams4 :0.> "s AT- redundant in the .NET world4

::. Miscellaneous

o o o o o

::.: ?ow does .NET remotin! work4 ::.2 ?ow can " !et at the 5in;2 A1" from a .NET pro!ram4 ::.; ?ow do " write to the application confi!uration file at runtime4 ::.< 5hat is the difference $etween an e#ent and a dele!ate4 ::.= 5hat si3e is a .NET o$7ect4

:2. .NET 2.0

o o o o

:2.: 5hat are the new features of .NET 2.04 :2.2 5hat are the new 2.0 features useful for4 :2.; 5hat6s the pro$lem with .NET !enerics4 :2.< 5hat6s new in the .NET 2.0 class li$rary4

:;. %lass -i$rary

:;.: Threads

:;.:.: ?ow do " spawn a thread4 :;.:.2 ?ow do " stop a thread4 :;.:.; ?ow do " use the thread pool4 :;.:.< ?ow do " know when my thread pool work item has completed4 :;.:.= ?ow do " pre#ent concurrent access to my data4

:;.2 Tracin!


:<. .esources

:;.2.: "s there $uilt)in support for tracin!,lo!!in!4 :;.2.2 %an " redirect tracin! to a file4 :;.2.; %an " customise the trace output4 :;.2.< Are there any third party lo!!in! components a#aila$le4

o o o

:<.: .ecommended $ooks :<.2 5e$ sites :<.; Clo!s

1. #ntrodu$t%on

1.1 &'at %s .NET(


.NET is a !eneral)purpose software de#elopment platform similar to Ja#a. At its core is a #irtual machine that turns intermediate lan!ua!e E"-F into machine code. ?i!h)le#el lan!ua!e compilers for %/ GC.NET and %00 are pro#ided to turn source code into "-. %/ is a new pro!rammin! lan!ua!e #ery similar to Ja#a. An e'tensi#e class li$rary is included featurin! all the functionality one mi!ht e'pect from a contempory de#elopment platform ) windows 8H" de#elopment E5indows FormsF data$ase access EA(&.NETF we$ de#elopment EA21.NETF we$ ser#ices *M- etc. 2ee also Microsoft6s definition.

1.2 &'en was .NET announ$ed(


Cill 8ates deli#ered a keynote at Forum 2000 held June 22 2000 outlinin! the .NET 6#ision6. The July 2000 1(% had a num$er of sessions on .NET technolo!y and dele!ates were !i#en %(s containin! a pre)release #ersion of the .NET framework,2(9 and Gisual 2tudio.NET.

1. &'at )ers%ons o* .NET are t'ere(

The final #ersion of the :.0 2(9 and runtime was made pu$licly a#aila$le around >pm 12T on :=)Jan) 2002. At the same time the final #ersion of Gisual 2tudio.NET was made a#aila$le to M2(N su$scri$ers. .NET :.: was released in April 200; ) it6s mostly $u! fi'es for :.0. .NET 2.0 is e'pected in 200=.

1.+ &'at operat%n, s-stems does t'e .NET Framework run on(
The runtime supports 5indows 2er#er 200; 5indows *1 5indows 2000 NT< 21>a and 5indows ME,BA. 5indows B= is not supported. 2ome parts of the framework do not work on all platforms ) for e'ample A21.NET is only supported on *1 and 5indows 2000,200;. 5indows BA,ME cannot $e used for de#elopment. ""2 is not supported on 5indows *1 ?ome Edition and so cannot $e used to host A21.NET. ?owe#er the A21.NET 5e$ Matri' we$ ser#er does run on *1 ?ome. The .NET %ompact Framework is a #ersion of the .NET Framework for mo$ile de#ices runnin! 5indows %E or 5indows Mo$ile. The Mono pro7ect has a #ersion of the .NET Framework that runs on -inu'.

1.5 &'at too.s $an # use to de)e.op .NET app.%$at%ons(


There are a num$er of tools descri$ed here in ascendin! order of cost+

The .NET Framework 2(9 is free and includes command)line compilers for %00 %/ and GC.NET and #arious other utilities to aid de#elopment. A21.NET 5e$ Matri' is a free A21.NET de#elopment en#ironment from Microsoft. As well as a 8H" de#elopment en#ironment the download includes a simple we$ ser#er that can $e used instead of ""2 to host A21.NET apps. This opens up A21.NET de#elopment to users of 5indows *1 ?ome Edition which cannot run ""2. Microsoft Gisual %/ .NET 2tandard 200; is a cheap Earound I:00F #ersion of Gisual 2tudio limited to one lan!ua!e and also with limited wi3ard support. For e'ample there6s no wi3ard support for class li$raries or custom H" controls. Hseful for $e!inners to learn with or for sa##y de#elopers who can work around the deficiencies in the supplied wi3ards. As well as %/ there are GC.NET and %00 #ersions. Microsoft Gisual 2tudio.NET 1rofessional 200;. "f you ha#e a license for Gisual 2tudio >.0 you can !et the up!rade. Jou can also up!rade from G2.NET 2002 for a token I;0. Gisual 2tudio.NET includes support for all the M2 lan!ua!es E%/ %00 GC.NETF and has e'tensi#e wi3ard support.

At the top end of the price spectrum are the Gisual 2tudio.NET 200; Enterprise and Enterprise Architect editions. These offer e'tra features such as Gisual 2ourcesafe E#ersion controlF and performance and analysis tools. %heck out the Gisual 2tudio.NET Feature %omparison at http+,,msdn.microsoft.com,#studio,howto$uy,choosin!.asp

1.! &'- d%d t'e- $a.. %t .NET(

" don6t know what they were thinkin!. They certainly weren6t thinkin! of people usin! search tools. "t6s meanin!less marketin! nonsense ) $est not to think a$out it.

2. Term%no.o,-

2.1 &'at %s t'e "L#( #s %t t'e same as t'e "L/(


The %-" E%ommon -an!ua!e "nfrastructureF is the definiton of the fundamentals of the .NET framework ) the %ommon Type 2ystem E%T2F metadata the Girtual E'ecution En#ironment EGE2F and its use of intermediate lan!ua!e E"-F and the support of multiple pro!rammin! lan!ua!es #ia the %ommon -an!ua!e 2pecification E%-2F. The %-" is documented throu!h E%MA ) see http+,,msdn.microsoft.com,net,ecma, for more details. The %-. E%ommon -an!ua!e .untimeF is Microsoft6s primary implementation of the %-". Microsoft also ha#e a shared source implementation known as .&T&. for educational purposes as well as the .NET %ompact Framework for mo$ile de#ices. Non)Microsoft %-" implementations include Mono and (ot8NH 1orta$le.NET.

2.2 &'at %s t'e "T01 and 'ow does %t re.ate to t'e "L0(
%T2 K %ommon Type 2ystem. This is the full ran!e of types that the .NET runtime understands. Not all .NET lan!ua!es support all the types in the %T2. %-2 K %ommon -an!ua!e 2pecification. This is a su$set of the %T2 which all .NET lan!ua!es are e'pected to support. The idea is that any pro!ram which uses %-2)compliant types can interoperate with any .NET pro!ram written in any lan!ua!e. This interop is #ery fine)!rained ) for e'ample a GC.NET class can inherit from a %/ class.

2. &'at %s #L(
"- K "ntermediate -an!ua!e. Also known as M2"- EMicrosoft "ntermediate -an!ua!eF or %"- E%ommon "ntermediate -an!ua!eF. All .NET source code Eof any lan!ua!eF is compiled to "- durin! de#elopment. The "- is then con#erted to machine code at the point where the software is installed or Emore commonlyF at run)time $y a Just)"n)Time EJ"TF compiler.

2.+ &'at %s "2(


%/ is a new lan!ua!e desi!ned $y Microsoft to work with the .NET framework. "n their D"ntroduction to %/D whitepaper Microsoft descri$e %/ as follows+ D%/ is a simple modern o$7ect oriented and type)safe pro!rammin! lan!ua!e deri#ed from % and %0 0. %/ Epronounced L% sharpMF is firmly planted in the % and %00 family tree of lan!ua!es and will immediately $e familiar to % and %00 pro!rammers. %/ aims to com$ine the hi!h producti#ity of Gisual Casic and the raw power of %00.D 2u$stitute 6Ja#a6 for 6%/6 in the Nuote a$o#e and you6ll see that the statement still works pretty well +)F.

"f you are a %00 pro!rammer you mi!ht like to check out my %/ FAQ.

2.5 &'at does 3mana,ed3 mean %n t'e .NET $onte4t(


The term 6mana!ed6 is the cause of much confusion. "t is used in #arious places within .NET meanin! sli!htly different thin!s. Mana!ed code+ The .NET framework pro#ides se#eral core run)time ser#ices to the pro!rams that run within it ) for e'ample e'ception handlin! and security. For these ser#ices to work the code must pro#ide a minimum le#el of information to the runtime. 2uch code is called mana!ed code. Mana!ed data+ This is data that is allocated and freed $y the .NET runtime6s !ar$a!e collector. Mana!ed classes+ This is usually referred to in the conte't of Mana!ed E'tensions EMEF for %00. 5hen usin! ME %00 a class can $e marked with the OO!c keyword. As the name su!!ests this means that the memory for instances of the class is mana!ed $y the !ar$a!e collector $ut it also means more than that. The class $ecomes a fully paid)up mem$er of the .NET community with the $enefits and restrictions that $rin!s. An e'ample of a $enefit is proper interop with classes written in other lan!ua!es ) for e'ample a mana!ed %00 class can inherit from a GC class. An e'ample of a restriction is that a mana!ed class can only inherit from one $ase class.

2.! &'at %s re*.e$t%on(


All .NET compilers produce metadata a$out the types defined in the modules they produce. This metadata is packa!ed alon! with the module Emodules in turn are packa!ed to!ether in assem$liesF and can $e accessed $y a mechanism called re*.e$t%on. The 2ystem..eflection namespace contains classes that can $e used to interro!ate the types for a module,assem$ly. Hsin! reflection to access .NET metadata is #ery similar to usin! "Type-i$,"Type"nfo to access type li$rary data in %&M and it is used for similar purposes ) e.!. determinin! data type si3es for marshalin! data across conte't,process,machine $oundaries. .eflection can also $e used to dynamically in#oke methods Esee 2ystem.Type."n#okeMem$erF or e#en create types dynamically at run)time Esee 2ystem..eflection.Emit.TypeCuilderF.

. Assem5.%es

.1 &'at %s an assem5.-(
An assem$ly is sometimes descri$ed as a lo!ical .E*E or .(-- and can $e an application Ewith a main entry pointF or a library. An assem$ly consists of one or more files Edlls e'es html files etcF and represents a !roup of resources type definitions and implementations of those types. An assem$ly may also contain references to other assem$lies. These resources types and references are descri$ed in a $lock of data called a manifest. The manifest is part of the assem$ly thus makin! the assem$ly self)descri$in!. An important aspect of assem$lies is that they are part of the identity of a type. The identity of a type is the assem$ly that houses it com$ined with the type name. This means for e'ample that if assem$ly A e'ports a type called T and assem$ly C e'ports a type called T the .NET runtime sees these as two

completely different types. Furthermore don6t !et confused $etween assem$lies and namespaces ) namespaces are merely a hierarchical way of or!anisin! type names. To the runtime type names are type names re!ardless of whether namespaces are used to or!anise the names. "t6s the assem$ly plus the typename Ere!ardless of whether the type name $elon!s to a namespaceF that uniNuely indentifies a type to the runtime. Assem$lies are also important in .NET with respect to security ) many of the security restrictions are enforced at the assem$ly $oundary. Finally assem$lies are the unit of #ersionin! in .NET ) more on this $elow.

.2 6ow $an # produ$e an assem5.-(


The simplest way to produce an assem$ly is directly from a .NET compiler. For e'ample the followin! %/ pro!ram+
public class CTest { public CTest() { System.Console.WriteLine( "Hello from CTest" ); } }

can $e compiled into a li$rary assem$ly EdllF like this+


csc /t library ctest.cs

Jou can then #iew the contents of the assem$ly $y runnin! the D"- (isassem$lerD tool that comes with the .NET 2(9. Alternati#ely you can compile your source into modules and then com$ine the modules into an assem$ly usin! the assem$ly linker Eal.e'eF. For the %/ compiler the ,tar!et+module switch is used to !enerate a module instead of an assem$ly.

. &'at %s t'e d%**eren$e 5etween a pr%)ate assem5.- and a s'ared assem5.-(

Lo$at%on and )%s%5%.%t-+ A pri#ate assem$ly is normally used $y a sin!le application and is stored in the application6s directory or a su$)directory $eneath. A shared assem$ly is normally stored in the !lo$al assem$ly cache which is a repository of assem$lies maintained $y the .NET runtime. 2hared assem$lies are usually li$raries of code which many applications will find useful e.!. the .NET framework classes. 7ers%on%n,+ The runtime enforces #ersionin! constraints only on shared assem$lies not on pri#ate assem$lies.

.+ 6ow do assem5.%es *%nd ea$' ot'er(


Cy searchin! directory paths. There are se#eral factors which can affect the path Esuch as the App(omain host and application confi!uration filesF $ut for pri#ate assem$lies the search path is normally the application6s directory and its su$)directories. For shared assem$lies the search path is normally same as the pri#ate assem$ly path plus the shared assem$ly cache.

.5 6ow does assem5.- )ers%on%n, work(

Each assem$ly has a #ersion num$er called the compati$ility #ersion. Also each reference to an assem$ly Efrom another assem$lyF includes $oth the name and #ersion of the referenced assem$ly. The #ersion num$er has four numeric parts Ee.!. =.=.2.;;F. Assem$lies with either of the first two parts different are normally #iewed as incompati$le. "f the first two parts are the same $ut the third is different the assem$lies are deemed as 6may$e compati$le6. "f only the fourth part is different the assem$lies are deemed compati$le. ?owe#er this is 7ust the default !uideline ) it is the #ersion policy that decides to what e'tent these rules are enforced. The #ersion policy can $e specified #ia the application confi!uration file. /emem5er+ #ersionin! is only applied to shared assem$lies not pri#ate assem$lies.

.! 6ow $an # de)e.op an app.%$at%on t'at automat%$a..- updates %tse.* *rom t'e we5(
For .NET :.' use the Hpdater Application Clock. For .NET 2.' use %lick&nce.

+. App.%$at%on 8oma%ns

+.1 &'at %s an app.%$at%on doma%n(


An App(omain can $e thou!ht of as a li!htwei!ht process. Multiple App(omains can e'ist inside a 5in;2 process. The primary purpose of the App(omain is to isolate applications from each other and so it is particularly useful in hostin! scenarios such as A21.NET. An App(omain can $e destroyed $y the host without affectin! other App(omains in the process. 5in;2 processes pro#ide isolation $y ha#in! distinct memory address spaces. This is effecti#e $ut e'pensi#e. The .NET runtime enforces App(omain isolation $y keepin! control o#er the use of memory ) all memory in the App(omain is mana!ed $y the .NET runtime so the runtime can ensure that App(omains do not access each other6s memory. &ne non)o$#ious use of App(omains is for unloadin! types. %urrently the only way to unload a .NET type is to destroy the App(omain it is loaded into. This is particularly useful if you create and destroy types on)the)fly #ia reflection. Microsoft ha#e an App(omain FAQ.

+.2 6ow does an App8oma%n ,et $reated(


App(omains are usually created $y hosts. E'amples of hosts are the 5indows 2hell A21.NET and "E. 5hen you run a .NET application from the command)line the host is the 2hell. The 2hell creates a new App(omain for e#ery application. App(omains can also $e e'plicitly created $y .NET applications. ?ere is a %/ sample which creates an App(omain creates an instance of an o$7ect inside it and then e'ecutes one of the o$7ect6s methods+
usin! System; usin! System."untime."emotin!; usin! System."eflection;

public class C#pp$omain%nfo &ars'al(y"ef)b*ect { public strin! +et,ame() { return #pp$omain.Current$omain.-rien.ly,ame; } } public class #pp { public static int &ain() { #pp$omain a. / #pp$omain.Create$omain( "#n.y0s ne1 .omain" ); C#pp$omain%nfo a.%nfo / (C#pp$omain%nfo)a..Create%nstance#n.2n1rap( #ssembly.+etCallin!#ssembly().+et,ame().,ame3 "C#pp$omain%nfo" ); Console.WriteLine( "Create. #pp$omain name / " 4 a.%nfo.+et,ame() ); return 5; } }

+. "an # wr%te m- own .NET 'ost(


Jes. For an e'ample of how to do this take a look at the source for the dm.net moniker de#eloped $y Jason 5hittin!ton and (on Co'. There is also a code sample in the .NET 2(9 called %or?ost.

5. 9ar5a,e "o..e$t%on

5.1 &'at %s ,ar5a,e $o..e$t%on(


8ar$a!e collection is a heap)mana!ement strate!y where a run)time component takes responsi$ility for mana!in! the lifetime of the memory used $y o$7ects. This concept is not new to .NET ) Ja#a and many other lan!ua!es,runtimes ha#e used !ar$a!e collection for some time.

5.2 #s %t true t'at o5:e$ts don3t a.wa-s ,et destro-ed %mmed%ate.- w'en t'e .ast re*eren$e ,oes awa-(
Jes. The !ar$a!e collector offers no !uarantees a$out the time when an o$7ect will $e destroyed and its memory reclaimed. There was an interestin! thread on the (&TNET list started $y %hris 2ells a$out the implications of non)deterministic destruction of o$7ects in %/. "n &cto$er 2000 Microsoft6s Crian ?arry posted a len!thy analysis of the pro$lem. %hris 2ells6 response to Crian6s postin! is here.

5. &'- doesn3t t'e .NET runt%me o**er determ%n%st%$ destru$t%on(


Cecause of the !ar$a!e collection al!orithm. The .NET !ar$a!e collector works $y periodically runnin! throu!h a list of all the o$7ects that are currently $ein! referenced $y an application. All the o$7ects that it doesn6t find durin! this search are ready to $e destroyed and the memory reclaimed. The implication of this al!orithm is that the runtime doesn6t !et notified immediately when the final reference on an o$7ect !oes away ) it only finds out durin! the ne't 6sweep6 of the heap.

Futhermore this type of al!orithm works $est $y performin! the !ar$a!e collection sweep as rarely as possi$le. Normally heap e'haustion is the tri!!er for a collection sweep.

5.+ #s t'e .a$k o* determ%n%st%$ destru$t%on %n .NET a pro5.em(


"t6s certainly an issue that affects component desi!n. "f you ha#e o$7ects that maintain e'pensi#e or scarce resources Ee.!. data$ase locksF you need to pro#ide some way to tell the o$7ect to release the resource when it is done. Microsoft recommend that you pro#ide a method called (isposeEF for this purpose. ?owe#er this causes pro$lems for distri$uted o$7ects ) in a distri$uted system who calls the (isposeEF method4 2ome form of reference)countin! or ownership)mana!ement mechanism is needed to handle distri$uted o$7ects ) unfortunately the runtime offers no help with this.

5.5 0'ou.d # %mp.ement F%na.%;e on m- $.ass( 0'ou.d # %mp.ement #8%sposa5.e(


This issue is a little more comple' than it first appears. There are really two cate!ories of class that reNuire deterministic destruction ) the first cate!ory manipulate unmana!ed types directly E!enerally #ia an "nt1tr representin! an &2 handleF whereas the second cate!ory manipulate managed types that reNuire deterministic destruction. An e'ample of the first cate!ory is a class with an "nt1tr mem$er representin! an &2 file handle. An e'ample of the second cate!ory is a class with a 2ystem."&.File2tream mem$er. For the first cate!ory it makes sense to implement "(isposa$le and o#erride Finali3e. This allows the o$7ect user to 6do the ri!ht thin!6 $y callin! (ispose $ut also pro#ides a fall$ack of freein! the unmana!ed resource in the Finali3er should the callin! code fail in its duty. ?owe#er this lo!ic does not apply to the second cate!ory of class with only mana!ed resources. "n this case implementin! Finali3e is pointless as mana!ed mem$er o$7ects cannot $e accessed in the Finali3er. This is $ecause there is no !uarantee a$out the orderin! of Finali3er e'ecution. 2o only the (ispose method should $e implemented. E"f you think a$out it it doesn6t really make sense to call (ispose on mem$er o$7ects from a Finali3er anyway as the mem$er o$7ect6s Finali3er will do the reNuired cleanup anyway.F For classes that need to implement "(isposa$le and o#erride Finali3e see Microsoft6s documented pattern. Note that some de#elopers ar!ue that implementin! a Finali3er is always a $ad idea as it hides a $u! in your code Ei.e. the lack of a (ispose callF. A less radical approach is to implement Finali3e $ut include a (e$u!.Assert at the start thus si!nallin! the pro$lem in de#eloper $uilds $ut allowin! the cleanup to occur in release $uilds.

5.! 8o # 'a)e an- $ontro. o)er t'e ,ar5a,e $o..e$t%on a.,or%t'm(


A little. For e'ample the 2ystem.8% class e'poses a %ollect method which forces the !ar$a!e collector to collect all unreferenced o$7ects immediately. Also there is a ,$"on$urrent settin! that can $e specified #ia the application confi!uration file. This specifies whether or not the !ar$a!e collector performs some of its collection acti#ities on a separate thread. The settin! only applies on multi)processor machines and defaults to true.

5.7 6ow $an # *%nd out w'at t'e ,ar5a,e $o..e$tor %s do%n,(
-ots of interestin! statistics are e'ported from the .NET runtime #ia the 6.NET %-. '''6 performance counters. Hse 1erformance Monitor to #iew them.

5.8 &'at %s t'e .apsed .%stener pro5.em(


The lapsed listener pro$lem is one of the primary causes of leaks in .NET applications. "t occurs when a su$scri$er Eor 6listener6F si!ns up for a pu$lisher6s e#ent $ut fails to unsu$scri$e. The failure to unsu$scri$e means that the pu$lisher maintains a reference to the su$scri$er as lon! as the pu$lisher is ali#e. For some pu$lishers this may $e the duration of the application. This situation causes two pro$lems. The o$#ious pro$lem is the leaka!e of the su$scri$er o$7ect. The other pro$lem is the performance de!redation due to the pu$lisher sendin! redundant notifications to 63om$ie6 su$scri$ers. There are at least a couple of solutions to the pro$lem. The simplest is to make sure the su$scri$er is unsu$scri$ed from the pu$lisher typically $y addin! an Hnsu$scri$eEF method to the su$scri$er. Another solution documented here $y 2hawn Gan Ness is to chan!e the pu$lisher to use weak references in its su$scri$er list.

5.< &'en do # need to use 9".=eepA.%)e(


"t6s #ery unintuiti#e $ut the runtime can decide that an o$7ect is !ar$a!e much sooner than you e'pect. More specifically an o$7ect can $ecome !ar$a!e while a method is e'ecutin! on the o$7ect which is contrary to most de#elopers6 e'pectations. %hris Crumme e'plains the issue on his $lo!. "6#e taken %hris6s code and e'panded it into a full app that you can play with if you want to pro#e to yourself that this is a real pro$lem+
usin! System; usin! System."untime.%nteropSer6ices; class Win78 { 9$ll%mport(":ernel78..ll"); public static e<tern %nt=tr Create>6ent( %nt=tr lp>6ent#ttributes3 bool b&anual"eset3bool b%nitialState3 strin! lp,ame); 9$ll%mport(":ernel78..ll"3 SetLast>rror/true); public static e<tern bool CloseHan.le(%nt=tr ')b*ect); 9$ll%mport(":ernel78..ll"); public static e<tern bool Set>6ent(%nt=tr '>6ent); } class >6ent2ser { public >6ent2ser() { '>6ent / Win78.Create>6ent( %nt=tr.?ero3 false3 false3 null ); } @>6ent2ser() { Win78.CloseHan.le( '>6ent ); Console.WriteLine(">6ent2ser finaliAe."); } public 6oi. 2se>6ent() {

2se>6ent%nStatic( t'is.'>6ent ); } static 6oi. 2se>6ent%nStatic( %nt=tr '>6ent ) { //+C.Collect(); bool bSuccess / Win78.Set>6ent( '>6ent ); Console.WriteLine( "Set>6ent " 4 (bSuccess B "succee.e." "-#%L>$C") ); } %nt=tr '>6ent; } class #pp { static 6oi. &ain(strin!9; ar!s) { >6ent2ser e6ent2ser / ne1 >6ent2ser(); e6ent2ser.2se>6ent(); } }

"f you run this code it6ll pro$a$ly work fine and you6ll !et the followin! output+
Set>6ent succee.e. >6ent$emo finaliAe.

?owe#er if you uncomment the 8%.%ollectEF call in the HseE#ent"n2taticEF method you6ll !et this output+
>6ent$emo finaliAe. Set>6ent -#%L>$C

ENote that you need to use a release $uild to reproduce this pro$lem.F 2o what6s happenin! here4 5ell at the point where HseE#entEF calls HseE#ent"n2taticEF a copy is taken of the hE#ent field and there are no further references to the E#entHser o$7ect anywhere in the code. 2o as far as the runtime is concerned the E#entHser o$7ect is !ar$a!e and can $e collected. Normally of course the collection won6t happen immediately so you6ll !et away with it $ut sooner or later a collection will occur at the wron! time and your app will fail. A solution to this pro$lem is to add a call to 8%.9eepAli#eEthisF to the end of the HseE#ent method as %hris e'plains.

!. 0er%a.%;at%on

!.1 &'at %s ser%a.%;at%on(


2eriali3ation is the process of con#ertin! an o$7ect into a stream of $ytes. (eseriali3ation is the opposite process i.e. creatin! an o$7ect from a stream of $ytes. 2eriali3ation,(eseriali3ation is mostly used to transport o$7ects Ee.!. durin! remotin!F or to persist o$7ects Ee.!. to a file or data$aseF.

!.2 8oes t'e .NET Framework 'a)e %n-5u%.t support *or ser%a.%;at%on(
There are two separate mechanisms pro#ided $y the .NET class li$rary ) *ml2eriali3er and 2oapFormatter,CinaryFormatter. Microsoft uses *ml2eriali3er for 5e$ 2er#ices and 2oapFormatter,CinaryFormatter for remotin!. Coth are a#aila$le for use in your own code.

!. # want to ser%a.%;e %nstan$es o* m- $.ass. 0'ou.d # use >m.0er%a.%;er1 0oapFormatter or ?%nar-Formatter(


"t depends. *ml2eriali3er has se#ere limitations such as the reNuirement that the tar!et class has a parameterless constructor and only pu$lic read,write properties and fields can $e seriali3ed. ?owe#er on the plus side *ml2eriali3er has !ood support for customisin! the *M- document that is produced or consumed. *ml2eriali3er6s features mean that it is most suita$le for cross)platform work or for constructin! o$7ects from e'istin! *M- documents. 2oapFormatter and CinaryFormatter ha#e fewer limitations than *ml2eriali3er. They can seriali3e pri#ate fields for e'ample. ?owe#er they $oth reNuire that the tar!et class $e marked with the P2eriali3a$leQ attri$ute so like *ml2eriali3er the class needs to $e written with seriali3ation in mind. Also there are some Nuirks to watch out for ) for e'ample on deseriali3ation the constructor of the new o$7ect is not in#oked. The choice $etween 2oapFormatter and CinaryFormatter depends on the application. CinaryFormatter makes sense where $oth seriali3ation and deseriali3ation will $e performed on the .NET platform and where performance is important. 2oapFormatter !enerally makes more sense in all other cases for ease of de$u!!in! if nothin! else.

!.+ "an # $ustom%se t'e ser%a.%;at%on pro$ess(


Jes. *ml2eriali3er supports a ran!e of attri$utes that can $e used to confi!ure seriali3ation for a particular class. For e'ample a field or property can $e marked with the P*ml"!noreQ attri$ute to e'clude it from seriali3ation. Another e'ample is the P*mlElementQ attri$ute which can $e used to specify the *M- element name to $e used for a particular property or field. 2eriali3ation #ia 2oapFormatter,CinaryFormatter can also $e controlled to some e'tent $y attri$utes. For e'ample the PNon2eriali3edQ attri$ute is the eNui#alent of *ml2eriali3er6s P*ml"!noreQ attri$ute. Hltimate control of the seriali3ation process can $e achei#ed $y implementin! the the "2eriali3a$le interface on the class whose instances are to $e seriali3ed.

!.5 &'- %s >m.0er%a.%;er so s.ow(


There is a once)per)process)per)type o#erhead with *ml2eriali3er. 2o the first time you seriali3e or deseriali3e an o$7ect of a !i#en type in an application there is a si!nificant delay. This normally doesn6t matter $ut it may mean for e'ample that *ml2eriali3er is a poor choice for loadin! confi!uration settin!s durin! startup of a 8H" application.

!.! &'- do # ,et errors w'en # tr- to ser%a.%;e a 6as'ta5.e(


*ml2eriali3er will refuse to seriali3e instances of any class that implements "(ictionary e.!. ?ashta$le. 2oapFormatter and CinaryFormatter do not ha#e this restriction.

!.7 >m.0er%a.%;er %s t'row%n, a ,ener%$ @T'ere was an error re*.e$t%n, A-".ass@ error. 6ow do # *%nd out w'at t'e pro5.em %s(
-ook at the "nnerE'ception property of the e'ception that is thrown to !et a more specific error messa!e.

!.8 &'- am # ,ett%n, an #n)a.%dBperat%onE4$ept%on w'en # ser%a.%;e an Arra-L%st(


*ml2eriali3er needs to know in ad#ance what type of o$7ects it will find in an Array-ist. To specify the type use the *mlArray"tem atti$ute like this+
public class =erson { public strin! ,ame; public int #!e; } public class =opulation { 9Dml#rray%tem(typeof(=erson)); public #rrayList =eople; }

7. Attr%5utes

7.1 &'at are attr%5utes(


There are at least two types of .NET attri$ute. The first type " will refer to as a metadata attri$ute ) it allows some data to $e attached to a class or method. This data $ecomes part of the metadata for the class and Elike other class metadataF can $e accessed #ia reflection. An e'ample of a metadata attri$ute is Pseriali3a$leQ which can $e attached to a class and means that instances of the class can $e seriali3ed.
9serialiAable; public class CTest {}

The other type of attri$ute is a context attri$ute. %onte't attri$utes use a similar synta' to metadata attri$utes $ut they are fundamentally different. %onte't attri$utes pro#ide an interception mechanism where$y instance acti#ation and method calls can $e pre) and,or post)processed. "f you ha#e encountered 9eith Crown6s uni#ersal dele!ator you6ll $e familiar with this idea.

7.2 "an # $reate m- own metadata attr%5utes(


Jes. 2imply deri#e a class from 2ystem.Attri$ute and mark it with the Attri$uteHsa!e attri$ute. For e'ample+
9#ttribute2sa!e(#ttributeTar!ets.Class); public class %nspire.(y#ttribute System.#ttribute { public strin! %nspire.(y; public %nspire.(y#ttribute( strin! inspire.(y )

{ %nspire.(y / inspire.(y; } } 9%nspire.(y("#n.y &c0s brilliant .,>T -#E"); class CTest { } class C#pp { public static 6oi. &ain() { ob*ect9; atts / typeof(CTest).+etCustom#ttributes(true); foreac'( ob*ect att in atts ) if( att is %nspire.(y#ttribute ) Console.WriteLine( "Class CTest 1as inspire. by {5}"3 ((%nspire.(y#ttribute)att).%nspire.(y ); } }

7. "an # $reate m- own $onte4t att%5utes(


Jes. Take a look at 1eter (rayton6s Tracehook.NET.

8. "ode A$$ess 0e$ur%t-

8.1 &'at %s "ode A$$ess 0e$ur%t- C"A0D(


%A2 is the part of the .NET security model that determines whether or not code is allowed to run and what resources it can use when it is runnin!. For e'ample it is %A2 that will pre#ent a .NET we$ applet from formattin! your hard disk.

8.2 6ow does "A0 work(


The %A2 security policy re#ol#es around two key concepts ) code !roups and permissions. Each .NET assem$ly is a mem$er of a particular code !roup and each code !roup is !ranted the permissions specified in a named perm%ss%on set. For e'ample usin! the default security policy a control downloaded from a we$ site $elon!s to the 6Rone ) "nternet6 code !roup which adheres to the permissions defined $y the 6"nternet6 named permission set. ENaturally the 6"nternet6 named permission set represents a #ery restricti#e ran!e of permissions.F

8. &'o de*%nes t'e "A0 $ode ,roups(

Microsoft defines some default ones $ut you can modify these and e#en create your own. To see the code !roups defined on your system run 6caspol )l!6 from the command)line. &n my system it looks like this+
Le6el / &ac'ine Co.e +roups F. #ll co.e ,ot'in! F.F. ?one G &yComputer -ullTrust F.F.F. Honor S:ipHerification reIuests S:ipHerification F.8. ?one G %ntranet Local%ntranet F.7. ?one G %nternet %nternet F.J. ?one G 2ntruste. ,ot'in! F.K. ?one G Truste. %nternet F.L. Stron!,ame G 558J55555JM55555NJ5555555L585555558J5555K8K7JF7F555J555557 555555C-C(78NF##OFK->NN$J5$JN5J577L-N5KL$OMML->$JLOOK(CO((KJ75(#JJJJ->-M7JM>($5 L -NL8-7NOOL#>J$C7(O(5J#O->L-JN-8K-OJ5J87>(-8C5(MNLNM$M$5M#CJM$LNC>$5-CM-M7(JLK>5 M 5O#CFF>CF$CCO$5KJ>M5O#J777L$$>J5M#K7N7#JMKKLF878O8C>>>>O8-FLL5(OFN8O$7MKLF##(-K C #CF$-FO7JL77CL58-M-8$K >6eryt'in!

Note the hierarchy of code !roups ) the top of the hierarchy is the most !eneral E6All code6F which is then su$)di#ided into se#eral !roups each of which in turn can $e su$)di#ided. Also note that Esomewhat counter)intuiti#elyF a su$)!roup can $e associated with a more permissi#e permission set than its parent.

8.+ 6ow do # de*%ne m- own $ode ,roup(


Hse caspol. For e'ample suppose you trust code from www.mydomain.com and you want it ha#e full access to your system $ut you want to keep the default restrictions for all other internet sites. To achie#e this you would add a new code !roup as a su$)!roup of the 6Rone ) "nternet6 !roup like this+
caspol Ga! F.7 Gsite 111.my.omain.com -ullTrust

Now if you run caspol )l! you will see that the new !roup has $een added as !roup :.;.:+
... F.7. ?one G %nternet %nternet F.7.F. Site G 111.my.omain.com ... -ullTrust

Note that the numeric la$el E:.;.:F is 7ust a caspol in#ention to make the code !roups easy to manipulate from the command)line. The underlyin! runtime ne#er sees it.

8.5 6ow do # $'an,e t'e perm%ss%on set *or a $ode ,roup(


Hse caspol. "f you are the machine administrator you can operate at the 6machine6 le#el ) which means not only that the chan!es you make $ecome the default for the machine $ut also that users cannot chan!e the permissions to $e more permissi#e. "f you are a normal Enon)adminF user you can still modify the permissions $ut only to make them more restricti#e. For e'ample to allow intranet code to do what it likes you mi!ht do this+

caspol Gc! F.8 -ullTrust

Note that $ecause this is more permissi#e than the default policy Eon a standard systemF you should only do this at the machine le#el ) doin! it at the user le#el will ha#e no effect.

8.! "an # $reate m- own perm%ss%on set(


Jes. Hse caspol )ap specifyin! an *M- file containin! the permissions in the permission set. To sa#e you some time here is a sample file correspondin! to the 6E#erythin!6 permission set ) 7ust edit to suit your needs. 5hen you ha#e edited the sample add it to the ran!e of a#aila$le permission sets like this+
caspol Gap samplepermset.<ml

Then to apply the permission set to a code !roup do somethin! like this+
caspol Gc! F.7 Sample=ermSet

ECy default :.; is the 6"nternet6 code !roupF

8.7 #3m 'a)%n, some trou5.e w%t' "A0. 6ow $an # trou5.es'oot t'e pro5.em(
%aspol has a couple of options that mi!ht help. First you can ask caspol to tell you what code !roup an assem$ly $elon!s to usin! caspol )rs!. 2imilarly you can ask what permissions are $ein! applied to a particular assem$ly usin! caspol )rsp.

8.8 # $an3t 5e 5ot'ered w%t' "A0. "an # turn %t o**(


Jes as lon! as you are an administrator. Just run+
caspol Gs off

<. #ntermed%ate Lan,ua,e C#LD

<.1 "an # .ook at t'e #L *or an assem5.-(


Jes. M2 supply a tool called "ldasm that can $e used to #iew the metadata and "- for an assem$ly.

<.2 "an sour$e $ode 5e re)erse-en,%neered *rom #L(


Jes it is often relati#ely strai!htforward to re!enerate hi!h)le#el source from "-. -ut3 .oeder6s .eflector does a #ery !ood 7o$ of turnin! "- into %/ or GC.NET.

<. 6ow $an # stop m- $ode 5e%n, re)erse-en,%neered *rom #L(


Jou can $uy an "- o$fuscation tool. These tools work $y 6optimisin!6 the "- in such a way that re#erse) en!ineerin! $ecomes much more difficult. &f course if you are writin! we$ ser#ices then re#erse)en!ineerin! is not a pro$lem as clients do not ha#e access to your "-.

<.+ "an # wr%te #L pro,rams d%re$t.-(


Jes. 1eter (rayton posted this simple e'ample to the (&TNET mailin! list+
.assembly &y#ssembly {} .class &y#pp { .met'o. static 6oi. &ain() { .entrypoint l.str "Hello3 %LC" call 6oi. System.Console ret } }

WriteLine(class System.)b*ect)

Just put this into a file called hello.il and then run ilasm hello.il. An e'e assem$ly will $e !enerated.

<.5 "an # do t'%n,s %n #L t'at # $an3t do %n "2(


Jes. A couple of simple e'amples are that you can throw e'ceptions that are not deri#ed from 2ystem.E'ception and you can ha#e non)3ero)$ased arrays.

10. #mp.%$at%ons *or "BA

10.1 8oes .NET rep.a$e "BA(


This su$7ect causes a lot of contro#ersy as you6ll see if you read the mailin! list archi#es. Take a look at the followin! two threads+ http+,,discuss.de#elop.com,archi#es,wa.e'e4A2Kind000@S-K(&TNETS(K0S1K>A2<: http+,,discuss.de#elop.com,archi#es,wa.e'e4A2Kind000@S-K(&TNETS1K.>0@>: The $ottom line is that .NET has its own mechanisms for type interaction and they don6t use %&M. No "Hnknown no "(- no typeli$s no re!istry)$ased acti#ation. This is mostly !ood as a lot of %&M was u!ly. 8enerally speakin! .NET allows you to packa!e and use components in a similar way to %&M $ut makes the whole thin! a $it easier.

10.2 #s 8"BA dead(

1retty much for .NET de#elopers. The .NET Framework has a new remotin! model which is not $ased on (%&M. (%&M was pretty much dead anyway once firewalls $ecame widespread and Microsoft !ot 2&A1 fe#er. &f course (%&M will still $e used in interop scenarios.

10. #s "BAE dead(


Not immediately. The approach for .NET :.0 was to pro#ide access to the e'istin! %&M0 ser#ices Ethrou!h an interop layerF rather than replace the ser#ices with nati#e .NET ones. Garious tools and attri$utes were pro#ided to make this as painless as possi$le. &#er time it is e'pected that interop will $ecome more seamless ) this may mean that some ser#ices $ecome a core part of the %-. and,or it may mean that some ser#ices will $e rewritten as mana!ed code which runs on top of the %-.. For more on this topic search for postin!s $y Joe -on! in the archi#es ) Joe is the M2 !roup mana!er for %&M0. 2tart with this messa!e+ http+,,discuss.de#elop.com,archi#es,wa.e'e4A2Kind000@S-K(&TNETS1K.>A;@0

10.+ "an # use "BA $omponents *rom .NET pro,rams(


Jes. %&M components are accessed from the .NET runtime #ia a .untime %alla$le 5rapper E.%5F. This wrapper turns the %&M interfaces e'posed $y the %&M component into .NET)compati$le interfaces. For oleautomation interfaces the .%5 can $e !enerated automatically from a type li$rary. For non)oleautomation interfaces it may $e necessary to de#elop a custom .%5 which manually maps the types e'posed $y the %&M interface to .NET)compati$le types. ?ere6s a simple e'ample for those familiar with AT-. First create an AT- component which implements the followin! "(-+
import "oai.l.i.l"; import "oci.l.i.l"; 9 ob*ect3 uui.(>#5F7-N7GJMO#GJJ57GML>CG-$N->>K>L85L)3 'elpstrin!("%Cpp,ame %nterface")3 pointerP.efault(uniIue)3 oleautomation ; interface %Cpp,ame %2n:no1n { 9'elpstrin!("met'o. Set,ame"); H">S2LT Set,ame(9in; (ST" name); 9'elpstrin!("met'o. +et,ame"); H">S2LT +et,ame(9out3ret6al; Qp,ame ); }; 9 uui.(-K>JCLF$G$N7#GJ8NKG#J(JG8JK7$J#JJMJ$)3 6ersion(F.5)3 'elpstrin!("cppcomser6er F.5 Type Library") ; library C==C)&S>"H>"Lib { importlib("st.ole78.tlb"); importlib("st.ole8.tlb"); 9 uui.(L55C>L$NGK>$OGJ(J$G((JNG>M$K$K5NL-O5)3

(ST"

'elpstrin!("Cpp,ame Class") ; coclass Cpp,ame { 9.efault; interface %Cpp,ame; }; };

5hen you6#e $uilt the component you should !et a typeli$rary. .un the T-C"M1 utility on the typeli$ary like this+
tlbimp cppcomser6er.tlb

"f successful you will !et a messa!e like this+


Typelib importe. successfully to C==C)&S>"H>"Lib..ll

Jou now need a .NET client ) let6s use %/. %reate a .cs file containin! the followin! code+
usin! System; usin! C==C)&S>"H>"Lib; public class &ain#pp { static public 6oi. &ain() { Cpp,ame cppname / ne1 Cpp,ame(); cppname.Set,ame( "bob" ); Console.WriteLine( ",ame is " 4 cppname.+et,ame() ); } }

%ompile the %/ code like this+


csc /r cppcomser6erlib..ll cs'arpcomclient.cs

Note that the compiler is $ein! told to reference the (-- we pre#iously !enerated from the typeli$rary usin! T-C"M1. Jou should now $e a$le to run csharpcomclient.e'e and !et the followin! output on the console+
,ame is bob

10.5 "an # use .NET $omponents *rom "BA pro,rams(


Jes. .NET components are accessed from %&M #ia a %&M %alla$le 5rapper E%%5F. This is similar to a .%5 Esee pre#ious NuestionF $ut works in the opposite direction. A!ain if the wrapper cannot $e automatically !enerated $y the .NET de#elopment tools or if the automatic $eha#iour is not desira$le a custom %%5 can $e de#eloped. Also for %&M to 6see6 the .NET component the .NET component must $e re!istered in the re!istry. ?ere6s a simple e'ample. %reate a %/ file called testcomser#er.cs and put the followin! in it+
usin! System; usin! System."untime.%nteropSer6ices; namespace #n.y&c {

9Class%nterface(Class%nterfaceType.#uto$ual); public class CS'arpC)&Ser6er { public CS'arpC)&Ser6er() {} public 6oi. Set,ame( strin! name ) { mPname / name; } public strin! +et,ame() { return mPname; } pri6ate strin! mPname; } }

Then compile the .cs file as follows+


csc /tar!et library testcomser6er.cs

Jou should !et a dll which you re!ister like this+


re!asm testcomser6er..ll /tlb testcomser6er.tlb /co.ebase

Now you need to create a client to test your .NET %&M component. GC2cript will do ) put the followin! in a file called comclient.#$s+
$im .ot,et)b* Set .ot,et)b* / Create)b*ect("#n.y&c.CS'arpC)&Ser6er") .ot,et)b*.Set,ame ("bob") &s!(o< ",ame is " R .ot,et)b*.+et,ame()

and run the script like this+


1script comclient.6bs

And hey presto you should !et a messa!e $o' displayed with the te't DName is $o$D. An alternati#e to the approach a$o#e it to use the dm.net moniker de#eloped $y Jason 5hittin!ton and (on Co'.

10.! #s ATL redundant %n t'e .NET wor.d(


Jes. AT- will continue to $e #alua$le for writin! %&M components for some time $ut it has no place in the .NET world.

11. A%s$e..aneous

11.1 6ow does .NET remot%n, work(


.NET remotin! in#ol#es sendin! messa!es alon! channels. Two of the standard channels are ?TT1 and T%1. T%1 is intended for -ANs only ) ?TT1 can $e used for -ANs or 5ANs EinternetF. 2upport is pro#ided for multiple messa!e seriali3arion formats. E'amples are 2&A1 E*M-)$asedF and $inary. Cy default the ?TT1 channel uses 2&A1 E#ia the .NET runtime 2eriali3ation 2&A1 FormatterF and the T%1 channel uses $inary E#ia the .NET runtime 2eriali3ation Cinary FormatterF. Cut either channel can use either seriali3ation format.

There are a num$er of styles of remote access+

0%n,.e"a... Each incomin! reNuest from a client is ser#iced $y a new o$7ect. The o$7ect is thrown away when the reNuest has finished. 0%n,.eton. All incomin! reNuests from clients are processed $y a sin!le ser#er o$7ect. ".%ent-a$t%)ated o5:e$t. This is the old stateful E(F%&M model where$y the client recei#es a reference to the remote o$7ect and holds that reference Ethus keepin! the remote o$7ect ali#eF until it is finished with it.

(istri$uted !ar$a!e collection of o$7ects is mana!ed $y a system called 6leased $ased lifetime6. Each o$7ect has a lease time and when that time e'pires the o$7ect is disconnected from the .NET runtime remotin! infrastructure. &$7ects ha#e a default renew time ) the lease is renewed when a successful call is made from the client to the o$7ect. The client can also e'plicitly renew the lease. "f you6re interested in usin! *M-).1% as an alternati#e to 2&A1 take a look at %harles %ook6s *M-) .1%.Net.

11.2 6ow $an # ,et at t'e &%n 2 AF# *rom a .NET pro,ram(
Hse 1,"n#oke. This uses similar technolo!y to %&M "nterop $ut is used to access static (-- entry points instead of %&M o$7ects. ?ere is an e'ample of %/ callin! the 5in;2 Messa!eCo' function+
usin! System; usin! System."untime.%nteropSer6ices; class &ain#pp { 9$ll%mport("user78..ll"3 >ntry=oint/"&essa!e(o<"3 SetLast>rror/true3 C'arSet/C'arSet.#uto); public static e<tern int &essa!e(o<(int 'Wn.3 Strin! str&essa!e3 Strin! strCaption3 uint uiType); public static 6oi. &ain() { &essa!e(o<( 53 "Hello3 t'is is =%n6o:e in operationC"3 ".,>T"3 5 ); } }

1in#oke.net is a !reat resource for off)the)shelf 1,"n#oke si!natures.

11. 6ow do # wr%te to t'e app.%$at%on $on*%,urat%on *%.e at runt%me(


Jou don6t. 2ee http+,,www.interact)sw.co.uk,ian!$lo!,200<,::,2=,sa#in!confi!.

11.+ &'at %s t'e d%**eren$e 5etween an e)ent and a de.e,ate(


An e#ent is 7ust a wrapper for a multicast dele!ate. Addin! a pu$lic e#ent to a class is almost the same as addin! a pu$lic multicast dele!ate field. "n $oth cases su$scri$er o$7ects can re!ister for notifications and in $oth cases the pu$lisher o$7ect can send notifications to the su$scri$ers. ?owe#er a pu$lic multicast dele!ate has the undesira$le property that e'ternal o$7ects can invoke the dele!ate somethin! we6d normally want to restrict to the pu$lisher. ?ence e#ents ) an e#ent adds pu$lic

methods to the containin! class to add and remo#e recei#ers $ut does not make the in#ocation mechanism pu$lic. 2ee this post $y Julien %ou#reur for more discussion.

11.5 &'at s%;e %s a .NET o5:e$t(


Each instance of a reference type has two fields maintained $y the runtime ) a method ta$le pointer and a sync $lock. These are < $ytes each on a ;2)$it system makin! a total of A $ytes per o$7ect o#erhead. &$#iously the instance data for the type must $e added to this to !et the o#erall si3e of the o$7ect. 2o for e'ample instances of the followin! class are :2 $ytes each+
class &y%nt { ... pri6ate int <; }

?owe#er note that with the current implementation of the %-. there seems to $e a minimum o$7ect si3e of :2 $ytes e#en for classes with no data Ee.!. 2ystem.&$7ectF. Galues types ha#e no eNui#alent o#erhead.

12. .NET 2.0

12.1 &'at are t'e new *eatures o* .NET 2.0(


8enerics anonymous methods partial classes iterators property #isi$ility Eseparate #isi$ility for !et and setF and static classes. 2ee http+,,msdn.microsoft.com,msdnma!,issues,0<,0=,%20,default.asp' for more information a$out these features.

12.2 &'at are t'e new 2.0 *eatures use*u. *or(


8enerics are useful for writin! efficient type)independent code particularly where the types mi!ht include #alue types. The o$#ious application is container classes and the .NET 2.0 class li$rary includes a suite of !eneric container classes in the 2ystem.%ollections.8eneric namespace. ?ere6s a simple e'ample of a !eneric container class $ein! used+
ListSintT myList / ne1 ListSintT(); myList.#..( F5 );

Anonymous methods reduce the amount of code you ha#e to write when usin! dele!ates and are therefore especially useful for 8H" pro!rammin!. ?ere6s an e'ample
#pp$omain.Current$omain.=rocess><it 4/ .ele!ate { Console.WriteLine("=rocess en.in! ..."); };

1artial classes is a useful feature for separatin! machine)!enerated code from hand)written code in the same class and will therefore $e hea#ily used $y de#elopment tools such as Gisual 2tudio.

"terators reduce the amount of code you need to write to implement "Enumera$le,"Enumerator. ?ere6s some sample code+
static 6oi. &ain() { "an.om>numerator re / ne1 "an.om>numerator( K ); foreac'( .ouble r in re ) Console.WriteLine( r ); Console."ea.(); } class "an.om>numerator %>numerableS.oubleT { public "an.om>numerator(int siAe) { mPsiAe / siAe; } public %>numeratorS.oubleT +et>numerator() { "an.om ran. / ne1 "an.om(); for( int i/5; i S mPsiAe; i44 ) yiel. return ran..,e<t$ouble(); } int mPsiAe / 5; }

The use of 6yield return6 is rather stran!e at first si!ht. "t effecti#ely synthethises an implementation of "Enumerator somethin! we had to do manually in .NET :.'.

12. &'at3s t'e pro5.em w%t' .NET ,ener%$s(


.NET !enerics work !reat for container classes. Cut what a$out other uses4 5ell it turns out that .NET !enerics ha#e a ma7or limitation ) they reNuire the type parameter to $e constrained. For e'ample you cannot do this+
static class $isposerSTT { public static 6oi. $ispose(T ob*) { ob*.$ispose(); } }

The %/ compiler will refuse to compile this code as the type T has not $een constrained and therefore only supports the methods of 2ystem.&$7ect. (ispose is not a method on 2ystem.&$7ect so the compilation fails. To fi' this code we need to add a w'ere clause to reassure the compiler that our type T does indeed ha#e a (ispose method
static class $isposerSTT 1'ere T %$isposable { public static 6oi. $ispose(T ob*) { ob*.$ispose(); } }

The pro$lem is that the reNuirement for e'plicit contraints is #ery limitin!. 5e can use constraints to say that T implements a particular interface $ut we can6t dilute that to simply say that T implements a particular method. %ontrast this with %00 templates Efor e'ampleF where no constraint at all is reNuired ) it is assumed Eand #erified at compile timeF that if the code in#okes the (isposeEF method on a type then the type will support the method. "n fact after writin! !eneric code with interface constraints we Nuickly see that we ha#en6t !ained much o#er non)!eneric interface)$ased pro!rammin!. For e'ample we can easily rewrite the (isposer class without !enerics+

static class $isposer { public static 6oi. $ispose( %$isposable ob* ) { ob*.$ispose(); } }

For more on this topic start $y readin! the followin! articles+ Cruce Eckel+ http+,,www.mind#iew.net,5e$-o!,lo!)00=0 "an 8riffiths+ http+,,www.interact)sw.co.uk,ian!$lo!,200<,0;,:<,!enerics %harles %ook+ http+,,www.cookcomputin!.com,$lo!,archi#es,000<2=.html Crad 5ilson+ http+,,dotnet!uy.techieswithcats.com,archi#es,00<2@;.shtml

12.+ &'at3s new %n t'e .NET 2.0 $.ass .%5rar-(


?ere is a selection of new features in the .NET 2.0 class li$rary E$eta :F+

8eneric collections in the 2ystem.%ollections.8eneric namespace. The 0-stem.Nu..a5.eGTH type. ENote that %/ has special synta' for this type e.!. int4 is eNui#alent to Nulla$leTintUF The 9I%p0tream and 8e*.ate0tream classes in the 2ystem."&.%ompression namespace. The 0emap'ore class in the 2ystem.Threadin! namespace. 5rappers for (1A1" in the form of the Frote$ted8ata and Frote$tedAemor- classes in the 2ystem.2ecurity.%rypto!raphy namespace. The "1% remotin! channel in the 2ystem..untime..emotin!.%hannels."pc namespace optimised intra)machine communication. for

1 . ".ass L%5rar-

1 .1 T'reads

1 .1.1 6ow do # spawn a t'read(


%reate an instance of a 2ystem.Threadin!.Thread o$7ect passin! it an instance of a Thread2tart dele!ate that will $e e'ecuted on the new thread. For e'ample+
class &yT'rea. { public &yT'rea.( strin! init$ata ) { mP.ata / init$ata; mPt'rea. / ne1 T'rea.( ne1 T'rea.Start(T'rea.&ain) ); mPt'rea..Start(); } // T'rea.&ain() is e<ecute. on t'e ne1 t'rea.. pri6ate 6oi. T'rea.&ain() { Console.WriteLine( mP.ata ); }

public 6oi. Wait2ntil-inis'e.() { mPt'rea..Uoin(); } pri6ate T'rea. mPt'rea.; pri6ate strin! mP.ata; }

"n this case creatin! an instance of the MyThread class is sufficient to spawn the thread and e'ecute the MyThread.ThreadMainEF method+
&yT'rea. t / ne1 &yT'rea.( "Hello3 1orl.." ); t.Wait2ntil-inis'e.();

1 .1.2 6ow do # stop a t'read(


There are se#eral options. First you can use your own communication mechanism to tell the Thread2tart method to finish. Alternati#ely the Thread class has in)$uilt support for instructin! the thread to stop. The two principle methods are Thread."nterruptEF and Thread.A$ortEF. The former will cause a Thread"nterruptedE'ception to $e thrown on the thread when it ne't !oes into a 5aitJoin2leep state. "n other words Thread."nterrupt is a polite way of askin! the thread to stop when it is no lon!er doin! any useful work. "n contrast Thread.A$ortEF throws a ThreadA$ortE'ception re!ardless of what the thread is doin!. Furthermore the ThreadA$ortE'ception cannot normally $e cau!ht Ethou!h the Thread2tart6s finally method will $e e'ecutedF. Thread.A$ortEF is a hea#y)handed mechanism which should not normally $e reNuired.

1 .1. 6ow do # use t'e t'read poo.(


Cy passin! an instance of a 5ait%all$ack dele!ate to the Thread1ool.QueueHser5ork"temEF method
class C#pp { static 6oi. &ain() { strin! s / "Hello3 Worl."; T'rea.=ool.Eueue2serWor:%tem( ne1 WaitCallbac:( $oWor: )3 s ); T'rea..Sleep( F555 ); } // $oWor: is e<ecute. on a t'rea. from t'e t'rea. pool. static 6oi. $oWor:( ob*ect state ) { Console.WriteLine( state ); } } // +i6e time for 1or: item to be e<ecute.

1 .1.+ 6ow do # know w'en m- t'read poo. work %tem 'as $omp.eted(
There is no way to Nuery the thread pool for this information. Jou must put code into the 5ait%all$ack method to si!nal that it has completed. E#ents are useful for this.

1 .1.5 6ow do # pre)ent $on$urrent a$$ess to m- data(


Each o$7ect has a concurrency lock Ecritical sectionF associated with it. The 2ystem.Threadin!.Monitor.Enter,E'it methods are used to acNuire and release this lock. For e'ample instances of the followin! class only allow one thread at a time to enter method fEF+
class C { public 6oi. f() { try { &onitor.>nter(t'is); ... } finally { &onitor.><it(t'is); } } }

%/ has a 6lock6 keyword which pro#ides a con#enient shorthand for the code a$o#e+
class C { public 6oi. f() { loc:(t'is) { ... } } }

Note that callin! Monitor.EnterEmy&$7ectF does N&T mean that all access to my&$7ect is seriali3ed. "t means that the synchronisation lock associated with my&$7ect has $een acNuired and no other thread can acNuire that lock until Monitor.E'itEoF is called. "n other words this class is functionally eNui#alent to the classes a$o#e+
class C { public 6oi. f() { loc:( mPob*ect ) { ... } } pri6ate mPob*ect / ne1 ob*ect(); }

Actually it could $e ar!ued that this #ersion of the code is superior as the lock is totally encapsulated within the class and not accessi$le to the user of the o$7ect.

1 .2 Tra$%n,

1 .2.1 #s t'ere 5u%.t-%n support *or tra$%n,J.o,,%n,(


Jes in the 2ystem.(ia!nostics namespace. There are two main classes that deal with tracin! ) (e$u! and Trace. They $oth work in a similar way ) the difference is that tracin! from the (e$u! class only works in $uilds that ha#e the (ECH8 sym$ol defined whereas tracin! from the Trace class only works in $uilds that ha#e the T.A%E sym$ol defined. Typically this means that you should use 2ystem.(ia!nostics.Trace.5rite-ine for tracin! that you want to work in de$u! and release $uilds and 2ystem.(ia!nostics.(e$u!.5rite-ine for tracin! that you want to work only in de$u! $uilds.

1 .2.2 "an # red%re$t tra$%n, to a *%.e(


Jes. The (e$u! and Trace classes $oth ha#e a -isteners property which is a collection of sinks that recei#e the tracin! that you send #ia (e$u!.5rite-ine and Trace.5rite-ine respecti#ely. Cy default the -isteners collection contains a sin!le sink which is an instance of the (efaultTrace-istener class. This sends output to the 5in;2 &utput(e$u!2trin!EF function and also the 2ystem.(ia!nostics.(e$u!!er.-o!EF method. This is useful when de$u!!in! $ut if you6re tryin! to trace a pro$lem at a customer site redirectin! the output to a file is more appropriate. Fortunately the Te't5riterTrace-istener class is pro#ided for this purpose. ?ere6s how to use the Te't5riterTrace-istener class to redirect Trace output to a file+
Trace.Listeners.Clear(); -ileStream fs / ne1 -ileStream( V"c Wlo!.t<t"3 -ile#ccess.Write ); Trace.Listeners.#..( ne1 Te<tWriterTraceListener( fs ) ); Trace.WriteLine( V"T'is 1ill be 1riten to c Wlo!.t<tC" ); Trace.-lus'();

-ile&o.e.Create3

Note the use of Trace.-isteners.%learEF to remo#e the default listener. "f you don6t do this the output will !o to the file and &utput(e$u!2trin!EF. Typically this is not what you want $ecause &utput(e$u!2trin!EF imposes a $i! performance hit.

1 .2. "an # $ustom%se t'e tra$e output(


Jes. Jou can write your own Trace-istener)deri#ed class and direct all output throu!h it. ?ere6s a simple e'ample which deri#es from Te't5riterTrace-istener Eand therefore has in)$uilt support for writin! to files as shown a$o#eF and adds timin! information and the thread "( for each trace line+
class &yListener Te<tWriterTraceListener { public &yListener( Stream s ) base(s) { } public o6erri.e 6oi. WriteLine( strin! s ) { Writer.WriteLine( "{5 $M} 9{F $J}; {8}"3 >n6ironment.Tic:Count G mPstartTic:Count3 #pp$omain.+etCurrentT'rea.%.()3 s ); } protecte. int mPstartTic:Count / >n6ironment.Tic:Count; }

ENote that this implementation is not complete ) the Trace-istener.5rite method is not o#erridden for e'ample.F The $eauty of this approach is that when an instance of My-istener is added to the Trace.-isteners collection all calls to Trace.5rite-ineEF !o throu!h My-istener includin! calls made $y referenced assem$lies that know nothin! a$out the My-istener class.

1 .2.+ Are t'ere an- t'%rd part- .o,,%n, $omponents a)a%.a5.e(


-o!<net is a port of the esta$lished lo!<7 Ja#a lo!!in! component.

"ontents

:. "ntroduction

o o o o

:.: 5hat is %/4 :.2 ?ow do " de#elop %/ apps4 :.; (oes %/ replace %004 :.< (oes %/ ha#e its own class li$rary4

2. Types

o o o o o o

2.: 5hat standard types does %/ use4 2.2 "s it true that all %/ types deri#e from a common $ase class4 2.; 2o " can pass an instance of a #alue type to a method that takes an o$7ect as a parameter4 2.< 5hat are the fundamental differences $etween #alue types and reference types4 2.= &kay so an int is a #alue type and a class is a reference type. ?ow can int $e deri#ed from o$7ect4 2.> Are %/ references the same as %00 references4

;. %lasses and 2tructs

o o o o o o o o o o

;.: 2tructs are lar!ely redundant in %00. 5hy does %/ ha#e them4 ;.2 (oes %/ support multiple inheritance EM"F4 ;.; "s a %/ interface the same as a %00 a$stract class4 ;.< Are %/ constructors the same as %00 constructors4 ;.= Are %/ destructors the same as %00 destructors4 ;.> "f %/ destructors are so different to %00 destructors why did M2 use the same synta'4 ;.@ Are all methods #irtual in %/4 ;.A ?ow do " declare a pure #irtual function in %/4 ;.B %an " call a #irtual method from a constructor,destructor4 ;.:0 2hould " make my destructor #irtual4

<. E'ceptions

o o o o o o

<.: %an " use e'ceptions in %/4 <.2 5hat types of o$7ect can " throw as e'ceptions4 <.; %an " define my own e'ceptions4 <.< (oes the 2ystem.E'ception class ha#e any cool features4 <.= 5hen should " throw an e'ception4 <.> (oes %/ ha#e a 6throws6 clause4

=. .un)time Type "nformation

o o

=.: ?ow can " check the type of an o$7ect at runtime4 =.2 %an " !et the name of a type at runtime4

>. Miscellaneous

o o o o o o o o

>.: ?ow do " do a case)insensiti#e strin! comparison4 >.2 (oes %/ support a #aria$le num$er of ar!uments4 >.; ?ow can " process command)line ar!uments4 >.< (oes %/ do array $ounds checkin!4 >.= ?ow can " make sure my %/ classes will interoperate with other .NET lan!ua!es4 >.> ?ow do " use the 6usin!6 keyword with multiple o$7ects4 >.@ 5hat is the difference $etween KK and o$7ect.ENuals4 >.A ?ow do " enforce const correctness in %/4

@. %/ 2.0

o o

@.: 5hat are the new features in %/ 2.04 @.2 Are %/ !enerics the same as %00 templates4

A. .esources

A.: Cooks

1. #ntrodu$t%on

1.1 &'at %s "2(


%/ is a pro!rammin! lan!ua!e desi!ned $y Microsoft. "t is loosely $ased on %,%00 and $ears a strikin! similarity to Ja#a. Microsoft descri$e %/ as follows+ D%/ is a simple modern o$7ect oriented and type)safe pro!rammin! lan!ua!e deri#ed from % and %0 0. %/ Epronounced 6% sharp6F is firmly planted in the % and %00 family tree of lan!ua!es and will immediately $e familiar to % and %00 pro!rammers. %/ aims to com$ine the hi!h producti#ity of Gisual Casic and the raw power of %00.D

1.2 6ow do # de)e.op "2 apps(


The EfreeF .NET 2(9 contains the %/ command)line compiler Ecsc.e'eF. Gisual 2tudio has fully inte!rated support for %/ de#elopment. &n -inu' you can use Mono.

1. 8oes "2 rep.a$e "EE(


There are three options open to the 5indows de#eloper from a %00 $ack!round+

2tick with standard %00. (on6t use .NET at all. Hse %00 with .NET. Microsoft supply a .NET %00 compiler that produces "- rather than machine code. ?owe#er to make full use of the .NET en#ironment Ee.!. !ar$a!e collectionF a set of e'tensions are reNuired to standard %00. "n .NET :.' this e'tended lan!ua!e is called Mana!ed E'tensions for %00. "n .NET 2.0 ME %00 has $een completely redesi!ned under the stewardship of 2tan -ippman and renamed %00,%-". For!et %00 and use %/.

Each of these options has merits dependin! on the de#eloper and the application. For my own part " intend to use %/ where possi$le fallin! $ack to %00 only where necessary. ME %00 Esoon to $e %0 0,%-"F is #ery useful for interop $etween new .NET code and old %00 code ) simply write a mana!ed wrapper class usin! ME %00 then use the mana!ed class from %/. From e'perience this works well.

1.+ 8oes "2 'a)e %ts own $.ass .%5rar-(


Not e'actly. The .NET Framework has a comprehensi#e class li$rary which %/ can make use of. %/ does not ha#e its own class li$rary.

2. T-pes

2.1 &'at standard t-pes does "2 use(


%/ supports a #ery similar ran!e of $asic types to %00 includin! int lon! float dou$le char strin! arrays structs and classes. ?owe#er don6t assume too much. The names may $e familiar $ut many of the details are different. For e'ample a lon! is >< $its in %/ whereas in %00 the si3e of a lon! depends on the platform Etypically ;2 $its on a ;2)$it platform >< $its on a ><)$it platformF. Also classes and structs are almost the same in %00 ) this is not true for %/. Finally chars and strin!s in .NET are :>)$it EHnicode,HTF):>F not A)$it like %00.

2.2 #s %t true t'at a.. "2 t-pes der%)e *rom a $ommon 5ase $.ass(
Jes and no. All types can $e treated as if they deri#e from o5:e$t E2ystem.&$7ectF $ut in order to treat an instance of a #alue type Ee.!. int floatF as o$7ect)deri#ed the instance must $e con#erted to a reference type usin! a process called 6$o'in!6. "n theory a de#eloper can for!et a$out this and let the run)time worry a$out when the con#ersion is necessary $ut in reality this implicit con#ersion can ha#e side)effects that may trip up the unwary.

2. 0o # $an pass an %nstan$e o* a )a.ue t-pe to a met'od t'at takes an o5:e$t as a parameter(
Jes. For e'ample+
class C#pplication { public static 6oi. &ain() { int < / 8K; strin! s / "fre."; $isplay&e( < ); $isplay&e( s ); } static 6oi. $isplay&e( ob*ect o ) { System.Console.WriteLine( "Xou are {5}"3 o ); } }

This would display+


Xou are 8K Xou are fre.

2.+ &'at are t'e *undamenta. d%**eren$es 5etween )a.ue t-pes and re*eren$e t-pes(
%/ di#ides types into two cate!ories ) )a.ue types and re*eren$e types. Most of the intrinsic types Ee.!. int charF are #alue types. 2tructs are also #alue types. .eference types include classes arrays and strin!s. The $asic idea is strai!htforward ) an instance of a #alue type represents the actual data whereas an instance of a reference type represents a pointer or reference to the data. The most confusin! aspect of this for %00 de#elopers is that %/ has predetermined which types are represented as #alues and which are represented as references. A %00 de#eloper e'pects to take responsi$ility for this decision. For e'ample in %00 we can do this+
int <F / 7; // <F is a 6alue on t'e stac: int Q<8 / ne1 int(7) // <8 is a pointer to a 6alue on t'e 'eap

$ut in %/ there is no control+


int <F / 7; // <F is a 6alue on t'e stac: int <8 / ne1 int(); <8 / 7; // <8 is also a 6alue on t'e stac:C

2.5 Bka-1 so an %nt %s a )a.ue t-pe1 and a $.ass %s a re*eren$e t-pe. 6ow $an %nt 5e der%)ed *rom o5:e$t(
"t isn6t really. 5hen an int is $ein! used as an int it is a #alue. ?owe#er when it is $ein! used as an o$7ect it is a reference to an inte!er #alue Eon the mana!ed heapF. "n other words when you treat an int as an o$7ect the runtime automatically con#erts the int #alue to an o$7ect reference. This process is

called 5o4%n,. The con#ersion in#ol#es copyin! the int to the heap and creatin! an o$7ect instance which refers to it. Hn$o'in! is the re#erse process ) the o$7ect is con#erted $ack to a #alue.
int < / 7; // ne1 int 6alue 7 on t'e stac: ob*ect ob*< / <; // ne1 int on 'eap3 set to 6alue 7 G still 'a6e </7 on stac: int y / (int)ob*<; // ne1 6alue 7 on stac:3 still !ot </7 on stac: an. ob*</7 on 'eap

2.! Are "2 re*eren$es t'e same as "EE re*eren$es(


Not Nuite. The $asic idea is the same $ut one si!nificant difference is that %/ references can $e null . 2o you cannot rely on a %/ reference pointin! to a #alid o$7ect. "n that respect a %/ reference is more like a %00 pointer than a %00 reference. "f you try to use a null reference a Null.eferenceE'ception is thrown. For e'ample look at the followin! method+
6oi. .isplayStrin!Len!t'( strin! s ) { Console.WriteLine( "Strin! is len!t' {5}"3 s.Len!t' ); }

The pro$lem with this method is that it will throw a Null.eferenceE'ception if called like this+
strin! s / null; .isplayStrin!Len!t'( s );

&f course for some situations you may deem a Null.eferenceE'ception to $e a perfectly accepta$le outcome $ut in this case it mi!ht $e $etter to re)write the method like this+
6oi. .isplayStrin!Len!t'( strin! s ) { if( s // null ) Console.WriteLine( "Strin! is null" ); else Console.WriteLine( "Strin! is len!t' {5}"3 s.Len!t' ); }

. ".asses and 0tru$ts

.1 0tru$ts are .ar,e.- redundant %n "EE. &'- does "2 'a)e t'em(
"n %00 a struct and a class are pretty much the same thin!. The only difference is the default #isi$ility le#el Epu$lic for structs pri#ate for classesF. ?owe#er in %/ structs and classes are #ery different. "n %/ structs are #alue types Einstances stored directly on the stack or inline within heap)$ased o$7ectsF whereas classes are reference types Einstances stored on the heap accessed indirectly #ia a referenceF. Also structs cannot inherit from structs or classes thou!h they can implement interfaces. 2tructs cannot ha#e destructors. A %/ struct is much more like a % struct than a %00 struct.

.2 8oes "2 support mu.t%p.e %n'er%tan$e CA#D(


No thou!h it does support implementation of multiple interfaces on a sin!le class or struct.

. #s a "2 %nter*a$e t'e same as a "EE a5stra$t $.ass(


No not Nuite. An a$stract class in %00 cannot $e instantiated $ut it can Eand often doesF contain implementation code and,or data mem$ers. A %/ interface cannot contain any implementation code or data mem$ers ) it is simply a !roup of method names S si!natures. A %/ interface is more like a %&M interface than a %00 a$stract class.

.+ Are "2 $onstru$tors t'e same as "EE $onstru$tors(


Gery similar. A si!nificant difference is that %/ supports constructor chaining. This means one constructor can use another+
class =erson { public =erson( strin! name3 int a!e ) { ... } public =erson( strin! name ) t'is( name3 5 ) {} public =erson() t'is( ""3 5 ) {} }

Another difference is that #irtual method calls within a constructor are routed to the most deri#ed implementation ) see %an " %all a #irtual method from a constructor. Finally %/ has static constructors. The static constructor for a class runs $efore the first instance of the class is created. Note that Elike %00F some %/ de#elopers prefer the factory method pattern o#er constructors. 2ee Crad 5ilson6s article.

.5 Are "2 destru$tors t'e same as "EE destru$tors(


No. They look the same $ut they are #ery different. The %/ destructor synta' Ewith the familiar V characterF is 7ust syntactic su!ar for an o#erride of the 2ystem.&$7ect Finali3e method. This Finali3e method is called $y the !ar$a!e collector when it determines that an o$7ect is no lon!er referenced $efore it frees the memory associated with the o$7ect. 2o far this sounds like a %00 destructor. The difference is that the !ar$a!e collector makes no !uarantees a$out when this procedure happens. "ndeed the al!orithm employed $y the %-. !ar$a!e collector means that it may $e a lon! time after the application has finished with the o$7ect. This lack of certainty is often termed 6non)deterministic finali3ation6 and it means that %/ destructors are not suita$le for releasin! scarce resources such as data$ase connections file handles etc. To achie#e deterministic destruction a class must offer a method to $e used for the purpose. The standard approach is for the class to implement the "(isposa$le interface. The user of the o$7ect must call the (isposeEF method when it has finished with the o$7ect. %/ offers the 6usin!6 construct to make this easier.

.! #* "2 destru$tors are so d%**erent to "EE destru$tors1 w'- d%d A0 use t'e same s-nta4(
1resuma$ly they wanted %00 pro!rammers to feel at home. " think they made a mistake.

.7 Are a.. met'ods )%rtua. %n "2(


No. -ike %00 methods are non)#irtual $y default $ut can $e marked as #irtual.

.8 6ow do # de$.are a pure )%rtua. *un$t%on %n "2(


Hse the a$stract modifier on the method. The class must also $e marked as a$stract EnaturallyF. Note that a$stract methods cannot ha#e an implementation Eunlike pure #irtual %00 methodsF.

.< "an # $a.. a )%rtua. met'od *rom a $onstru$torJdestru$tor(


Jes $ut it6s !enerally not a !ood idea. The mechanics of o$7ect construction in .NET are Nuite different from %00 and this affects #irtual method calls in constructors. %00 constructs o$7ects from $ase to deri#ed so when the $ase constructor is e'ecutin! the o$7ect is effecti#ely a $ase o$7ect and #irtual method calls are routed to the $ase class implementation. Cy contrast in .NET the deri#ed constructor is e'ecuted first which means the o$7ect is always a deri#ed o$7ect and #irtual method calls are always routed to the deri#ed implementation. ENote that the %/ compiler inserts a call to the $ase class constructor at the start of the deri#ed constructor thus preser#in! standard && semantics $y creatin! the illusion that the $ase constructor is e'ecuted first.F The same issue arises when callin! #irtual methods from %/ destructors. A #irtual method call in a $ase destructor will $e routed to the deri#ed implementation.

.10 0'ou.d # make m- destru$tor )%rtua.(


A %/ destructor is really 7ust an o#erride of the 2ystem.&$7ect Finali3e method and so is #irtual $y definition.

+. E4$ept%ons

+.1 "an # use e4$ept%ons %n "2(


Jes in fact e'ceptions are the recommended error)handlin! mechanism in %/ Eand in .NET in !eneralF. Most of the .NET framework classes use e'ceptions to si!nal errors.

+.2 &'at t-pes o* o5:e$t $an # t'row as e4$ept%ons(

&nly instances of the 2ystem.E'ception classes or classes deri#ed from 2ystem.E'ception. This is in sharp contrast with %00 where instances of almost any type can $e thrown.

+. "an # de*%ne m- own e4$ept%ons(


Jes as lon! as you follow the rule that e'ceptions deri#e from 2ystem.E'ception. More specifically M2 recommend that user)defined e'ceptions inherit from 2ystem.ApplicationE'ception Ewhich is deri#ed from 2ystem.E'ceptionF.

+.+ 8oes t'e 0-stem.E4$ept%on $.ass 'a)e an- $oo. *eatures(


Jes ) the feature which stands out is the 2tackTrace property. This pro#ides a call stack which records where the e'ception was thrown from. For e'ample the followin! code+
usin! System; class C#pp { public static 6oi. &ain() { try { f(); } catc'( ><ception e ) { Console.WriteLine( "System.><ception stac: trace / Wn{5}"3 e.Stac:Trace ); } } static 6oi. f() { t'ro1 ne1 ><ception( "f 1ent pearGs'ape." ); } }

produces this output+


System.><ception stac: trace / at C#pp.f() at C#pp.&ain()

Note howe#er that this stack trace was produced from a de$u! $uild. A release $uild may optimise away some of the method calls which could mean that the call stack isn6t Nuite what you e'pect.

+.5 &'en s'ou.d # t'row an e4$ept%on(


This is the su$7ect of some de$ate and is partly a matter of taste. ?owe#er it is accepted $y many that e'ceptions should $e thrown only when an 6une'pected6 error occurs. ?ow do you decide if an error is e'pected or une'pected4 This is a 7ud!ement call $ut a strai!htforward e'ample of an e'pected error is failin! to read from a file $ecause the seek pointer is at the end of the file whereas an e'ample of an une'pected error is failin! to allocate memory from the heap.

+.! 8oes "2 'a)e a 3t'rows3 $.ause(


No unlike Ja#a %/ does not reNuire Eor e#en allowF the de#eloper to specify the e'ceptions that a method can throw.

5. /un-t%me T-pe #n*ormat%on

5.1 6ow $an # $'e$k t'e t-pe o* an o5:e$t at runt%me(


Jou can use the %s keyword. For e'ample+
usin! System; class C#pp { public static 6oi. &ain() { strin! s / "fre."; lon! i / F5; Console.WriteLine( "{5} is {F}an inte!er"3 s3 (%s%nte!er(s) B "" "not ") ); Console.WriteLine( "{5} is {F}an inte!er"3 i3 (%s%nte!er(i) B "" "not ") ); } static bool %s%nte!er( ob*ect ob* ) { if( ob* is int YY ob* is lon! ) return true; else return false; } }

produces the output+


fre. is not an inte!er F5 is an inte!er

5.2 "an # ,et t'e name o* a t-pe at runt%me(


Jes use the 8etType method of the o$7ect class Ewhich all types inherit fromF. For e'ample+
usin! System; class CTest { class C#pp { public static 6oi. &ain() { lon! i / F5; CTest ctest / ne1 CTest();

$isplayType%nfo( ctest ); $isplayType%nfo( i ); } static 6oi. $isplayType%nfo( ob*ect ob* ) { Console.WriteLine( "Type name / {5}3 full type name / {F}"3 ob*.+etType()3 ob*.+etType().-ull,ame ); } } }

produces the followin! output+


Type name / CTest3 full type name / CTest Type name / %ntLJ3 full type name / System.%ntLJ

!. A%s$e..aneous

!.1 6ow do # do a $ase-%nsens%t%)e str%n, $ompar%son(


Hse the 2trin!.%ompare function. "ts third parameter is a $oolean which specifies whether case should $e i!nored or not.
"fre." // "-re." // false System.Strin!.Compare( "fre."3 "-re."3 true )

// true

!.2 8oes "2 support a )ar%a5.e num5er o* ar,uments(


Jes usin! the params keyword. The ar!uments are specified as a list of ar!uments of a specific type e.!. int. For ultimate fle'i$ility the type can $e o$7ect. The standard e'ample of a method which uses this approach is 2ystem.%onsole.5rite-ineEF.

!. 6ow $an # pro$ess $ommand-.%ne ar,uments(


-ike this+
usin! System; class C#pp { public static 6oi. &ain( strin!9; ar!s ) { Console.WriteLine( "Xou passe. t'e follo1in! ar!uments " ); foreac'( strin! ar! in ar!s ) Console.WriteLine( ar! ); } }

!.+ 8oes "2 do arra- 5ounds $'e$k%n,(


Jes. An "nde'&ut&f.an!e e'ception is used to si!nal an error.

!.5 6ow $an # make sure m- "2 $.asses w%.. %nteroperate w%t' ot'er .NET .an,ua,es(
Make sure your %/ code conforms to the %ommon -an!ua!e 2u$set E%-2F. To help with this add the Passem$ly+%-2%ompliantEtrueFQ !lo$al attri$ute to your %/ source files. The compiler will emit an error if you use a %/ feature which is not %-2)compliant.

!.! 6ow do # use t'e 3us%n,3 ke-word w%t' mu.t%p.e o5:e$ts(


Jou can nest usin! statements like this+
usin!( ob*F ) { usin!( ob*8 ) { ... } }

?owe#er consider usin! this more aesthetically pleasin! E$ut functionally identicalF formattin!+
usin!( ob*F ) usin!( ob*8 ) { ... }

!.7 &'at %s t'e d%**eren$e 5etween KK and o5:e$t.ELua.s(


For #alue types KK and ENualsEF usually compare two o$7ects $y value. For e'ample+
int < / F5; int y / F5; Console.WriteLine( < // y ); Console.WriteLine( <.>Iuals(y) );

will display+
True True

?owe#er thin!s are more comple' for reference types. 8enerally speakin! for reference types KK is e'pected to perform an identity comparison i.e. it will only return true if $oth references point to the same o$7ect. Cy contrast ENualsEF is e'pected to perform a value comparison i.e. it will return true if the references point to o$7ects that are equivalent. For e'ample+
Strin!(uil.er sF / Strin!(uil.er s8 / Console.WriteLine( Console.WriteLine( ne1 Strin!(uil.er("fre."); ne1 Strin!(uil.er("fre."); sF // s8 ); sF.>Iuals(s8) );

will display+
-alse True

s: and s2 are different o$7ects Ehence KK returns falseF $ut they are eNui#alent Ehence ENualsEF returns trueF. Hnfortunately there are e'ceptions to these rules. The implementation of ENualsEF in 2ystem.&$7ect Ethe one you6ll inherit $y default if you write a classF compares identity i.e. it6s the same as operatorKK. 2o ENualsEF only tests for eNui#alence if the class author o#errides the method Eand implements it correctlyF. Another e'ception is the strin! class ) its operatorKK compares #alue rather than identity. Cottom line+ "f you want to perform an identity comparison use the .eferenceENualsEF method. "f you want to perform a #alue comparison use ENualsEF $ut $e aware that it will only work if the type has o#erridden the default implementation. A#oid operatorKK with reference types Ee'cept perhaps strin!sF as it6s simply too am$i!uous.

!.8 6ow do # en*or$e $onst $orre$tness %n "2(


Jou can6t ) at least not in the same way you do in %00. %/ Eactually the %-"F has no real concept of const correctness For e'ample there6s no way to specify that a method should not modify an ar!ument passed in to it. And there6s no way to specify that a method does not modify the o$7ect on which it is actin!. To !et a feel for the an!st this causes amon! some %00 pro!rammers read the feed$ack on this post from .aymond %hen. There are of course ways of addressin! this issue. For e'ample see Crad A$ram6s post Eand associated feed$ackF for some ideas on addin! optional read)only $eha#iour to collection classes.

7. "2 2.0

7.1 &'at are t'e new *eatures %n "2 2.0(


2upport for all of the new framework features such as !enerics anonymous methods partial classes iterators and static classes. 2ee the .NET FAQ for more on these features. (ele!ate inference is a new feature of the %/ compiler which makes dele!ate usa!e a little simpler. "t allows you to write this+
T'rea. t / ne1 T'rea.(T'rea.-unc);

instead of this+
T'rea. t / ne1 T'rea.( ne1 T'rea.Start(T'rea.-unc) );

Another minor $ut welcome addition is the e'plicit !lo$al namespace which fi'es a hole in namespace usa!e in %/ :.'. Jou can prefi' a type name with ,.o5a.:: to indicate that the type $elon!s to the

!lo$al namespace thus a#oidin! pro$lems where the compiler infers the namespace and !ets it wron!. Finally %/ 2.0 includes some syntactic su!ar for the new 2ystem.Nulla$le type. Jou can use T( as a synonym for 0-stem.Nu..a5.eGTH where T is a #alue type. As su!!ested $y the name this allows #alues of the type to $e 6null6 or 6undefined6.

7.2 Are "2 ,ener%$s t'e same as "EE temp.ates(


No not really. There are some similarities $ut there are also fundamental differences. 2ee the .NET FAQ for more details.

FAQs
The FAQs have been split into a few broad categories. In many senses, a lot of the FAQs aren't really appropriate for the C# newsgro p in the first place, b t that's tr e of a lot of the posts in the gro p anyway, and I'd rather people were able to find the answer here than as! a possibly inappropriate " estion in the gro p. #here $my$ and $I$ are sed, this tends to indicate %on &!eet as the initial a thor of the FAQ. If many e'tra " estions and answers are added which se the first person, I'll convert everything to the third person, b t for now I thin! it'll s ffice.

C# and .NET descriptions and history


#hat is C#( #hat is .)*T( #hat version of #indows do I need to se .)*T( +o I have to be r nning #indows to se .)*T( +oes the framewor! have to be installed to r n my .)*T application( #hat do all the acronyms ,C-I, C-., I- etc/ mean( #hat is #hidbey and when is it coming o t(

C# as a language

#here is the C# specification( &ho ld I choose 01.)*T or C#( #hy doesn't C# have 01's 'with' feat re( #hy doesn't C# have m ltiple inheritance( +oes C# have macros or a preprocessor( +oes C# have templates li!e C22( Are parameters passed by reference or val e in C#( Are constr ctors inherited in C#( 3ow do I call one constr ctor from another( #hat does an 4 before the start of a string literal mean(

#hat does an 4 before the start of an identifier mean( #hat character escape se" ences are available( #hy can't I se static and const together( #hat's the difference between an event and a delegate( #hat's the difference between strin! and System.Strin!B Can I define a property to have different $get$ access to $set$ access( #hat's the difference between o6erri.e and ne1( #hat's the difference between sing cast synta' and the as operator( 3ow do I se an alias for a namespace or class( #hy doesn't C# have chec!ed e'ceptions( #hy are str ct constr ctors in C# re" ired to have at least one arg ment( 3ow do I tell C# what !ind of literal n mber I want( #hat's the difference between the ref and o t modifiers on parameters( #hen sho ld I se >Iuals and when sho ld I se //(

Converting to C# from VB.NET


#hat's the e" ivalent of ,ot'in!( 3ow do I get the rightmost part of a string( #hat do I se instead of a..ressof( Is there an e" ivalent of &yClass( #hat are the e" ivalents of &e and &y(ase( Is there a f ller comparison between C# and 01.)*T(

.NET core li raries


3ow do I start another program from .)*T( 3ow do I ma!e s re that only one instance of my application r ns at a time( #hy can't I read files with accented characters( #hy does .)*T get simple arithmetic wrong( 3ow can I call a method when I have its name as a string( 3ow can I show an int as a binary n mber 5 a string of 6s and 7s( #hy doesn't calling %nitialiAe() on a reference5type array fill the array with ob8ects( +oes .)*T have any compressiong9:ipping capabilities( 3ow do I retrieve assembly attrib tes at r ntime( 3ow do I convert a strin! to an int etc( #hat's the difference between Con6ert.To%nt78(strin!) and %nt78.=arse(strin!)( 3ow do I create an instance of a type if I only !now its name( #hat's the simplest way of retrieving a web page in .)*T(

!indo"s Forms programming

3ow do I pass parameters from one form to another(

3ow do I set the bac!gro nd of an ;+I container window(

A#$.NET programming
,)o " estions yet./

A%&.NET programming

#hich sho ld I call on database connections< $ispose or Close( 3ow sho ld I escape te't in &Q- statements, and e'press dates and times(

'eneral (uestions

3ow can I protect my code against decompilation(

)esources

#hat other relevant FAQs are available( #hat online t torials are available( #hat are the best C#9.)*T boo!s available(

Ans"ers
C# and .NET descriptions and history What is C#?
C# is a lang age created by ;icrosoft specifically for the .)*T framewor!. It has been standardised by *C;A for version 6, and version = will no do bt go thro gh *C;A when it's been f lly released by ;icrosoft. It is similar in synta' to the C lang age of families, and also appears to borrow from %ava and +elphi. ,This is in no way a criticism of it 5 it's always good to learn from the mista!es and positive aspects of other things./

What is .NET?

.)*T is a platform created by ;icrosoft. It consists of a virt al e'ec tion environment ,incl ding garbage collection, %ITting, strong versioning, type and memory safety etc/ and a large r ntime library. It is at the heart of ;icrosoft's f t re strategy for the #indows platform, and will be a central part of the ne't release of #indows ,-onghorn/.

What version of Windows do I need to use .NET?


The .)*T framewor! itself r ns on all versions of #indows from #indows >?9)T@ pwards. It does not r n on #indows >A or )TB.A. For )T@, it re" ires service pac! Ca.

Do I have to be running Windows to use .NET?


There are vario s ,mostly open so rce/ pro8ects to write a C-. ,Common -ang age . ntime/ on other operating systems s ch as -in ' and 1&+. The two best !nown are<

;ono 5 an open so rce m lti5platform system .DTD. 5 a ;icrosoft &hared &o rce implementation for Free1&+, #indows EF and ;ac D& E 67.=. ,-in! is to a website with a range of lin!sG no one lin! seems partic larly s itable on its own./

&trictly spea!ing, these are not act ally .)*T 5 .)*T is ;icrosoft's closed5so rce #indows5only implementation of the C-. and other technologies, incl ding vario s other framewor! libraries which aren't all covered in the above pro8ects ,which may themselves have libraries which aren't in .)*T5 proper/. They do, however, allow yo to write programs in C# and r n them.

Does the framework have to be installed to run my .NET a

li!ation?

Hes 5 if yo have a managed application, it will re" ire the framewor! to be present in order to r n. This is li!e re" iring the #inB= libraries to be present in order to r n #indows applications. Fre5 compiling yo r code sing ngen doesn't affect this re" irement. 3aving said the above, there are two prod cts which b ild everything yo need from the framewor! for yo r application, along with yo r application itself, into one big b ndle<

.emote&oft's lin!er and mini5deployment tool Thinstall &t dio

1oth of these mean the framewor! itself isn't re" ired, and give additional protection against decompilation. The downside is that if a ser then has many s ch applications, they end p effectively with m ltiple copies of bits of the framewor!. I cannot vo ch for either of these prod cts myself, as I've had no e'perience of them.

What do all the a!ronyms "C#I$ C#%$ I# et!& mean?


There are many acronyms in .)*T and related technologies. They're often ab sed, incl ding by me, almost always n!nowingly. +on't be too worried abo t them. CI- 5 Common Intermediate -ang age The lang age all .)*T lang ages compile to. *" ivalent to %ava bytecode. C-I 5 Common -ang age Infrastr ct re The combination of the C-., C-&, CT& and CIC-. 5 Common -ang age . ntime The r ntime environment itself, incl ding garbage collection, threading etc. C-& 5 Common -ang age &pecification A set of conventions intended to promote lang age interoperability. CT& 5 Common Type &ystem The lang age5ne tral type system sed in the C-I. I- 5 Intermediate -ang age ;ore commonly sed abbreviation for CI-. 0*& 5 0irt al *'ec tion &ystem Another name for the C-. as far as I can tell.

What is Whidbey and when is it !oming out?


#hidbey is the ne't version of 0is al &t dio .)*T, and is closely tied to 0=.7 of the framewor!. It is li!ely to be released in the first half of =77A.

C# as a language Where is the C# s e!ifi!ation?


There are two versions of the C# specification 5 one from ;icrosoft, and one from *C;A. They are the same in all important respects as far as I can tell ,a few pieces of e'planatory wording are different, b t nothing that affects the specification itself/ b t the n mbering of sections is different. The *C;A specification is available as a F+F, or yo can email *C;A and they will send yo a hard copy for free. +etails are on the *C;A website. Alternatively, %on %agger's 3T;- version is available and is a sef l download. It is from a draft version, b t it's very close to the final version. I don't !now whether or not %on %agger is planning to ma!e an 3T;- copy of version = of the specification when it's released. The ;icrosoft version is available online or within the offline version of the ;&+) 5 loo! for $specifications, 0is al C#$ in the inde' to find it " ic!ly.

'hould I !hoose ().NET or C#?


The choice between C# and 01.)*T is largely one of s b8ective preference. &ome people li!e C#'s terse synta', others li!e 01.)*T's nat ral lang age, case5insensitive approach. 1oth have access to the same framewor! libraries. 1oth will perform largely e" ivalently ,with a few small differences which are nli!ely to affect most people, ass ming 01.)*T is sed with )ption Strict on/. -earning the .)*T framewor! itself is a m ch bigger iss e than learning either of the lang ages, and it's perfectly possible to become fl ent in both 5 so don't worry too m ch abo t which to pl mp for. There are, however, a few act al differences which may affect yo r decision<
VB.NET Advantages

& pport for optional parameters 5 very handy for some CD; interoperability & pport for late binding with )ption Strict off 5 type safety at compile time goes o t of the window, b t legacy libraries which don't have strongly typed interfaces become easier to se. & pport for named inde'ers ,a!a properties with parameters/. 0ario s legacy 01 f nctions ,provided in the &icrosoft.Hisual(asic namespace, and can be sed by other lang ages with a reference to the &icrosoft.Hisual(asic..ll/. ;any of these can be harmf l to performance if sed nwisely, however, and many people believe they sho ld be avoided for the most part. &ome methods here are apparently faster than the more idiomatic .)*T e" ivalent, however. .eadability sho ld be considered< sing 01 f nctions probably ma!es the code easier for a 015classic programmer to read, b t harder for someone from a bac!gro nd in another .)*T lang age to read. The 1it' constr ct< it's a matter of debate as to whether this is an advantage or not, b t it's certainly a difference. &impler ,in e'pression 5 perhaps more complicated in nderstanding/ event handling, where a method can declare that it handles an event, rather than the handler having to be set p in code. The ability to implement interfaces with methods of different names. ,Arg ably this ma!es it harder to find the implementation of an interface, however./ Catc' ... W'en ... cla ses, which allow e'ceptions to be filtered based on r ntime e'pressions rather than 8 st by type. The 01.)*T part of 0is al &t dio .)*T compiles yo r code in the bac!gro nd. #hile this is considered an advantage for small pro8ects, people creating very large pro8ects have fo nd that the I+* slows down considerably as the pro8ect gets larger.

C# Advantages

E;- doc mentation generated from so rce code comments. ,This is coming in 01.)*T with #hidbey ,the code name for the ne't version of 0is al &t dio and .)*T/, and there are tools which will do it with e'isting 01.)*T code already./ Dperator overloading 5 again, coming to 01.)*T in #hidbey. -ang age s pport for nsigned types ,yo can se them from 01.)*T, b t they aren't in the lang age itself/. Again, s pport for these is coming to 01.)*T in #hidbey. The usin! statement, which ma!es nmanaged reso rce disposal simple. *'plicit interface implementation, where an interface which is already implemented in a base class can be reimplemented separately in a derived class. Arg ably this ma!es the class harder to nderstand, in the same way that member hiding normally does.

Insafe code. This allows pointer arithmetic etc, and can improve performance in some sit ations. 3owever, it is not to be sed lightly, as a lot of the normal safety of C# is lost ,as the name implies/. )ote that nsafe code is still managed code, i.e. it is compiled to I-, %ITted, and r n within the C-..

+espite the fact that the above list appears to favo r 01.)*T ,if yo don't mind waiting for #hidbey/, many people ,myself incl ded/ prefer C#'s terse synta' eno gh to ma!e them se C# instead.

Why doesn*t C# have ()*s *with* feature?


;any people, incl ding myself and the C# lang age designers, believe that 'with' often harms readability, and is more of a c rse than a blessing. For more information, see the As! a C# -ang age +esigner page.

Why doesn*t C# have multi le inheritan!e?


C# ,and .)*T in general/ has m ltiple inheritance of interface ,meaning that yo can implement many interfaces in a type/ b t only single inheritance of implementation ,meaning that yo can only derive a class from one other class 5 which may, itself derive from another, etc/. ,I'll get ro nd to the act al reasoning behind this sooner or later.../

Does C# have ma!ros or a re ro!essor?


C# doesn't have macros as s ch, nor does it strictly spea!ing have a pre5processor, b t it does have conditional compilation symbols which can be sed to affect compilation. These can be defined within code or with parameters to the compiler. The $pre5processing$ directives in C# ,named solely for consistency with C9C22, despite there being no separate pre5processing step/ are ,te't ta!en from the *C;A specification/< and Zun.ef Ised to define and ndefine conditional compilation symbols Zif, Zelif, Zelse and Zen.if Ised to conditionally s!ip sections of so rce code
Z.efine Zline

Ised to control line n mbers emitted for errors and warnings. Zerror and Z1arnin! Ised to iss e errors and warnings. Zre!ion and Zen.re!ion Ised to e'plicitly mar! sections of so rce code. &ee section >.A of the *C;A specification for more information on the above. Conditional compilation can also be achieved sing the Con.itional attrib te on a method, so that calls to the

method will only be compiled when the appropriate symbol is defined. &ee section =@.@.= of the *C;A specifcation for more information on this.

Does C# have tem lates like C++?


Altho gh C# doesn't have templates, and isn't li!ely to get them, it is getting a feat re called generics which will be available in #hidbey, the ne't version of .)*T, which sho ld be available in the first half of =77A. ,A beta version is c rrently available./ Jenerics will be a feat re in the C-. itself, and most lang ages targetting the C-. will change to s pport it. Jenerics provide a lot of the f nctionality of C22 templates ,mostly in terms of type safety/ b t in a more restricted ,and therefore potentially less conf sing/ way.

,re arameters assed by referen!e or value in C#?


1y defa lt, all parameters are passed by val e in C# 5 b t yo need to be aware that when yo 're passing a reference type, yo 're passing a reference rather than an act al ob8ect. For more information, see my article on parameter passing.

,re !onstru!tors inherited in C#?


)o, constr ctors are not inherited. For more information abo t constr ctors and constr ctor chaining, see my article on constr ctors.

-ow do I !all one !onstru!tor from another?


Ho se base (parameters) or t'is (parameters) 8 st before the act al code for the constr ctor, depending on whether yo want to call a constr ctor in the base class or in this class. For more information abo t constr ctor chaining, see my article on constr ctors.

What does an . before the start of a string literal mean?


A string literal s ch as V"c W-oo" is called a verbatim string literal. It basically means, $don't apply any interpretations to characters ntil the ne't " ote character is reached$. &o, a verbatim string literal can contain bac!slashes ,witho t them being do bled5 p/ and even line separators. To get a do ble5 " ote ,"/ within a verbatim literal, yo need to 8 st do ble it, e.g. V"&y name is ""Uon""" represents the string &y name is "Uon". 0erbatim string literals which contain line separators will also contain the white5space at the start of the line, so I tend not to se them in cases where the white5 space matters. They're very handy for incl ding E;- or &Q- in yo r so rce code tho gh, and another typical se ,which doesn't need line separators/ is for specifying a path.

What does an . before the start of an identifier mean?


#hen 4 appears before an identifier ,the name of a variable, property, method etc/, it indicates that the compiler sho ld treat what follows as an identifier, even if it normally means something else. For instance, this code fails to compile<
int t'is / J8; // 0t'is0 is a reser6e. 1or.

b t this code compiles s ccessf lly<


int Vt'is / J8;

What !hara!ter es!a e se/uen!es are available?


C# defines the following character escape se" ences<
W0 5 single " ote, needed for character literals W" 5 do ble " ote, needed for string literals WW 5 bac!slash W5 5 Inicode character 7 Wa 5 Alert ,character K/ Wb 5 1ac!space ,character ?/ Wf 5 Form feed ,character 6=/ Wn 5 )ew line ,character 67/ Wr 5 Carriage ret rn ,character 6B/ Wt 5 3ori:ontal tab ,character >/ W6 5 0ertical " ote ,character 66/ Wu<<<< 5 Inicode escape se" ence for character with he' val e '''' W<n9n;9n;9n; 5 Inicode escape se" ence for character with he' val

e nnnn ,variable length version of L ''''/ W2<<<<<<<< 5 Inicode escape se" ence for character with he' val e '''''''' ,for generating s rrogates/

Df these, Wa, Wf, W6, W< and W2 are rarely sed in my e'perience.

Why !an*t I use static and const together?


All constants declarations are implicitly static, and the C# specification states that the ,red ndant/ incl sion of the static modifier is prohibited. I believe this is to avoid the conf sion which co ld occ r if a reader were to see two constants, one declared static and one not 5 they co ld easily ass me that the difference in specification implied a difference in semantics. ,3aving said that, there is no prohibition on red ndantly specifying an access modifier which is also the defa lt one, where there is a choice. For instance, a ,concrete/ method can be e'plicitly mar!ed as private despite that being the

defa lt. The r le appears to be that where there is no choice ,e.g. a method declaration in an interface/ the red ndant modifier is prohibited. #here there is a choice, it's allowed.

What*s the differen!e between an event and a delegate?


F t simply, an event gives more limited access than a delegate. If an event is made p blic, code in other classes can only add or remove handlers for that eventG they can't necessarily fire it, find o t all the handlers for it, or remove handlers they don't !now abo t. *vents also allow more fle'ibility in terms of how the handlers are stored. For more details on this, see *ric J nnerson's article on the topic.

What*s the differen!e between string and System.String?


C# defines a n mber of aliases for C-. types. They may be sed interchangably, and even mi'ed together, e.g. strin! < / ne1 System.Strin!(0 03 K);. These are the aliases defined< Alias string sbyte byte short short int int long long char float do ble bool decimal C*) type &ystem.&tring &ystem.&1yte &ystem.1yte &ystem.Int6C &ystem.IInt6C &ystem.IntB= &ystem.IIntB= &ystem.IntC@ &ystem.IIntC@ &ystem.Char &ystem.&ingle &ystem.+o ble &ystem.1oolean &ystem.+ecimal

Can I define a ro erty to have different 0get0 a!!ess to 0set0 a!!ess?


Infort nately, yo can't at the moment 5 if a property is p blic, it's wholly p blic. It needn't have a setter ,or, in rare cases, it can have a setter b t no getter/ b t yo can't have a p blic getter and a private setter, or vice versa. Than!f lly, this is being changed in #hidbey.

What*s the differen!e between override and new?

This is all to do with polymorphism. #hen a virt al method is called on a reference, the act al type of the ob8ect that the reference refers to is sed to decide which method implementation to se. #hen a method of a base class is overridden in a derived class, the version in the derived class is sed, even if the calling code didn't $!now$ that the ob8ect was an instance of the derived class. For instance<
public class (ase { public 6irtual 6oi. Some&et'o.() { } } public class $eri6e. (ase { public o6erri.e 6oi. Some&et'o.() { } } ... (ase b / ne1 $eri6e.(); b.Some&et'o.();

will end p calling $eri6e..Some&et'o. if that overrides (ase.Some&et'o.. )ow, if yo se the ne1 !eyword instead of o6erri.e, the method in the derived class doesn't override the method in the base class, it merely hides it. In that case, code li!e this<
public class (ase { public 6irtual 6oi. Some)t'er&et'o.() { } } public class $eri6e. (ase { public ne1 6oi. Some)t'er&et'o.() { } } ... (ase b / ne1 $eri6e.(); $eri6e. . / ne1 $eri6e.(); b.Some)t'er&et'o.(); ..Some)t'er&et'o.();

#ill first call (ase.Some)t'er&et'o. ,line B/, then $eri6e..Some)t'er&et'o. ,line @/. They're effectively two entirely separate methods which happen to have the same name, rather than the derived method overriding the base method. If yo don't specify either ne1 or o6erri.es, the res lting o tp t is the same as if yo specified ne1, b t yo 'll also get a compiler warning ,as yo may not be aware that yo 're hiding a method in the base class method, or indeed yo may have wanted to override it, and merely forgot to incl de the !eyword/. That provides the basics of overriding and the difference between ne1 and o6erri.e, b t yo sho ld really see a boo! or t torial for a more in5depth loo! at polymorphism.

-ow !an I !all a method when I have its name as a string?


#hat yo need is reflection. The basic idea is that yo find the type which contains the method, find the method from that type, and then invo!e it. 3ere's a sample program 5 it's simple ,it doesn't pass any parameters, it only finds a p blic method, it doesn't se a ret rn val e/ b t it gives the basic idea. -oo! p the relevant methods in ;&+) for more information.
usin! System; usin! System."eflection; class Test { strin! name; Test (strin! name) { t'is.name / name; } public 6oi. S'o1,ame() { Console.WriteLine(name); } static 6oi. &ain() { // Create an instance of Test Test t / ne1 Test ("-oo"); // +et t'e met'o. 1e 1ant to call &et'o.%nfo mi / typeof(Test).+et&et'o.("S'o1,ame"); // Call it on t'e instance 1e06e create.3 // 1it' no ar!uments mi.%n6o:e (t3 null); } }

What*s the differen!e between using !ast synta1 and the as o erator?
Ising the as operator differs from a cast in C# in three important ways< 6. It ret rns a n ll when the variable yo are trying to convert is not of the re" ested type or in it's inheritance chain, instead of throwing an e'ception. =. It can only be applied to reference type variables converting to reference types. B. Ising as will not perform ser5defined conversions, s ch as implicit or e'plicit conversion operators, which casting synta' will do. There are in fact two completely different operations defined in I- that handle these two !eywords ,the castclass and isinst instr ctions/ 5 it's not 8 st $syntactic s gar$ written by C# to get this different behavior. The as operator appears to be slightly faster in v6.7 and v6.6 of ;icrosoft's C-. compared to casting ,even in cases where there are no invalid casts which wo ld severely lower casting's performance d e to e'ceptions/.

-ow do I use an alias for a names a!e or !lass?


Ise the usin! directive to create an alias for a long namespace or class. Ho can then se it anywhere yo normally wo ld have sed that class or namespace. The sing alias has a scope within the namespace yo declare it in. &ample code<
// ,amespace usin! act / System."untime."emotin!.#cti6ation; // Class usin! list / System.Collections.#rrayList; ... list l / ne1 list(); // Creates an #rrayList act.2rl#ttribute foo; // >Iui6alent to System."untime."emotin!.#cti6ation.2rl#ttribute foo

Why doesn*t C# have !he!ked e1!e tions?


Chec!ed e'ceptions are a very hotly debated topic in some circles, partic larly for e'perienced %ava developers moving to, or additionally learning, C#. 3ere are some reso rces that disc ss the iss e in depth<

The Tro ble #ith Chec!ed *'ceptions ,Anders 3e8lsberg, 1r ce *c!el, 1ill 0enners/ +oes %ava )eed Chec!ed *'ceptions( ,1r ce *c!el/

)ote that witho t the C-. itself s pporting chec!ed e'ceptions, it wo ld be effectively impossible for C# to do so alone.

Why are stru!t !onstru!tors in C# re/uired to have at least one argument?


The .)*T r ntime can't g arantee that parameterless constr ctors will be called. If str cts where to allow defa lt, parameterless constr ctors, it wo ld imply that these defa lt constr ctors wo ld MalwaysM be called. 3owever, the r ntime can not ma!e this g arantee. For e'ample an array of val e types will be initiali:ed to the initial val es of it's members ,i.e. 7 for n mber type primitive members, n ll for reference types etc/ not to the val es provided in a defa lt constr ctor 5 which ma!es str cts better performing by not having to call constr ctor code. *nforcing a minim m of one parameter in the constr ctor red ces the possibility that someone will define a constr ctor that they then e'pect to be called every time one of their str ct types is constr cted.

-ow do I tell C# what kind of literal number I want?


If yo need to tell C# that yo want it to treat a literal as a partic lar type of n mber, yo may do so by adding a n mber type s ffi' at the end of the literal yo provide. For e'ample<
F2; // #n unsi!ne. int Ful; // #n unsi!ne. lon! Ff; // # System.Sin!le floatin!Gpoint number; F.; // # System.$ouble floatin!Gpoint number Fm; // a System.$ecimal floatin!Gpoint number

This is somewhat important beca se sometimes yo m st match a literal to the signat re of something or specify the val e to 'defeat' an implicit cast behavior yo don't li!e. For e'ample, Has'table names / ne1 Has'table(F553 5.F); won't compile beca se the constr ctor ta!es parameters (int3 float) and the above is (int3 .ouble). The line sho ld read Has'table names / ne1
Has'table(F553 5.Ff);

A f ll listing of the s ffi'es is in the Jrammar portion of the C# specification ,appendi' A in the *C;A specification, appendi' C in the ;& specification/. The s ffi'es are also detailed in the -iterals section of the specification ,>.@.@ of the *C;A specification, =.@.@ of the ;& specification/.

What*s the differen!e between the ref and out modifiers on arameters?
1oth the ref and out modifiers are applied to arg ments of a method and both mean that the arg ment will be passed $by reference$ ,either a val e type variable by reference or a reference type variable by reference/. The out parameter, however, allows yo to pass in an ninitiali:ed variable li!e so and g arantees it will come bac! with it's val e set ,so long as the called method was written in C#, anyway/.
int i; $oStuff(y"ef(out i); // i is no1 a usable int 6alue

For more details, see my article on parameter passing.

!hen should + use Equals and "hen should + use ==,


The >Iuals method is 8 st a virt al one defined in System.)b*ect, and overridden by whichever classes choose to do so. The // operator is an operator which can be overloaded by classes, b t which s ally has identity behavio r. For reference types where // has not been overloaded, it compares whether two references refer to the same ob8ect 5 which is e'actly what the implementation of >Iuals does in System.)b*ect. 0al e types do not provide an overload for // by defa lt. 3owever, most of the val e types provided by the framewor! provide their own overload. The defa lt implementation of >Iuals for a val e type is provided by HalueType, and ses reflection to ma!e the comparison, which ma!es it significantly slower than a type5specific implementation normally wo ld be. This implementation also calls >Iuals on pairs of references within the two val es being compared. 3owever, the main difference between the two types of comparison in normal se ,where yo 're nli!ely to be defining yo r own val e types very often/ is polymorphism. Dperators are overloaded, not overridden, which means that nless the compiler !nows to call the more specific version, it'll 8 st call the identity version. To ill strate that, here's an e'ample<
usin! System; public class Test { static 6oi. &ain() { // Create t1o eIual but .istinct strin!s strin! a / ne1 strin!(ne1 c'ar9; {0'03 0e03 0l03 0l03 0o0}); strin! b / ne1 strin!(ne1 c'ar9; {0'03 0e03 0l03 0l03 0o0}); Console.WriteLine (a//b); Console.WriteLine (a.>Iuals(b)); // ,o1 let0s see 1'at 'appens 1it' t'e same tests but // 1it' 6ariables of type ob*ect ob*ect c / a; ob*ect . / b; Console.WriteLine (c//.); Console.WriteLine (c.>Iuals(.));

} }

The res lts are<


True True -alse True

The third line is -alse beca se the compiler can only call the non5overloaded version of // as it doesn't !now that the contents of c and . are both string references. As they are references to different strings, the identity operator ret rns false. &o, when sho ld yo se which operator( ;y r le of th mb is that for almost all reference types, se >Iuals when yo want to test e" ality rather than reference identity. The e'ception is for strings 5 comparing strings with // does ma!e things an awf l lot simpler and more readable but yo need to remember that both sides of the operator m st be e'pressions of type string in order to get the comparison to wor! properly. For val e types, I'd normally se // for easier5to5read code. Things wo ld get tric!y if a val e type provided an overload for // which acted differently to >Iuals, b t I'd consider s ch a type very badly designed to start with.

Converting to C# from VB.NET What*s the e/uivalent of Nothing?


For reference types, the e" ivalent of 01's ,ot'in! is C#'s null. For val e types, it's the defa lt val e 5 7, false, etc.

-ow do I get the rightmost art of a string?


Ise Strin!.Substrin!. Ass ming that < is a string of length at least n, to get the last n characters, yo wo ld se <.Substrin!(<.Len!t'Gn).

What do I use instead of addressof?


To create delegate instances in C#, yo 8 st specify the delegate type, the method, and ,if yo want to create a delegate targetting a different instance or type from the c rrent one/ the target. For instance, each of these creates a T'rea.Start delegate<
T'rea.Start <F / ne1 T'rea.Start(Some%nstance&et'o.); T'rea.Start <8 / ne1 T'rea.Start(#not'erType.SomeStatic&et'o.);

T'rea.Start <7 / ne1 T'rea.Start(someHariable.Some%nstance&et'o.);

Is there an e/uivalent of MyClass?


)o, C# doesn't have an e" ivalent of 01.)*T's &yClass !eyword. If yo want to g arantee not to call an overridden version of a method, yo need to ma!e it non5virt al in the first place.

What are the e/uivalents of Me and MyBase?


in C# is t'is, and &y(ase in C# is base. To access normal members, 8 st se t'is.member,ame or base.member,ame. For information abo t chaining constr ctors together, see my article on constr ctors.
&e

Is there a fuller !om arison between C# and ().NET?


;icrosoft provides a very f ll lang age e" ivalents page which compares not only C# and 01.)*T, b t also other lang ages targeted at the .)*T framewor!. It loo!s at the e" ivalent concepts, !eywords, types, operators etc. A very val able reso rce when yo 're trying to read or write code in a lang age which isn't yo r preferred one.

.NET core li raries -ow do I start another rogram from .NET?


Ho need to se the =rocess.Start method. Ho can b ild more complicated start5 p parameters sing the =rocessStart%nfo class which allows yo to specify command line parameters, redirect o tp t etc. The =rocessStart%nfo and =rocess classes are in the System.$ia!nostics namespace.

-ow do I make sure that only one instan!e of my a

li!ation runs at a time?

Frobably the best way of accomplishing this is sing a named m te'. Create the m te' sing code s ch as<
bool first%nstance; &ute< mute< / ne1 &ute<(false3 "LocalWW"4some2niIue,ame3 out first%nstance); // %f first%nstance is no1 true3 1e0re t'e first instance of t'e application;

// ot'er1ise anot'er instance is runnin!.

)ote that the m te' is a local one, which means it's in the c rrent ser's session 5 witho t the local part, other sers wo ld share the m te', so two different sers co ldn't r n the program at the same time. Also note that , nli!e vario s samples aro nd the net/ my code doesn't have a call to .elease; te' 5 this is beca se the m te' will a tomatically be released when the process dies, which is s ally the desired behavio r anyway. Dne thing to beware of is that the m te' isn't garbage collected. If a local variable is only sed near the start of a method, the JC may ignore it when wor!ing o t which variables are garbage collection $roots$ if that part of the method has already been e'ec ted. This can lead to the m te' being released earlier than yo might anticipateN To prevent this from happening, ma!e a call to +C.[eep#li6e (mute<); at the end of yo r main method. Alternatively, se a static variable to store the m te'. That will ens re that the m te' is not garbage collected ntil the #pp$omain is nloaded. ,That way even if &ain terminates, yo won't have any problems if yo 've got other threads r nning./ Another way of attac!ing the problem ,which comes with its own iss es/ is to listen on a local port. As only one process can listen on any partic lar port, that can ens re that no other instance of yo r application is r nning. 3owever, it co ld 8 st be that another application wants to se that port, in which case either yo r application will thin! there's another instance r nning, or the other application is li!ely to malf nction. )ote that this approach has the added benefit that it provides a comm nication channel between the $main$ instance and the newly created instance 5 if, say, the newly created instance wants to tell the main instance to open a file that the ser has 8 st re" ested, it can do so sing the soc!et.

Why !an*t I read files with a!!ented !hara!ters?


#henever te't is stored in a file, or sent across a networ!, it is always encoded in some way or other, to convert the characters into bytes. It then needs to be decoded to get the characters bac! again. If yo se the wrong encoding, yo ,nat rally/ get the wrong res lts. This is s ally the ca se of a fail re to see $e'tended$ characters. It's a big topic, so see my article on Inicode for more information.

Why does .NET get sim le arithmeti! wrong?


.)*T doesn't get arithmetic wrong, as s ch 5 it 8 st does arithmetic in a different way to how yo might e'pect. For instance, when yo write 7.6 in code to be stored in a do ble variable, the val e stored isn't act ally 7.6. It's as close to 7.6 as can be represented in the do ble type, b t it's not act ally 7.6. This is beca se the float9do ble types are binary floating point types, and 7.6 ,decimal/ can't be e'actly represented in base =. For more information on this, see my article on .)*T floating point types.

-ow !an I show an int as a binary number 2 a string of 3s and 4s?


The Con6ert class has an overload of the static ToStrin!() method that ta!es two ints and ret rns a string pop lated with the n mber in the specified base. For instance, calling Con6ert.ToStrin!(F8M3 8) will ret rn $67777777$.

Why doesn*t !alling Initialize() on a referen!e2ty e array fill the array with ob5e!ts?
The System.#rray class instance method %nitialiAe() e'ists solely to initiali:e val e type arrays to their defa lt val es and is not valid on reference type arrays. ,In fact it is not even intended for C# val e type str cts, as these str cts can have no defa lt constr ctor for %nitialiAe to call. C-. val e types are allowed to have parameterless constr ctors, b t there's no way of creating s ch a type in C#./

Does .NET have any !om ressiong67i

ing !a abilities?

The .)*T framewor! doesn't contain any general p rpose compression libraries, b t there are plenty of third5party libraries available. The most commonly referenced is probably &harpOip-ib, which is free and open so rce b t may still be sed in commercial applications.

-ow do I retrieve assembly attributes at runtime?


;ost of the assembly5wide attrib tes ,which are s ally specified in #ssembly%nfo.cs/ are available sing #ssembly.+etCustom#ttributes. For instance, to get the assembly title, yo co ld se code s ch as<
#ssembly t'is#sm / t'is.+etType().#ssembly; ob*ect9; attrs / t'is#sm.+etCustom#ttributes(typeof(#ssemblyTitle#ttribute)3 false)); if (attrs.Len!t' // F) { Console.WriteLine(((#ssemblyTitle#ttribute)attrs95;).Title); }

)ote, however, that #ssemblyHersion#ttribute ends p as 8 st part of the assembly name, which can be retrieved with the #ssembly.+et,ame method. The version can be retrieved from the name with the Hersion property. For e'ample<
#ssembly t'is#sm / t'is.+etType().#ssembly; Console.WriteLine (t'is#sm.+et,ame().Hersion);

-ow do I !onvert a string to an int et!?


In general, when yo want to convert from one type to another, the first class to loo! at is System.Con6ert. It has a load of static methods which are li!ely to help yo . If yo 're converting from a Strin!, yo co ld also chec! whether the type that yo want to convert to has a Farse method or something similar 5 for instance, I s ally se $ateTime.=arse><act to convert from a Strin! to a $ateTime.

What*s the differen!e between Convert.ToInt3

(string)

and Int3

.!arse(string)?

The two give identical res lts, e'cept where the string is null. Con6ert.To%nt78(null) ret rns :ero, whereas %nt78.=arse(null) throws an #r!ument,ull><ception.

-ow do I !reate an instan!e of a ty e if I only know its name?


This is a two stage process. Firstly, yo need to get a Type reference for the type. If the type yo want to create an instance of is in either mscorlib or the c rrent assembly, yo can 8 st se Type.+etType(name). If it's in a different assemby, yo co ld either call Type.+etType and pass in the full type name incl ding assembly information, or yo co ld find or load the assemnbly and then call #ssembly.+etType(name) on that assembly reference. Dnce yo 've got a Type reference, yo can either se #cti6ator.Create%nstance(type) to create an instance, or call Type.+etConstructor to get a specific constr ctor which yo can then se to create an instance by calling %n6o:e on it.

What*s the sim lest way of retrieving a web age in .NET?


For a good mi't re of fle'ibility and ease of se, the System.,et.Web"eIuest class is a good way of retrieving web content. &ome very simple code is given below, b t there are many options available incl ding asynchrono s downloads and lots of properties to both set and retrieve for the re" est and response. For some very simple scenarios, System.,et.WebClient is an alternative providing limited b t very easy to se f nctionality.
usin! System.,et; usin! System.%); usin! System.Te<t; ... strin! url / "'ttp //111.microsoft.com"; Web"eIuest reI / Web"eIuest.Create(url);

// // // // //

%f t'e 2"L is an HTT= one3 you can cast reI to HttpWeb"eIuest3 1'ic' allo1s you to set more properties3 suc' as t'e user a!ent. Similarly3 a response to an HTT= reIuest can be cast to HttpWeb"esponse.

usin! (Web"esponse resp / reI.+et"esponse()) { // &a:e sure you use t'e ri!'t enco.in! G // if you .on0t :no1 it in a.6ance3 you s'oul. // loo: at t'e response to see 1'at t'e 1eb ser6er // says it is. -or binary content3 you0. // 1ant to use t'e stream .irectly instea. // of 1rappin! it in a Stream"ea.er. usin! (Stream"ea.er rea.er / ne1 Stream"ea.er (resp.+et"esponseStream()3 >nco.in!.2T-M)) { strin! content / rea.er."ea.To>n.(); // $o 1'ate6er you 1ant 1it' t'e content 'ere } }

!indo"s Forms programming -ow do I ass arameters from one form to another?
Forms are 8 st ob8ects li!e any other. To call a method or pass a parameter from one form to another, yo need to have a reference to the $target$ form in the $so rce$ form, and the method9property9whatever of the $target$ form needs to be accessible ,which s ally means at least $internal$ visibility/.

-ow do I set the ba!kground of an 8DI !ontainer window?


The area of an ;+I container window is covered by an &.iClient control, so -orm.(ac:Color and -orm.(ac:!roun.%ma!e don't do anything sef l. Instead, iterate thro gh the controls to find the &.iClient, li!e this<
pri6ate 6oi. -ormPLoa.(ob*ect sen.er3 System.>6ent#r!s e) { foreac' (Control ctl in t'is.Controls) { if (ctl is &.iClient) // foun. it { ctl.(ac:Color / Color.Xello1;

} } }

brea:;

If yo need to pdate the ;+I bac!gro nd when the window is resi:ed 5 to !eep a logo in the centre, for e'ample 5 yo m st handle the =aint event for the &.iClient.

A#$.NET programming A%&.NET programming Whi!h should I !all on database !onne!tions9 "is#ose or Close?
As far as I can tell, the only difference between calling Close and $ispose on database connections sho ld be that Close leaves the connection in a re sable b t closed state 5 yo can still access all the properties, etc, and even call )pen again. As with any ob8ect, after calling $ispose on a database connection, yo sho ldn't access it any f rther. This does not mean that calling $ispose removes the connection from the connection pool, however. There is a sort of rban myth that it does, and that yo sho ld therefore only call Close on connections, and not $ispose. Fort nately, it's ntr e according to tests I've performed. I say $fort nately$ beca se it lends consistency to the framewor! 5 basically, yo sho ld always be able to call $ispose on an instnace of any type implementing %$isposable witho t s ffering from problems 5 it sho ld ,in my view/ be considered the $defa lt$ way of releasing non5memory reso rces. This is s pported by the C# $ sing$ statement which ma!es it so easy to a tomatically call $ispose. % st as I never call Close on a Stream, I never call Close on a database connection nless I specifically want to re se it later.

-ow should I es!a e te1t in ':# statements$ and e1 ress dates and times?
The answer here is not to p t the data in yo r &Q- statements at all, b t to se parameters. *very data provider worth sing provides a way of specifying parameters in &Q- statements, either named ,e.g. S>L>CT ,#&> -")& =>)=L> WH>"> %$/V%$/ or positional ,e.g. S>L>CT ,#&> -")& =>)=L> WH>"> %$/B/. &ome providers only s pport positional parameters, others only s pport named parameters, others s pport both. In practice it's not hard to wor! in a consistent way with either, by always sing sensible names and always specifying the command's parameters in the same order that they appear in the &Q- statement. Farameters are basically a mechanism for having a single &Q- statement which can ta!e different val es for some parts. Ho se a SIlComman. ,or the e" ivalent for yo r database provider/ to specify the " ery te't, the type of the command ,stored proced re, te't, etc/ and the parameters. Ho set the

command p with parameters once, and then yo can se the command several times, having set the parameter values p with the relevant data for each re" est. If yo 're sing a $ata#.apter to pdate yo r database, the parameter val es for the relevant command , pdate, insert or delete/ are filled in a tomatically, ass ming yo 've set the parameters p correctly. Farameters allow yo to write yo r &Q- witho t worrying abo t escaping val es or formatting dates and times etc. The database provider will do all that ,ass ming it even needs to/. Ho don't need to worry abo t &Q- in8ection attac!s 5 whatever parameter val e yo specify, it won't be sed as &Qitself. Farameters also ma!e life easier for the database 5 it can cache the " ery yo 've provided it so that it doesn't need to do as m ch wor! on f t re re" ests 5 it !nows everything apart from the act al parameter val es already. In short, parameters are wonderf l things, and sho ld be sed whenever yo 've got val es which may change for different re" ests. It even ma!es life easier if yo 're always going to se the same val e, if that val e is anything complicated ,li!e a string which may re" ire escaping, or a date and time which re" ires formatting/. For more information abo t sing parameters in database access, see the doc mentation for whichever database provider yo 're sing. The command type for yo r provider is li!ely to have a =arameters property which is a good starting point for finding o t more.

'eneral Questions -ow !an I rote!t my !ode against de!om ilation?


;any people have intellect al property concerns abo t .)*T, beca se it's easy to decompile I- into C# or 01.)*T, and the code prod ced is often remar!ably similar to the original so rce. Fersonally I feel that most of the time these concerns are misplaced. If yo r application becomes s fficiently pop lar that people are decompiling it, chances are yo 're ma!ing significant money from it anyway. If yo 're worried abo t yo r algorithsm themselves being poached, I believe that the overall design of an application or architect re is s ally more val able than a specific algorithm. If yo 're concerned abo t the sec rity of private !eys ,or whatever/ which are in yo r code, yo 're relying on sec rity thro gh obsc rity to start with, which is never a good idea. 0alid I- can always be decompiled to some e'tent, and modifying it so that it's no longer the !ind of I- which is $nat rally$ prod ced by the C# or 01.)*T compilers is li!ely to have a negative performance impact as the %IT will have been tailored towards the o tp t of those compilers. 3owever, yo can go a long way by sing an obf scator. Dbf scators change the names in code ,where possible/ so that l mps of code become a lot less meaningf l. For most s fficiently large apps, I believe this to be $good eno gh$ protection as nderstanding a large app with no so rce doc mentation is hard eno gh originally, let alone with mangled names. Dne possible e'ception to this is licence5handling code 5 if someone can wor! o t which part of yo r code is responsible for chec!ing that the installation is licensed, it may well be simple for them to disable it. Df co rse, with a large program with type names which are no longer readable, it may not always be easy to do this in the first place...

.emote&oft's lin!er ,see an earlier " estion/ provides more protection than a normal obf scator, as the I- is no longer present. ,This is in contrst to ngen, which precompiles the code b t still maintains the I-./ )ote that even this is only going to increase the protection rather than giving absolute protection tho gh 5 if someone has yo r code and can r n it, they can wor! o t how it does what it does, given eno gh time and patience. This has always been tr e, and gives one of the benefits of server5side code, where the ser never act ally has yo r code at all, only the res lts of specific re" ests etc. There are many obf scators aro nd, some free and some commercial. 0&.)*T =77B comes with the comm nity version of +otf scator. &ee the .)*T tools list on ;&+) for other options. I don't have any e'perience of +otf scator or any other .)*T obf scators.

9enera.Quest%ons :. 8oes "2 support mu.t%p.e-%n'er%tan$e( No use interfaces instead. 2. &'en -ou %n'er%t a prote$ted $.ass-.e)e. )ar%a5.e1 w'o %s %t a)a%.a5.e to( %lasses in the same namespace. ;. Are pr%)ate $.ass-.e)e. )ar%a5.es %n'er%ted( Jes $ut they are not accessi$le. Althou!h they are not #isi$le or accessi$le #ia the class interface they are inherited. <. 8es$r%5e t'e a$$ess%5%.%t- mod%*%er Mprote$ted %nterna.N. "t is a#aila$le to deri#ed classes and classes within the same Assem$ly Eand naturally from the $ase class itWs declared inF. :. To do: %onfirm the Lwithin the same assem$lyM portion.

=. "2 pro)%des a de*au.t $.ass $onstru$tor *or me. # de$%de to wr%te a $onstru$tor t'at takes a str%n, as a parameter1 5ut want to keep t'e $onstru$tor t'at 'as no parameter. 6ow man- $onstru$tors s'ou.d # wr%te( Two. &nce you write at least one constructor %/ cancels the free$ie constructor and now you ha#e to write one yourself e#en if thereWs no implementation in it. >. &'atOs t'e top .NET $.ass t'at e)er-t'%n, %s der%)ed *rom( 2ystem.&$7ect. @. :. answer the Nuestion. &'at does t'e term %mmuta5.e mean(

A. &'atOs t'e d%**eren$e 5etween 0-stem.0tr%n, and 0-stem.0tr%n,?u%.der $.asses( 2ystem.2trin! is immuta$le. 2ystem.2trin!Cuilder was desi!ned with the purpose of ha#in! a muta$le strin! where a #ariety of operations can $e performed. B. &'atOs t'e ad)anta,e o* us%n, 0-stem.Te4t.0tr%n,?u%.der o)er 0-stem.0tr%n,( 2trin!Cuilder is more efficient in cases where there is a lar!e amount of strin! manipulation. 2trin!s are immuta$le so each time itWs $ein! operated on a new instance is created. :0. "an -ou store mu.t%p.e data t-pes %n 0-stem.Arra-( No. ::. &'atOs t'e d%**eren$e 5etween t'e 0-stem.Arra-."op-ToCD and 0-stem.Arra-.".oneCD( The first one performs a deep copy of the array the second one is shallow. :. To do: impro#e the answer.

:2. 6ow $an -ou sort t'e e.ements o* t'e arra- %n des$end%n, order( Cy callin! 2ortEF and then .e#erseEF methods. :;. &'atOs t'e .NET $.ass t'at a..ows t'e retr%e)a. o* a data e.ement us%n, a un%Lue ke-( ?ashTa$le. :<. &'at $.ass %s underneat' t'e 0ortedL%st $.ass( A sorted ?ashTa$le. :=. &%.. t'e finally 5.o$k ,et e4e$uted %* an e4$ept%on 'as not o$$urred( Jes. :>. &'atOs t'e "2 eLu%)a.ent o* "EE $at$' CPD1 w'%$' was a $at$'-a.. statement *or an- poss%5.e e4$ept%on( A catch $lock that catches the e'ception of type 2ystem.E'ception. Jou can also omit the parameter data type in this case and 7ust write catch XY. 1. To do: Cad Nuestion. .e)word.

:@. "an mu.t%p.e $at$' 5.o$ks 5e e4e$uted( No. &nce the proper catch code fires off the control is transferred to the finally $lock Eif there are anyF and then whate#er follows the finally $lock. :A. E4p.a%n t'e t'ree ser)%$es mode. $ommon.- know as a t'ree-t%er app.%$at%on. 1resentation EH"F $usiness Elo!ic and underlyin! codeF and data Efrom stora!e or other sourcesF. :B. &'at %s t'e ro.e o* t'e 8ata/eader $.ass %n A8B.NET $onne$t%ons( "t returns a read)only dataset from the data source when the command is e'ecuted. :. To do: "mpro#e the answer.

".ass Quest%ons 20. 6ow do -ou %n'er%t *rom a $.ass %n "2( 1lace a colon and then the name of the $ase class. 2:. "an -ou pre)ent -our $.ass *rom 5e%n, %n'er%ted 5- anot'er $.ass( Jes. The keyword LsealedM will pre#ent the class from $ein! inherited. 22. "an -ou a..ow a $.ass to 5e %n'er%ted1 5ut pre)ent t'e met'od *rom 5e%n, o)er-r%dden( Jes. Just lea#e the class pu$lic and make the method sealed. 2;. &'atOs an a5stra$t $.ass( A class that cannot $e instantiated. An a$stract class is a class that must $e inherited and ha#e the methods o#erridden. An a$stract class is essentially a $lueprint for a class without any implementation. 2<. &'en do -ou a5so.ute.- 'a)e to de$.are a $.ass as a5stra$t( :. 5hen at least one of the methods in the class is a$stract.

2. 5hen the class itself is inherited from an a$stract class $ut not all $ase a$stract methods ha#e $een o#erridden.

2=. &'atOs an %nter*a$e $.ass( "tWs an a$stract class with pu$lic a$stract methods all of which must $e implemented in the inherited classes. 2>. &'- $anOt -ou spe$%*- t'e a$$ess%5%.%t- mod%*%er *or met'ods %ns%de t'e %nter*a$e( They all must $e pu$lic. Therefore to pre#ent you from !ettin! the false impression that you ha#e any freedom of choice you are not allowed to specify any accessi$ility itWs pu$lic $y default. :. To do: %lean up this answer.

2@. "an -ou %n'er%t mu.t%p.e %nter*a$es( Jes why not. :. To do: Need a $etter answer.

2A. And %* t'e- 'a)e $on*.%$t%n, met'od names( "tWs up to you to implement the method inside your own class so implementation is left entirely up to you. This mi!ht cause a pro$lem on a hi!her)le#el scale if similarly named methods from different interfaces e'pect different data $ut as far as compiler cares youWre okay. 2B. &'atOs t'e d%**eren$e 5etween an %nter*a$e and a5stra$t $.ass( "n an interface class all methods must $e a$stract. "n an a$stract class some methods can $e concrete. "n an interface class no accessi$ility modifiers are allowed which is ok in an a$stract class. ;0. &'at %s t'e d%**eren$e 5etween a 0tru$t and a ".ass( 2tructs are #alue)type #aria$les and are thus sa#ed on the stack )U additional o#erhead $ut faster retrie#al. Another difference is that structs %ANN&T inherit. ENuestions courtesy of EyalF Aet'od and Fropert- Quest%ons ;:. &'atOs t'e %mp.%$%t name o* t'e parameter t'at ,ets passed %nto t'e set met'odJpropert- o* a $.ass( #alue. The data type of the value parameter is defined $y whate#er data type the property is declared as. ;2. &'at does t'e ke-word M)%rtua.N de$.are *or a met'od or propert-( The method or property can $e o#erridden. ;;. 6ow %s met'od o)err%d%n, d%**erent *rom met'od o)er.oad%n,( 5hen o#erridin! a method you chan!e the $eha#ior of the method for the deri#ed class. &#erloadin! a method simply in#ol#es ha#in! another method with the same name within the class. ;<. "an -ou de$.are an o)err%de met'od to 5e stat%$ %* t'e or%,%na. met'od %s non-stat%$( No. The si!nature of the #irtual method must remain the same only the keyword #irtual is chan!ed to keyword o#erride. :. To do: .e)word the answer for $etter clarity.

;=. "an -ou o)err%de pr%)ate )%rtua. met'ods( No. 1ri#ate methods are not accessi$le outside the class. :. Br%,%na. answer: No moreo#er you cannot access pri#ate methods in inherited classes ha#e to $e protected in the $ase class to allow any sort of access.

2.

To do: %an a pri#ate method e#en $e declared a #irtual4

;>. &'at are t'e d%**erent wa-s a met'od $an 5e o)er.oaded( (ifferent parameter data types different num$er of parameters different order of parameters. ;@. #* a 5ase $.ass 'as a num5er o* o)er.oaded $onstru$tors1 and an %n'er%ted $.ass 'as a num5er o* o)er.oaded $onstru$torsQ $an -ou en*or$e a $a.. *rom an %n'er%ted $onstru$tor to a spe$%*%$ 5ase $onstru$tor( Jes 7ust place a colon and then keyword $ase Eparameter list to in#oke the appropriate constructorF in the o#erloaded constructor definition inside the inherited class. :. To do: Nuestion is to comple'. "t can $e stated $etter.

;A. &'- %s %t a 5ad %dea to t'row -our own e4$ept%ons( 5ell if at that point you know that an error has occurred then why not write the proper code to handle that error instead of passin! a new E'ception o$7ect to the catch $lock4 Throwin! your own e'ceptions si!nifies some desi!n flaws in the pro7ect. ;B. &'atOs a de.e,ate( A dele!ate o$7ect encapsulates a reference to a method. <0. &'atOs a mu.t%$ast de.e,ate( "tWs a dele!ate that points to and e#entually fires off se#eral methods. :. Assem5.- Quest%ons <:. 6ow %s t'e 8LL 6e.. pro5.em so.)ed %n .NET( Assem$ly #ersionin! allows the application to specify not only the li$rary it needs to run Ewhich was a#aila$le under 5in;2F $ut also the #ersion of the assem$ly. <2. &'at are t'e wa-s to dep.o- an assem5.-( An M2" installer a %AC archi#e and *%&1J command. <;. &'at %s a sate..%te assem5.-( 5hen you write a multilin!ual or multi)cultural application in .NET and want to distri$ute the core application separately from the locali3ed modules the locali3ed assem$lies that modify the core application are called satellite assem$lies. <<. &'at namespa$es are ne$essar- to $reate a .o$a.%;ed app.%$at%on( 2ystem.8lo$ali3ation and 2ystem..esources. >AL 8o$umentat%on Quest%ons <=. &'atOs t'e d%**eren$e 5etween JJ $omments1 JR RJ $omments and JJJ $omments( 2in!le)line comments multi)line comments and *M- documentation comments. To do: Need a $etter answer.

<>. 6ow do -ou ,enerate do$umentat%on *rom t'e "2 *%.e $ommented proper.- w%t' a $ommand-.%ne $omp%.er( %ompile it with the /doc switch. JO.&'at %s t'e d%**eren$e 5etween and XML documentation tag? Sin!le line co.e e<ample an. multipleGline co.e e<ample. 1. To do: Cad Nuestion <A. #s >AL $ase-sens%t%)e( Jes. 8e5u,,%n, and Test%n, Quest%ons <B. &'at de5u,,%n, too.s $ome w%t' t'e .NET 08=( :. %or(C8 Z command)line de$u!!er. To use %or($! you must compile the ori!inal %/ file usin! the ,de$u! switch. 2. ($!%-. Z !raphic de$u!!er. Gisual 2tudio .NET uses the ($!%-..

=0. &'at does t'e MT'%sN w%ndow s'ow %n t'e de5u,,er( "t points to the o$7ect thatWs pointed to $y this reference. &$7ectWs instance data is shown. :. To do: Need a $etter answer.

=:. &'at does assertCD met'od do( "n de$u! compilation assert takes in a Coolean condition as a parameter and shows the error dialo! if the condition is false. The pro!ram proceeds without any interruption if the condition is true. =2. &'atOs t'e d%**eren$e 5etween t'e 8e5u, $.ass and Tra$e $.ass( (ocumentation looks the same. Hse (e$u! class for de$u! $uilds use Trace class for $oth de$u! and release $uilds. =;. &'- are t'ere *%)e tra$%n, .e)e.s %n 0-stem.8%a,nost%$s.Tra$e0w%t$'er( The tracin! dumps can $e Nuite #er$ose. For applications that are constantly runnin! you run the risk of o#erloadin! the machine and the hard dri#e. Fi#e le#els ran!e from None to Ger$ose allowin! you to fine)tune the tracin! acti#ities. =<. &'ere %s t'e output o* Te4t&r%terTra$eL%stener red%re$ted( To the %onsole or a te't file dependin! on the parameter passed to the constructor. ==. 6ow do -ou de5u, an A0F.NET &e5 app.%$at%on( Attach the aspnetOwp.e'e process to the ($!%lr de$u!!er. =>. &'at are t'ree test $ases -ou s'ou.d ,o t'rou,' %n un%t test%n,( :. 1ositi#e test cases Ecorrect data correct outputF.

2. ;.

Ne!ati#e test cases E$roken or missin! data proper handlin!F. E'ception test cases Ee'ceptions are thrown and cau!ht properlyF. a "2 app.%$at%on(

=@. "an -ou $'an,e t'e )a.ue o* a )ar%a5.e w'%.e de5u,,%n, Jes. "f you are de$u!!in! #ia Gisual 2tudio.NET 7ust !o to "mmediate window. A8B.NET and 8ata5ase Quest%ons

=A. &'at are ad)anta,es and d%sad)anta,es o* A%$roso*t-pro)%ded data pro)%der $.asses %n A8B.NET( 2Q-2er#er.NET data pro#ider is hi!h)speed and ro$ust $ut reNuires 2Q- 2er#er license purchased from Microsoft. &-E)(C.NET is uni#ersal for accessin! other sources like &racle (C2 Microsoft Access and "nformi'. &-E) (C.NET is a .NET layer on top of the &-E layer so itWs not as fastest and efficient as 2Nl2er#er.NET. =B. &'at %s t'e w%.d$ard $'ara$ter %n 0QL( -etWs say you want to Nuery data$ase with -"9E for all employees whose name starts with -a. The wildcard character is [ the proper Nuery with -"9E would in#ol#e \-a[W. >0. E4p.a%n A"#8 ru.e o* t'um5 *or transa$t%ons. A transaction must $e+ :. Atomic ) it is one unit of work and does not dependent on pre#ious and followin! transactions.

2. %onsistent ) data is either committed or roll $ack no Lin)$etweenM case where somethin! has $een updated and somethin! hasnWt. ;. <. "solated ) no transaction sees the intermediate results of the current transactionF. (ura$le ) the #alues persist if the data had $een committed e#en if the system crashes ri!ht after.

>:. &'at $onne$t%ons does A%$roso*t 0QL 0er)er support( 5indows Authentication E#ia Acti#e (irectoryF and 2Q- 2er#er authentication E#ia Microsoft 2Q- 2er#er username and passwordF. >2. &'%$' one %s trusted and w'%$' one %s untrusted( 5indows Authentication is trusted $ecause the username and password are checked with the Acti#e (irectory the 2Q- 2er#er authentication is untrusted since 2Q- 2er#er is the only #erifier participatin! in the transaction. :. To do: ask the Nuestion $etter.

>;. &'- wou.d -ou use untrusted )er%*%$a%on( 5e$ 2er#ices mi!ht use it as well as non)5indows applications. :. To do: answer $etter.

><. &'at does t'e Initial Catalog parameter de*%ne %n t'e $onne$t%on str%n,( The data$ase name to connect to.

>=. &'at %s t'e data pro)%der name to $onne$t to an A$$ess data5ase( Microsoft.Access. >>. &'at does t'e Dispose met'od do w%t' t'e $onne$t%on o5:e$t( (eletes it from the memory. :. To do: answer $etter. The current answer is not entirely correct.

>@. &'at %s a pre-reLu%s%te *or $onne$t%on poo.%n,( Multiple processes must a!ree that they will share the same connection where e#ery parameter is the same includin! the security settin!s. The connection strin! must $e identical.

+eference bw Abstract and Interface< In the Db8ect orient design Interface is nothing li!e a Class witho t having the implementation, Interface defa lt access specifies is p blic not s al li!e a class representation. Interface can have method, properties and events. The advantage interface provides is high level abstract of how the implementation is done. In the design prospective interface no need to !now how the implementation and where the implementation is happened. For C22 world interface is nothing b t all method in that partic lar class is having p re virt al f nctions. Interface methods m st need to implement when the class is derived from the interface. In any thing is not implemented in the class level what ever is there in interface compiler provides the error notification to the developer. The I;- +esign notation the Interface loo!s li!e this< In this fig re &hape is the interface having the Area ,/ method witho t having the implementation. In that Circle, s" are, and rectangle class having vario s val es and varies implementation of the area based on that class, in this scenarios interface with implementation class will help. The highlight of the interface is< P Interface sho ld not have any implementation. P Interface can not create any instance. P Interface sho ld provide high level abstraction from the implementation. P Interface can have m ltiple inheritances. P +efa lt access level of the interface is p blic.

Abstract class A class is said to be a abstract class it sho ld have at least one ore more abstract methods and some of the method having the implementation also in that case that type of class is called abstract class. The re" irement of abstract class, if the designer things the common implementation we can p t in abstract class instead of implementing the all the derived class.

The highlight of the Abstract class is< P Abstract class sho ld have at least one or more method sho ld not have any implementation. P Instance can not be created for the abstract class. P Common implementation will implemented in the abstract base class ,A1C/ The I;- sage notation of Abstract class loo!s li!e this< In the case of the A1C, Jet 1alance,/ method is very common to both saving as well as c rrent acco nt in that case, instead implementing Jet 1alance,/ we will implement in base class and cons me in derive class. 1 t in the case of print 1alance ,/ is abstract method that m st need to implement in the derived classes to get there own implementation.

& mmary 1ased on the seage we have to choose interface 9 Abstract classes. 6. !hat is datagrid, The +ataJrid #eb server control is a powerf l tool for displaying information from a data so rce. It is easy to seG yo can display editable data in a professional5loo!ing grid by setting only a few properties. At the same time, the grid has a sophisticated ob8ect model that provides yo with great fle'ibility in how yo display the data. =. !hat-s the difference et"een the #ystem.!e ..+.!e Controls.%ata'rid and and #ystem.!indo"s.Forms.%ata'rid, The #eb II control does not inherently s pport master5 detail data str ct res. As with other #eb server controls, it does not s pport two5way data binding. If yo want to pdate data, yo m st write code to do this yo rself. Ho can only edit one row at a time. It does not inherently s pport sorting, altho gh it raises events yo can handle in order to sort the grid contents. Ho can bind the #eb Forms +ataJrid to any ob8ect that s pports the I*n merable interface. The #eb Forms +ataJrid control s pports paging. It is easy to c stomi:e the appearance and layo t of the #eb Forms +ataJrid control as compared to the #indows Forms one. B. /o" do you customi0e the column content inside the datagrid, If yo want to c stomi:e the content of a col mn, ma!e the col mn a template col mn. Template col mns wor! li!e item templates in the +ata-ist or .epeater control, e'cept that yo are defining the layo t of a col mn rather than a row. @. /o" do you apply specific formatting to the data inside the cells, Ho cannot specify formatting for col mns generated when the gridQs A toJenerateCol mns property is set to tr e, only for bo nd or template col mns. To format, set the col mnQs +ataFormat&tring property to a string5formatting e'pression s itable for the data type of the data yo are formatting. A. /o" do you hide the columns, Dne way to have col mns appear dynamically is to create them at design time, and then to hide or show them as needed. Ho can do this by setting a col mnQs 0isible property. C. /o" do you display an edita le drop1do"n list, +isplaying a drop5down list re" ires a template col mn in the grid. Typically, the ItemTemplate contains a control s ch as a data5bo nd -abel control to show the c rrent val e of a field in the record. Ho then add a drop5down list to the *ditItemTemplate. In 0is al &t dio, yo can add a template col mn in the Froperty b ilder for the grid, and then se standard template editing to remove the defa lt Te't1o' control from the *ditItemTemplate and drag a +rop+own-ist control into it instead. Alternatively, yo can add the

template col mn in 3T;- view. After yo have created the template col mn with the drop5down list in it, there are two tas!s. The first is to pop late the list. The second is to preselect the appropriate item in the list R for e'ample, if a boo!Qs genre is set to Sfiction,T when the drop5 down list displays, yo often want SfictionT to be preselected. K. /o" do you chec2 "hether the ro" data has een changed, The definitive way to determine whether a row has been dirtied is to handle the changed event for the controls in a row. For e'ample, if yo r grid row contains a Te't1o' control, yo can respond to the controlQs Te'tChanged event. &imilarly, for chec! bo'es, yo can respond to a Chec!edChanged event. In the handler for these events, yo maintain a list of the rows to be pdated. Jenerally, the best strategy is to trac! the primary !eys of the affected rows. For e'ample, yo can maintain an Array-ist ob8ect that contains the primary !eys of the rows to pdate.

.NET deployment (uestions


6. !hat do you 2no" a out .NET assem lies, Assemblies are the smallest nits of versioning and deployment in the .)*T application. Assemblies are also the b ilding bloc!s for programs s ch as #eb services, #indows services, serviced components, and .)*T remoting applications. =. !hat-s the difference et"een private and shared assem ly, Frivate assembly is sed inside an application only and does not have to be identified by a strong name. &hared assembly can be sed by m ltiple applications and has to have a strong name. B. !hat-s a strong name, A strong name incl des the name of the assembly, version n mber, c lt re identity, and a p blic !ey to!en. @. /o" can you tell the application to loo2 for assem lies at the locations other than its o"n install, Ise the directive in the E;- .config file for a given application. Uprobing privateFathV$c<LmylibsG binLdeb gT 9W sho ld do the tric!. Dr yo can add additional search paths in the Froperties bo' of the deployed application. A. /o" can you de ug failed assem ly inds, Ise the Assembly 1inding -og 0iewer ,f slogvw.e'e/ to find o t the paths searched. C. !here are shared assem lies stored, Jlobal assembly cache. K. /o" can you create a strong name for a .NET assem ly, #ith the help of &trong )ame tool ,sn.e'e/. ?. !here-s glo al assem ly cache located on the system, Is ally C<LwinntLassembly or C<LwindowsLassembly. >. Can you have t"o files "ith the same file name in 'AC, Hes, remember that JAC is a very special folder, and while normally yo wo ld not be able to place two files with the same name into a #indows folder, JAC differentiates by version n mber as well, so itQs possible for ;yApp.dll and ;yApp.dll to co5e'ist in JAC if the first one is version 6.7.7.7 and the second one is 6.6.7.7. 67. #o let-s say + have an application that uses 3yApp.dll assem ly4 version 5.6.6.6. There is a security ug in that assem ly4 and + pu lish the patch4 issuing it under name 3yApp.dll 5.5.6.6. /o" do + tell the client applications that are already installed to start using this ne" 3yApp.dll, Ise p blisher policy. To config re a p blisher policy, se the p blisher policy

config ration file, which ses a format similar app .config file. 1 t nli!e the app .config file, a p blisher policy file needs to be compiled into an assembly and placed in the JAC. 66. !hat is delay signing, +elay signing allows yo to place a shared assembly in the JAC by signing the assembly with 8 st the p blic !ey. This allows the assembly to be signed with the private !ey at a later stage, when the development process is complete and the component or assembly is ready to be deployed. This process enables developers to wor! with shared assemblies as if they were strongly named, and it sec res the private !ey of the signat re from being accessed at different stages of development.

!indo"s code security (uestions


6. !hat-s the difference et"een code1 ased security and role1 ased security, !hich one is etter, Code sec rity is the approach of sing permissions and permission sets for a given code to r n. The admin, for e'ample, can disable r nning e'ec tables off the Internet or restrict access to corporate database to only few applications. .ole5based sec rity most of the time involves the code r nning with the privileges of the c rrent ser. This way the code cannot s pposedly do more harm than mess p a single ser acco nt. ThereQs no better, or 677X th mbs5 p approach, depending on the nat re of deployment, both code5based and role5based sec rity co ld be implemented to an e'tent. =. /o" can you "or2 "ith permissions from your .NET application, Ho can re" est permission to do something and yo can demand certain permissions from other apps. Ho can also ref se permissions so that yo r app is not inadvertently sed to destroy some data. 7. /o" can C# app re(uest minimum permissions, sing &ystem.&ec rity.FermissionsG Yassembly<File+ialogFermissionAttrib te,&ec rityAction..e" est;inim m, InrestrictedVtr e/Z @. !hat-s a code group, A code gro p is a set of assemblies that share a sec rity conte't. A. !hat-s the difference et"een authentication and authori0ation, A thentication happens first. Ho verify serQs identity based on credentials. A thori:ation is ma!ing s re the ser only gets access to the reso rces he has credentials for. C. !hat are the authentication modes in A#$.NET, )one, #indows, Forms and Fassport. K. Are the actual permissions for the application defined at run1time or compile1time, The C-. comp tes act al permissions at r ntime based on code gro p membership and the calling chain of the code.

A#$.NET (uestions4 part 8


A&F.)*T interview " estions, part 6 6. !hats an assem ly, Assemblies are the b ilding bloc!s of .)*T Framewor! applicationsG they form the f ndamental nit of deployment, version control, re se, activation scoping, and sec rity permissions. An assembly is a collection of types and reso rces that are b ilt to wor! together and form a logical nit of f nctionality. An assembly provides the common lang age r ntime with the

information it needs to be aware of type implementations. To the r ntime, a type does not e'ist o tside the conte't of an assembly. =. %escri e the difference et"een inline and code ehind 1 "hich is est in a loosely coupled solution, A&F.)*T s pports two modes of page development< Fage logic code that is written inside Uscript r natVserverW bloc!s within an .asp' file and dynamically compiled the first time the page is re" ested on the server. Fage logic code that is written within an e'ternal class that is compiled prior to deployment on a server and lin!ed $behind$ the .asp' file at r n time. B. E9plain "hat a diffgram is4 and a good use for one, A +iffJram is an E;- format that is sed to identify c rrent and original versions of data elements. The +ata&et ses the +iffJram format to load and persist its contents, and to seriali:e its contents for transport across a networ! connection. #hen a +ata&et is written as a +iffJram, it pop lates the +iffJram with all the necessary information to acc rately recreate the contents, tho gh not the schema, of the +ata&et, incl ding col mn val es from both the Driginal and C rrent row versions, row error information, and row order. @. !here "ould you use an i/TT$3odule4 and "hat are the limitations of anyapproach you might ta2e in implementing one, Dne of A&F.)*TQs most sef l feat res is the e'tensibility of the 3TTF pipeline, the path that data ta!es between client and server. Ho can se them to e'tend yo r A&F.)*T applications by adding pre5 and post5processing to each 3TTF re" est coming into yo r application. For e'ample, if yo wanted c stom a thentication facilities for yo r application, the best techni" e wo ld be to intercept the re" est when it comes in and process the re" est in a c stom 3TTF mod le. A. !hat are the disadvantages of vie"state:"hat are the enefits, C. %escri e session handling in a "e farm4 ho" does it "or2 and "hat are the limits, K. /o" "ould you get A#$.NET running in Apache "e servers 1 "hy "ould you even do this, ?. !hats 3#+*4 and "hy should my developers need an appreciation of it if at all, >. +n "hat order do the events of an A#$; page e9ecute. As a developer is it important to undertsand these events, *very Fage ob8ect ,which yo r .asp' page is/ has nine events, most of which yo will not have to worry abo t in yo r day to day dealings with A&F.)*T. The three that yo will deal with the most are< Fage[Init, Fage[-oad, Fage[Fre.ender. 56. !hich method do you invo2e on the %ataAdapter control to load your generated dataset "ith data, &ystem.+ata.Common.+ataAdapter.Fill,&ystem.+ata.+ata&et/G If my +ataAdapter is s"l+ataAdapter and my +ata&et is dsIsers then it is called this way< s"l+ataAdapter.Fill,dsIsers/G 66. ata in the .epeater control( 6=. !hich template must you provide4 in order to display data in a )epeater control, ItemTemplate 6B. /o" can you provide an alternating color scheme in a )epeater control, AlternatingItemTemplate -i!e the ItemTemplate element, b t rendered for every other row ,alternating items/ in the .epeater control. Ho can specify a different appearance for the AlternatingItemTemplate element by setting its style properties. 6@. !hat property must you set4 and "hat method must you call in your code4 in order to ind the data from some data source to the )epeater control,

Ho m st set the +ata;ember property which Jets or sets the specific table in the +ata&o rce to bind to the control and the +ata1ind method to bind data from a so rce to a server control. This method is commonly sed after retrieving a data set thro gh a database " ery. 6A. !hat ase class do all !e Forms inherit from, &ystem.#eb.II.Fage 6C. !hat method do you use to e9plicitly 2ill a user-s session, The Abandon method destroys all the ob8ects stored in a &ession ob8ect and releases their reso rces. If yo do not call the Abandon method e'plicitly, the server destroys these ob8ects when the session times o t. &ynta'< Session.Abandon 6K. /o" do you turn off coo2ies for one page in your site, Ise the Coo!ie.+iscard Froperty which Jets or sets the discard flag set by the server. #hen tr e, this property instr cts the client application not to save the Coo!ie on the serQs hard dis! when a session ends. 6?. !hich t"o properties are on every validation control, ControlTo0alidate \ *rror;essage properties 6>. !hat tags do you need to add "ithin the asp<datagrid tags to ind columns manually, =7. /o" do you create a permanent coo2ie, &etting the *'pires property to ;in0al e means that the Coo!ie never e'pires. =6. !hat tag do you use to add a hyperlin2 column to the %ata'rid, ==. !hat is the standard you use to "rap up a call to a !e service, =B. !hich method do you use to redirect the user to another page "ithout performing a round trip to the client, &erver.transfer,/ =@. !hat is the transport protocol you use to call a !e service, &DAF. Transport Frotocols< It is essential for the acceptance of #eb &ervices that they are based on established Internet infrastr ct re. This in fact imposes the sage of of the 3TTF, &;TF and FTF protocols based on the TCF9IF family of transports. ;essaging Frotocol< The format of messages e'changed between #eb &ervices clients and #eb &ervices sho ld be vendor ne tral and sho ld not carry details abo t the technology sed to implement the service. Also, the message format sho ld allow for e'tensions and different bindings to specific transport protocols. &DAF and ebE;- Transport are specifications which f lfill these re" irements. #e e'pect that the #BC E;- Frotocol #or!ing Jro p defines a s ccessor standard. =A. True or False< A !e service can only e "ritten in .NET. False. =C. !hat does !#%* stand for, #eb &ervices +escription -ang age =K. !hat property do you have to set to tell the grid "hich page to go to "hen using the $ager o =ect, =?. !here on the +nternet "ould you loo2 for !e services, I++I repositaries li!e ddi.microsoft.com, I1; I++I node, I++I .egistries in Joogle +irectory, enth siast sites li!e E;ethods.net. =>. !hat tags do you need to add "ithin the asp<datagrid tags to ind columns manually, Col mn tag and an A&F<databo nd tag. B7. !hich property on a Com o Bo9 do you set "ith a column name4 prior to setting the %ata#ource4 to display data in the com o o9, B6. /o" is a property designated as read1only, In 01.)*T< 78. =ublic "ea.)nly =roperty =roperty,ame #s "eturnType

77. +et \Xour =roperty %mplementation !oes in 'ere 7J. >n. +et >n. =roperty in C# public returntype =roperty,ame { !et{ //property implementation !oes 'ere } // $o not 1rite t'e set implementation } BA. !hich control "ould you use if you needed to ma2e sure the values in t"o different controls matched, Ise the Compare0alidator control to compare the val es of = different controls. BC. True or False< To test a !e service you must create a "indo"s application or !e application to consume this service, False. BK. /o" many classes can a single .NET %** contain, Inlimited.

6. %escri e the advantages of "riting a managed code application instead of unmanaged one. !hat-s involved in certain piece of code eing managed, The advantages incl de a tomatic garbage collection, memory management, s pport for versioning and sec rity. These advantages are provided thro gh .)*T FC- and C-., while with the nmanaged code similar capabilities had to be implemented thro gh third5party libraries or as a part of the application itself. =. Are C&3 o =ects managed or unmanaged, &ince CD; ob8ects were written before .)*T, apparently they are nmanaged. B. #o can a C&3 o =ect tal2 to a .NET o =ect, Hes, thro gh . ntime Callable #rapper ,.C#/ or FInvo!e. @. /o" do you generate an )C! from a C&3 o =ect, Ise the Type -ibrary Import tility shipped with &+]. tlbimp CD;ob8ect.dll 9o t<.)*Tob8ect.dll or reference the CD; library from 0is al &t dio in yo r pro8ect. A. + can-t import the C&3 o =ect that + have on my machine. +id yo write that ob8ect( Ho can only import yo r own ob8ects. If yo need to se a CD; component from another developer, yo sho ld obtain a Frimary Interop Assembly ,FIA/ from whoever a thored the original ob8ect. C. /o" do you call unmanaged methods from your .NET code through $+nvo2e, & pply a +llImport attrib te. +eclare the methods in yo r .)*T code as static extern. +o not implement the methods as they are implemented in yo r nmanaged code, yo Qre 8 st providing declarations for method signat res. K. Can you retrieve comple9 data types li2e structs from the $+nvo2e calls, Hes, 8 st ma!e s re yo re5declare that str ct, so that managed code !nows what to do with it. ?. + "ant to e9pose my .NET o =ects to C&3 o =ects. +s that possi le, Hes, b t few things sho ld be considered first. Classes sho ld implement interfaces e'plicitly. ;anaged types m st be p blic. ;ethods, properties, fields, and events that are e'posed to CD; m st be p blic. Types m st have a p blic defa lt constr ctor with no arg ments to be activated from CD;. Types cannot be abstract. >. Can you inherit a C&3 class in a .NET application, The .)*T Framewor! e'tends the CD; model for re sability by adding implementation inheritance. ;anaged types can derive directly or indirectly from a CD; coclassG more specifically, they can derive from the r ntime callable

wrapper generated by the r ntime. The derived type can e'pose all the method and properties of the CD; ob8ect as well as methods and properties implemented in managed code. The res lting ob8ect is partly implemented in managed code and partly implemented in nmanaged code. 67. #uppose + call a C&3 o =ect from a .NET applicaiton4 ut C&3 o =ect thro"s an error. !hat happens on the .NET end, CD; methods report errors by ret rning 3.*&I-TsG .)*T methods report them by throwing e'ceptions. The r ntime handles the transition between the two. *ach e'ception class in the .)*T Framewor! maps to an 3.*&I-T.

C&3:C&3> services and components in .NET


6. E9plain transaction atomicity. #e m st ens re that the entire transaction is either committed or rolled bac!. =. E9plain consistency. #e m st ens re that the system is always left at the correct state in case of the fail re or s ccess of a transaction. B. E9plain integrity. *ns re data integrity by protecting conc rrent transactions from seeing or being adversely affected by each otherQs partial and ncommitted res lts. @. E9plain dura ility. ;a!e s re that the system can ret rn to its original state in case of a fail re. A. E9plain o =ect pooling. #ith ob8ect pooling, CD;2 creates ob8ects and !eeps them in a pool, where they are ready to be sed when the ne't client ma!es a re" est. This improves the performance of a server application that hosts the ob8ects that are fre" ently sed b t are e'pensive to create. C. E9plain ?+T activation. The ob8ective of %IT activation is to minimi:e the amo nt of time for which an ob8ect lives and cons mes reso rces on the server. #ith %IT activation, the client can hold a reference to an ob8ect on the server for a long time, b t the server creates the ob8ect only when the client calls a method on the ob8ect. After the method call is completed, the ob8ect is freed and its memory is reclaimed. %IT activation enables applications to scale p as the n mber of sers increases. K. E9plain role1 ased security. In the role5based sec rity model, access to parts of an application are granted or denied based on the role to which the callers belong. A role defines which members of a #indows domain are allowed to wor! with what components, methods, or interfaces. ?. E9plain (ueued components. The " e ed components service enables yo to create components that can e'ec te asynchrono sly or in disconnected mode. Q e ed components ens re availability of a system even when one or more s b5systems are temporarily navailable. Consider a scenario where salespeople ta!e their laptop comp ters to the field and enter orders on the go. 1eca se they are in disconnected mode, these orders can be " e ed p in a message " e e. #hen salespeople connect bac! to the networ!, the orders can be retrieved from the message " e e and processed by the order processing components on the server. >. E9plain loosely coupled events. -oosely co pled events enable an ob8ect ,p blisher/ to p blish an event. Dther ob8ects ,s bscribers/ can s bscribe to an event. CD;2 does not re" ire p blishers or s bscribers to !now abo t each other. Therefore, loosely co pled events greatly simplify the programming model for distrib ted applications. 67. %efine scala ility. The application meets its re" irement for efficiency even if the n mber of sers increases. 66. %efine relia ility. The application generates correct and consistent information all the time. 6=. %efine availa ility. Isers can depend on sing the application when needed.

6B. %efine security. The application is never disr pted or compromised by the efforts of malicio s or ignorant sers. 6@. %efine managea ility. +eployment and maintenance of the application is as efficient and painless as possible. 6A. !hich namespace do the classes4 allo"ing you to support C&3 functionality4 are located, &ystem.*nterprise&ervices 6C. /o" do you ma2e a NET component tal2 to a C&3 component, To enable the comm nication between CD; and .)*T components, the .)*T Framewor! generates a CD; Callable #rapper ,CC#/. The CC# enables comm nication between the calling CD; code and the managed code. It also handles conversion between the data types, as well as other messages between the CD; types and the .)*T types.

.NET !indo"s services development (uestions


6. E9plain !indo"s service. Ho often need programs that r n contin o sly in the bac!gro nd. For e'ample, an email server is e'pected to listen contin o sly on a networ! port for incoming email messages, a print spooler is e'pected to listen contin o sly to print re" ests, and so on. =. !hat-s the .ni9 name for a !indo"s service e(uivalent, +aemon. B. #o asically a !indo"s service application is =ust another e9ecuta le, !hat-s different a out a !indo"s service as compared to a regular application, #indows services m st s pport the interface of the &ervice Control ;anager ,&C;/. A #indows service m st be installed in the #indows service database before it can be la nched. @. /o" is development of a !indo"s service different from a !indo"s Forms application, A #indows service typically does not have a ser interface, it s pports a set of commands and can have a JII thatQs b ilt later to allow for easier access to those commands. A. /o" do you give a !indo"s service specific permissions, #indows service always r ns nder someoneQs identity. Can be &ystem or Administrator acco nt, b t if yo want to restrict the behavior of a #indows service, the best bet is to create a new ser acco nt, assign and deny necessary privileges to that acco nt, and then associate the #indows service with that new acco nt. C. Can you share processes et"een !indo"s services, Hes. K. !here-s !indo"s service data ase located, 3]*H[-DCA-[;AC3I)*L&H&T*;LC rrentControl&etL&ervices ?. !hat does #C3 do, &C; is #indows &ervice Control ;anager. Its responsibilities are as follows< o Accepts re" ests to install and ninstall #indows services from the #indows service database. o To start #indows services either on system start p or re" ested by the ser. o To en merate installed #indows services. o To maintain stat s information for c rrently r nning #indows services. o To transmits control messages ,s ch as &tart, &top, Fa se, and Contin e/ to available #indows services. o To loc!9 nloc! #indows service database. >. vice on a bo'( Ise #indows &ervice Installer, do not go thro gh Add9.emove Frograms or ;&I file, as yo wo ld normally go with applications.

67. !hen developing a !indo"s service for .NET4 "hich namespace do you typically loo2 in for re(uired classes, &ystem.&erviceFrocess. The classes are &ervice1ase, &erviceFrocessInstaller, &erviceInstaller and &erviceController. 66. /o" do you handle #tart4 $ause4 Continue and #top calls from #C3 "ithin your application, 1y implementing Dn&tart, DnFa se, DnContin e and Dn&top methods. 6=. %escri e the start1up process for a !indo"s service. ;ain,/ is e'ec ted to create an instance of a #eb service, then . n,/ to la nch it, then Dn&tart,/ from within the instance is e'ec ted. 6B. + "ant to "rite a !indo"s service that cannot e paused4 only started and stopped. /o" do + accomplish that, &et CanFa seAndContin e attrib te to false. 6@. !hat application do you use to install a !indo"s service, install til.e'e 6A. + am trying to install my !indo"s service under Net"or2#ervice account4 ut 2eep getting an error. The -ocal&ervice and )etwor!&ervice acco nts are only available on #indows EF and #indows &erver =77B. These acco nts do not e'ist on #indows =777 or older operating systems. 6C. /o" can you see "hich services are running on a !indo"s o9, Admin Tools 5W Comp ter ;anagement 5W &ervices and Application 5W &ervices. Ho can also open the Comp ter ;anagement tool by right5clic!ing on ;y Comp ter and selecting ;anage from the pop p men . 6K. /o" do you start4 pause4 continue or stop a !indo"s service off the command line, net start &ervice)ame, net pa se &ervice)ame and so on. Also sc.e'e provides a command5line interface for #indows services. 0iew the D& doc mentation or proper boo! chapters on sing sc.e'e. 6?. Can + "rite an 33C snap1in for my !indo"s service, Hes, se classes from the &ystem.;anagement.Instr mentation namespace. Also see ;anaging Applications Ising #;I from .)*T Framewor! &+].

3icrosoft .NET Frame"or2 intervie" (uestions


6. #hat is .)*T Framewor!( =. Is .)*T a r ntime service or a development platform( Answer ItQs bothand act ally a lot more. ;icrosoft .)*T is a company5wide initiative. It incl des a new way of delivering software and services to b sinesses and cons mers. A part of ;icrosoft.)*T is the .)*T Framewor!s. The framewor!s is the first part of the ;&.)*T initiate to ship and it was given o t to attendees at the F+C in % ly. The .)*T framewor!s consists of two parts< the .)*T common lang age r ntime and the .)*T class library. These two components are pac!aged together into the .)*T Framewor!s &+] which will be available for free download from ;icrosoftQs ;&+) web site later this month. In addition, the &+] also incl des command5line compilers for C#, C22, %&cript, and 01. Ho se these compilers to b ild applications and components. These components re" ire the r ntime to e'ec te so this is a development platform. #hen 0is al &t dio.)*T ships, it will incl de the .)*T &+] and a JII editor, wi:ards, tools, and a slew of other things. 3owever, 0is al &t dio.)*T is )DT re" ired to b ild .)*T applications. B. )ew feat res of Framewor! 6.6 ( @. #hat is C-.( 3ow it will wor!( A. #hat is ;&I-, I-, CT&( C. #hat is %IT and how is wor!s K. #hat is strong name( A name that consists of an assemblyQs identityRits simple te't name, version n mber, and c lt re information ,if provided/Rstrengthened by a p blic !ey and a digital signat re generated over the assembly.

?. #hat is portable e'ec table ,F*/ The file format defining the str ct re that all e'ec table files ,*E*/ and +ynamic -in! -ibraries ,+--/ m st se to allow them to be loaded and e'ec ted by #indows. F* is derived from the ;icrosoft Common Db8ect File Format ,CDFF/. The *E* and +-- files created sing the .)*T Framewor! obey the F*9CDFF formats and also add additional header and data sections to the files that are only sed by the C-.. The specification for the F*9CDFF file formats is available at http<99www.microsoft.com9whdc9hwdev9hardware9pecoffdown.msp' >. #hich is the base class for .net Class library( Ans< system.ob8ect 67. #hat is *vent( +elegate, clear synta' for writing a event delegate// :ey1or.P.ele!ate.cs //
.ele!ate .eclaration .ele!ate 6oi. &y$ele!ate(int i);

FF. class =ro!ram F8. { F7. public static 6oi. &ain() FJ. { FK. Ta:es#$ele!ate(ne1 &y$ele!ate($ele!ate-unction)); FL. } FO. public static 6oi. Ta:es#$ele!ate(&y$ele!ate Some-unction) FM. { FN. Some-unction(8F); 85. } 8F. public static 6oi. $ele!ate-unction(int i) 88. { 87. System.Console.WriteLine("Calle. by .ele!ate 1it'number {5}."3 i); 8J. } } =A. ment +ataJrid in .)*T( 3ow wo ld yo ma!e a combo5bo' appear in one col mn of a +ataJrid( #hat are the ways to show data grid inside a data grid for a master details type of tables( =C. If we write any code for +ataJrid methods, what is the access specifier sed for that methods in the code behind file and why( =K. #hat is Application +omain( Application domains provide a nit of isolation for the common lang age r ntime. They are created and r n inside a process. Application domains are s ally created by a r ntime host, which is an application responsible for loading the r ntime into a process and e'ec ting ser code within an application domain. The r ntime host creates a process and a defa lt application domain, and r ns managed code inside it. . ntime hosts incl de A&F.)*T, ;icrosoft Internet *'plorer, and the #indows shell. =?. #hat is seriali:ation in .)*T( #hat are the ways to control seriali:ation( &eriali:ation can be defined as the process of storing the state of an ob8ect to a storage medi m. + ring this process, the p blic and private fields of the ob8ect and the name of the class, incl ding the assembly containing the class, are converted to a stream of bytes, which is then written to a data stream. #hen the ob8ect is s bse" ently deseriali:ed, an e'act clone of the original ob8ect is created. o 1inary seriali:ation preserves type fidelity, which is sef l for preserving the state of an ob8ect between different invocations of an application. For e'ample, yo can share an ob8ect between different applications by seriali:ing it to the clipboard. Ho can seriali:e an ob8ect to a stream, dis!, memory, over the networ!, and so forth. .emoting ses seriali:ation to pass ob8ects Sby val eT from one comp ter or application domain to another.

E;- seriali:ation seriali:es only p blic properties and fields and does not preserve type fidelity. This is sef l when yo want to provide or cons me data witho t restricting the application that ses the data. 1eca se E;- is an open standard, it is an attractive choice for sharing data across the #eb. &DAF is an open standard, which ma!es it an attractive choice. =>. #hat are the different a thentication modes in the .)*T environment( 75. Saut'entication mo.e="Windows|Forms|Passport|None"> 7F. Sforms name="name lo!in2rl="url 78. protection="All|None|Encryption|Validation 77. timeout="30 pat!="" > reIuireSSL/#true|$alse 7J. sli.in!><piration/#true|$alseTS 7K. cre.entials pass1or.-ormat="%lear|&'A(|)*+>S 7L. user name="username password="password""> 7O. S/cre.entialsT S/formsT 7M. Spassport re.irect2rl/"internal"/T
o S/aut'enticationT

9liW B>. #hat is the se of trace tility @7. #hat is different between Iser Control and #eb Control and C stom Control( @6. #hat is e'ception handling( #hen an e'ception occ rs, the system searches for the nearest catch cla se that can handle the e'ception, as determined by the r n5time type of the e'ception. First, the c rrent method is searched for a le'ically enclosing try statement, and the associated catch cla ses of the try statement are considered in order. If that fails, the method that called the c rrent method is searched for a le'ically enclosing try statement that encloses the point of the call to the c rrent method. This search contin es ntil a catch cla se is fo nd that can handle the c rrent e'ception, by naming an e'ception class that is of the same class, or a base class, of the r n5time type of the e'ception being thrown. A catch cla se that doesnQt name an e'ception class can handle any e'ception. Dnce a matching catch cla se is fo nd, the system prepares to transfer control to the first statement of the catch cla se. 1efore e'ec tion of the catch cla se begins, the system first e'ec tes, in order, any finally cla ses that were associated withtry statements more nested that than the one that ca ght the e'ception. *'ceptions that occ r d ring destr ctor e'ec tion are worthspecial mention. If an e'ception occ rs d ring destr ctor e'ec tion, and that e'ception is not ca ght, then the e'ec tion of that destr ctor is terminated and the destr ctor of the base class ,if any/ is called. If there is no base class ,as in the case of the ob8ect type/ or if there is no base class destr ctor, then the e'ception is discarded. @=. #hat is Assembly( Assemblies are the b ilding bloc!s of .)*T Framewor! applicationsG they form the f ndamental nit of deployment, version control, re se, activation scoping, and sec rity permissions. An assembly is a collection of types and reso rces that are b ilt to wor! together and form a logical nit of f nctionality. An assembly provides the common lang age r ntime withthe information it needs to be aware of type implementations. To the r ntime, a type does not e'ist o tside the conte't of an assembly. Assemblies are a f ndamental part of programming withthe .)*T Framewor!. An assembly performs the following f nctions< o It contains code that the common lang age r ntime e'ec tes. ;icrosoft intermediate lang age ,;&I-/ code in a portable e'ec table ,F*/ file will not be e'ec ted if it does not have an associated assembly manifest. )ote that each assembly can have only one entry point ,that is,+ll;ain,#in;ain, or;ain/.

o o

It forms asecurity oundary. An assembly is the nit at which permissions are re" ested and granted. It forms atype oundary. *very typeQs identity incl des the name of the assembly in which it resides. A type called ;yType loaded in the scope of one assembly is not the same as a type called ;yType loaded in the scope of another assembly. It forms areference scope oundary. The assemblyQs manifest contains assembly metadata that is sed for resolving types and satisfying reso rce re" ests. It specifies the types and reso rces that are e'posed o tside the assembly. The manifest also en merates other assemblies on which it depends. It forms aversion oundary. The assembly is the smallest versionable nit in the common lang age r ntimeG all types and reso rces in the same assembly are versioned as a nit. The assemblyQs manifest describes the version dependencies yo specify for any dependent assemblies. It forms a deployment nit. #hen an application starts, only the assemblies that the application initially calls m st be present. Dther assemblies, s ch as locali:ation reso rces or assemblies containing tility classes, can be retrieved on demand. This allows applications to be !ept simple and thin when first downloaded. It is the nit at which side5by5side e'ec tion is s pported. Assem lies can e static or dynamic. &tatic assemblies can incl de .)*T Framewor! types ,interfaces and classes/, as well as reso rces for the assembly ,bitmaps, %F*J files, reso rce files, and so on/. &tatic assemblies are stored on dis! in F* files. Ho can also se the .)*T Framewor! to create dynamic assemblies, which are r n directly from memory and are not saved to dis! before e'ec tion. Ho can save dynamic assemblies to dis! after they have e'ec ted. There are several ways to create assemblies. Ho can se development tools, s ch as 0is al &t dio .)*T, that yo have sed in the past to create .dll or .e'e files. Ho can se tools provided in the .)*T Framewor! &+] to create assemblies withmod les created in other development environments. Ho can also se common lang age r ntime AFIs, s ch as .eflection.*mit, to create dynamic assemblies.

@B. s of assemblies( Frivate, F blic9&hared, &atellite @@. #hat are &atellite Assemblies( 3ow yo will create this( 3ow will yo get the different lang age strings( &atellite assemblies are often sed to deploy lang age5specific reso rces for an application. These lang age5specific assemblies wor! in side5by5side e'ec tion beca se the application has a separate prod ct I+ for each lang age and installs satellite assemblies in a lang age5specific s bdirectory for each lang age. #hen ninstalling, the application removes only the satellite assemblies associated witha given lang age and .)*T Framewor! version. )o core .)*T Framewor! files are removed nless the last lang age for that .)*T Framewor! version is being removed. For e'ample, *nglish and %apanese editions of the .)*T Framewor! version 6.6 share the same core files. The %apanese .)*T Framewor! version 6.6 adds satellite assemblies withlocali:ed reso rces in a L8a s bdirectory. An application that s pports the .)*T Framewor! version 6.6, regardless of its lang age, always ses the same core r ntime files. @A. 3ow will yo load dynamic assembly( 3ow will create assemblies at r n time( @C. #hat is Assembly manifest( what all details the assembly manifest will contain. *very assembly, whether static or dynamic, contains a collection of data that describes how the elements in the assembly relate to each other. The assembly manifest contains this assembly metadata. An assembly manifest contains all the metadata needed to specify the assemblyQs version

re" irements and sec rity identity, and all metadata needed to define the scope of the assembly and resolve references to reso rces and classes. The assembly manifest can be stored in either a F* file ,an .e'e or .dll/ with;icrosoft intermediate lang age ,;&I-/ code or in a standalone F* file that contains only assembly manifest information. It contains Assembly name, 0ersion n mber, C lt re, &trong name information, -ist of all files in the assembly, Type reference information, Information on referenced assemblies. @K. #hat are the contents of assembly( In general, a static assembly can consist of fo r elements< o The assembly manifest, which contains assembly metadata. o Type metadata. o ;icrosoft intermediate lang age ,;&I-/ code that implements the types. o A set of reso rces. @?. +ifference between assembly manifest \ metadata assembly manifest 5An integral part of every assembly that renders the assembly self5describing. The assembly manifest contains the assemblyQs metadata. The manifest establishes the assembly identity, specifies the files that ma!e p the assembly implementation, specifies the types and reso rces that ma!e p the assembly, itemi:es the compile5time dependencies on other assemblies, and specifies the set of permissions re" ired for the assembly to r n properly. This information is sed at r n time to resolve references, enforce version binding policy, and validate the integrity of loaded assemblies. The self5describing nat re of assemblies also helps ma!es :ero5impact install and ECDFH deployment feasible. metadata 5Information that describes every element managed by the common lang age r ntime< an assembly, loadable file, type, method, and so on. This can incl de information re" ired for deb gging and garbage collection, as well as sec rity attrib tes, marshaling data, e'tended class and member definitions, version binding, and other information re" ired by the r ntime. @>. #hat is Jlobal Assembly Cache ,JAC/ and what is the p rpose of it( ,3ow to ma!e an assembly to p blic( &teps/ *ach comp ter where the common lang age r ntime is installed has a machine5 wide code cache called the global assembly cache. The global assembly cache stores assemblies specifically designated to be shared by several applications on the comp ter. Ho sho ld share assemblies by installing them into the global assembly cache only when yo need to. A7. If I have more than one version of one assemblies, then howQll I se old version ,how9where to specify version n mber(/in my application( A6. 3ow to find methods of a assembly file ,not sing I-+A&;/ .eflection A=. 0al e type \ data types difference. *'ample from .)*T. AB. Integer \ str ct are val e types or reference types in .)*T( A@. #hat is Jarbage Collection in .)et( Jarbage collection process( The process of transitively tracing thro gh all pointers to actively sed ob8ects in order to locate all ob8ects that can be referenced, and then arranging to re se any heap memory that was not fo nd d ring this trace. The common lang age r ntime garbage collector also compacts the memory that is in se to red ce the wor!ing space needed for the heap. AA. .eadonly vs. const( Aconstfield can only be initiali:ed at the declaration of the field. Areadonlyfield can be initiali:ed either at the declaration or in a constr ctor. Therefore,readonlyfields can have different val es depending on the constr ctor sed. Also, while aconstfield is a compile5time constant, thereadonlyfield can be sed for r ntime constants, as in the following e'ample< p blic static readonly int l6 V , int/ +ateTime.)ow.Tic!sG AC.
F.

8. 7.

U . ^ &ystem.Attrib te < ;yAttrib te p blic attrib te.,W U ^ p blic this.myval eV$myval eG$ myval e/ ;yAttrib te,bool constr ctors,W J. //$eclarin! properties K. public bool &y=roperty L. { O. !et {return t'is.my6alue;} M. set {t'is.my6alue / 6alue;} N. } ion to get access to c stom attrib tes. class ;ainClass ^ p blic static void ;ain,/ ^ &ystem..eflection.;emberInfo info V typeof,;yClass/G ob8ectYZ attrib tes V info.JetC stomAttrib tes,/G for ,int i V 7G i U attrib tes.-engthG i 22/ ^ &ystem.Console.#rite-ine,attrib tesYiZ/G _ _ _

F5.

=. C22 \ C# differences B. #hat is the managed and nmanaged code in .net( The .)*T Framewor! provides a r n5time environment called the Common -ang age . ntime, which manages the e'ec tion of code and provides services that ma!e the development process easier. Compilers and tools e'pose the r ntimeQs f nctionality and enable yo to write code that benefits from this managed e'ec tion environment. Code that yo develop witha lang age compiler that targets the r ntime is calledmanaged codeG itbenefits from feat res s ch as cross5lang age integration, cross5lang age e'ception handling, enhanced sec rity, versioning and deployment s pport, a simplified model for component interaction, and deb gging and profiling services. @. 3ow do yo create threading in .)*T( #hat is the namespace for that( A. sing directive vs sing statement Ho create an instance in a singstatement to ens re that+ispose is called on the ob8ect when the singstatement is e'ited. A sing statement can be e'ited either when the end of the singstatement is reached or if, for e'ample, an e'ception is thrown and control leaves the statement bloc! before the end of the statement. The sing directive has two ses.
o o

Create an alias for a namespace ,a sing alias/. Fermit the se of types in a namespace, s ch that, yo do not have to " alify the se of a type in that namespace ,a singdirective/.

AK. +escribe the ;anaged *'ec tion Frocess A?. #hat is Active +irectory( #hat is the namespace sed to access the ;icrosoft Active +irectories( A>. Interop &ervices(

C7. #hat is .C# ,. n time Callable #rappers/( The common lang age r ntime e'poses CD; ob8ects thro gh a pro'y called the r ntime callable wrapper ,.C#/. Altho gh the .C# appears to be an ordinary ob8ect to .)*T clients, its primary f nction is to marshal calls between a .)*T client and a CD; ob8ect. C6. #hat is CC# ,CD; Callable #rapper/ A pro'y ob8ect generated by the common lang age r ntime so that e'isting CD; applications can se managed classes, incl ding .)*T Framewor! classes, transparently. C=. 3ow does yo handle this CD; components developed in other programming lang ages in .)*T( CB. 3ow will yo register com2 services( C@. #hat is se of Conte'tItil class( Conte'tItil is the preferred class to se for obtaining CD;2 conte't information. CA. #hat is the new three feat res of CD;2 services, which are not there in CD; ,;T&/ CC. Is the CD; architect re same as .)et architect re( #hat is the difference between them ,if at all there is/( For more " estions and answers, visit &anthosh

.NET )emoting (uestions and ans"ers


To satisfy pop lar demand, hereQs some basics of the .)*T .emoting. 6. !hat-s a !indo"s process, ItQs an application thatQs r nning and had been allocated memory. =. !hat-s typical a out a !indo"s process in regards to memory allocation, *ach process is allocated its own bloc! of available .A; space, no process can access another processQ code or data. If the process crashes, it dies alone witho t ta!ing the entire D& or a b nch of other applications down. B. !hy do you call it a process, !hat-s different et"een process and application in .NET4 not common computer usage4 terminology, A process is an instance of a r nning application. An application is an e'ec table on the hard drive or networ!. There can be n mero s processes la nched of the same application ,A copies of #ord r nning/, b t 6 process can r n 8 st 6 application. @. !hat distri uted process frame"or2s outside .NET do you 2no", +istrib ted Comp ting *nvironment9.emote Froced re Calls ,+*C9.FC/, ;icrosoft +istrib ted Component Db8ect ;odel ,+CD;/, Common Db8ect .e" est 1ro!er Architect re ,CD.1A/, and %ava .emote ;ethod Invocation ,.;I/. A. !hat are possi le implementations of distri uted applications in .NET, .)*T .emoting and A&F.)*T #eb &ervices. If we tal! abo t the Framewor! Class -ibrary, noteworthy classes are in &ystem.. ntime..emoting and &ystem.#eb.&ervices. C. !hen "ould you use .NET )emoting and "hen !e services, Ise remoting for more efficient e'change of information when yo control both ends of the application. Ise #eb services for open5protocol5based information e'change when yo are 8 st a client or a server with the other end belonging to someone else. K. !hat-s a pro9y of the server o =ect in .NET )emoting, ItQs a fa!e copy of the server ob8ect that resides on the client side and behaves as if it was the server. It handles the comm nication between real server ob8ect and the client ob8ect. This process is also !nown as marshaling.

?. !hat are remota le o =ects in .NET )emoting, .emotable ob8ects are the ob8ects that can be marshaled across the application domains. Ho can marshal by val e, where a deep copy of the ob8ect is created and then passed to the receiver. Ho can also marshal by reference, where 8 st a reference to an e'isting ob8ect is passed. >. !hat are channels in .NET )emoting, Channels represent the ob8ects that transfer the other seriali:ed ob8ects from one application domain to another and from one comp ter to another, as well as one process to another on the same bo'. A channel m st e'ist before an ob8ect can be transferred. 67. !hat security measures e9ist for .NET )emoting in #ystem.)untime.)emoting, )one. &ec rity sho ld be ta!en care of at the application level. Cryptography and other sec rity techni" es can be applied at application or server level. 66. !hat is a formatter, A formatter is an ob8ect that is responsible for encoding and seriali:ing data into messages on one end, and deseriali:ing and decoding messages into data on the other end. 6=. Choosing et"een /TT$ and TC$ for protocols and Binary and #&A$ for formatters4 "hat are the trade1offs, 1inary over TCF is the most effiecient, &DAF over 3TTF is the most interoperable. 6B. !hat-s #ingleCall activation mode used for, If the server ob8ect is instantiated for responding to 8 st one single re" est, the re" est sho ld be made in &ingleCall mode. 6@. !hat-s #ingleton activation mode, A single ob8ect is instantiated regardless of the n mber of clients accessing it. -ifetime of this ob8ect is determined by lifetime lease. 6A. /o" do you define the lease of the o =ect, 1y implementing I-ease interface when writing the class code. 6C. Can you configure a .NET )emoting o =ect via ;3* file, Hes, via machine.config and application level .config file ,or web.config in A&F.)*T/. Application5level E;- settings ta!e precedence over machine.config. 6K. /o" can you automatically generate interface for the remota le o =ect in .NET "ith 3icrosoft tools, Ise the &oaps ds tool.

Advanced C# intervie" (uestions


6. !hat-s the advantage of using #ystem.Te9t.#tringBuilder over #ystem.#tring, &tring1 ilder is more efficient in the cases, where a lot of manip lation is done to the te't. &trings are imm table, so each time itQs being operated on, a new instance is created. =. Can you store multiple data types in #ystem.Array, )o. B. !hat-s the difference et"een the #ystem.Array.CopyTo@A and #ystem.Array.Clone@A, The first one performs a deep copy of the array, the second one is shallow. @. /o" can you sort the elements of the array in descending order, 1y calling &ort,/ and then .everse,/ methods. A. !hat-s the .NET datatype that allo"s the retrieval of data y a uni(ue 2ey, 3ashTable. C. !hat-s class #orted*ist underneath, A sorted 3ashTable. K. !ill finally loc2 get e9ecuted if the e9ception had not occurred, Hes. ?. !hat-s the C# e(uivalent of C>> catch @BA4 "hich "as a catch1all statement for any possi le e9ception, A catch bloc! that catches the e'ception of type &ystem.*'ception. Ho can also omit the parameter data type in this case and 8 st write catch ^_. >. Can multiple catch loc2s e e9ecuted, )o, once the proper catch code fires off, the control is transferred to the finally bloc! ,if there are any/, and then whatever follows the finally bloc!.

67. !hy is it a ad idea to thro" your o"n e9ceptions, #ell, if at that point yo !now that an error has occ rred, then why not write the proper code to handle that error instead of passing a new *'ception ob8ect to the catch bloc!( Throwing yo r own e'ceptions signifies some design flaws in the pro8ect. 66. !hat-s a delegate, A delegate ob8ect encaps lates a reference to a method. In C22 they were referred to as f nction pointers. 6=. !hat-s a multicast delegate, ItQs a delegate that points to and event ally fires off several methods. 6B. /o"-s the %** /ell pro lem solved in .NET, Assembly versioning allows the application to specify not only the library it needs to r n ,which was available nder #inB=/, b t also the version of the assembly. 6@. !hat are the "ays to deploy an assem ly, An ;&I installer, a CA1 archive, and ECDFH command. 6A. !hat-s a satellite assem ly, #hen yo write a m ltiling al or m lti5c lt ral application in .)*T, and want to distrib te the core application separately from the locali:ed mod les, the locali:ed assemblies that modify the core application are called satellite assemblies. 6C. !hat namespaces are necessary to create a locali0ed application, &ystem.Jlobali:ation, &ystem..eso rces. 6K. !hat-s the difference et"een :: comments4 :C C: comments and ::: comments, &ingle5line, m lti5line and E;- doc mentation comments. 6?. /o" do you generate documentation from the C# file commented properly "ith a command1 line compiler, Compile it with a 9doc switch. 6>. !hat-s the difference et"een DcE and DcodeE ;3* documentation tag, &ingle line code e'ample and m ltiple5line code e'ample. =7. +s ;3* case1sensitive, Hes, so U&t dentW and Ust dentW are different elements. =6. !hat de ugging tools come "ith the .NET #%F, Cor+1J ` command5line deb gger, and +bgC-. ` graphic deb gger. 0is al &t dio .)*T ses the +bgC-.. To se Cor+bg, yo m st compile the original C# file sing the 9deb g switch. ==. !hat does the This "indo" sho" in the de ugger, It points to the ob8ect thatQs pointed to by this reference. Db8ectQs instance data is shown. =B. !hat does assert@A do, In deb g compilation, assert ta!es in a 1oolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds witho t any interr ption if the condition is tr e. =@. !hat-s the difference et"een the %e ug class and Trace class, %ocumentation loo2s the same. Ise +eb g class for deb g b ilds, se Trace class for both deb g and release b ilds. =A. !hy are there five tracing levels in #ystem.%iagnostics.Trace#"itcher, The tracing d mps can be " ite verbose and for some applications that are constantly r nning yo r n the ris! of overloading the machine and the hard drive there. Five levels range from )one to 0erbose, allowing to fine5t ne the tracing activities. =C. !here is the output of Te9t!riterTrace*istener redirected, To the Console or a te't file depending on the parameter passed to the constr ctor. =K. /o" do you de ug an A#$.NET !e application, Attach the aspnet[wp.e'e process to the +bgClr deb gger. =?. !hat are three test cases you should go through in unit testing, Fositive test cases ,correct data, correct o tp t/, negative test cases ,bro!en or missing data, proper handling/, e'ception test cases ,e'ceptions are thrown and ca ght properly/. =>. Can you change the value of a varia le "hile de ugging a C# application, Hes, if yo are deb gging via 0is al &t dio.)*T, 8 st go to Immediate window.

B7. E9plain the three services model @three1tier applicationA. Fresentation ,II/, b siness ,logic and nderlying code/ and data ,from storage or other so rces/. B6. !hat are advantages and disadvantages of 3icrosoft1provided data provider classes in A%&.NET, &Q-&erver.)*T data provider is high5speed and rob st, b t re" ires &Q- &erver license p rchased from ;icrosoft. D-*5+1.)*T is niversal for accessing other so rces, li!e Dracle, +1=, ;icrosoft Access and Informi', b t itQs a .)*T layer on top of D-* layer, so not the fastest thing in the world. D+1C.)*T is a deprecated layer provided for bac!ward compatibility to D+1C engines. B=. !hat-s the role of the %ata)eader class in A%&.NET connections, It ret rns a read5only dataset from the data so rce when the command is e'ec ted. BB. !hat is the "ildcard character in #Q*, *et-s say you "ant to (uery data ase "ith *+FE for all employees "hose name starts "ith *a. The wildcard character is X, the proper " ery with -I]* wo ld involve a-aXQ. B@. E9plain AC+% rule of thum for transactions. Transaction m st be Atomic ,it is one nit of wor! and does not dependent on previo s and following transactions/, Consistent ,data is either committed or roll bac!, no Sin5betweenT case where something has been pdated and something hasnQt/, Isolated ,no transaction sees the intermediate res lts of the c rrent transaction/, + rable ,the val es persist if the data had been committed even if the system crashes right after/. BA. !hat connections does 3icrosoft #Q* #erver support, #indows A thentication ,via Active +irectory/ and &Q- &erver a thentication ,via ;icrosoft &Q- &erver sername and passwords/. BC. !hich one is trusted and "hich one is untrusted, #indows A thentication is tr sted beca se the sername and password are chec!ed with the Active +irectory, the &Q- &erver a thentication is ntr sted, since &Q- &erver is the only verifier participating in the transaction. BK. !hy "ould you use untrusted verificaion, #eb &ervices might se it, as well as non5#indows applications. B?. !hat does the parameter +nitial Catalog define inside Connection #tring, The database name to connect to. B>. !hat-s the data provider name to connect to Access data ase, ;icrosoft.Access. @7. !hat does %ispose method do "ith the connection o =ect, +eletes it from the memory. @6. !hat is a pre1re(uisite for connection pooling, ; ltiple processes m st agree that they will share the same connection, where every parameter is the same, incl ding the sec rity settings.

%ata ase programming for the !e intervie" (uestions


Q< /o" "ould you ma2e the follo"ing #Q* statement run faster, #E*ECT C F)&3 TAB*EA !/E)E C&*5G-A- AN% C&*8G-BHI A< ;a!e s re that CD-6 and CD-= have inde'es. Find o t which condition will ret rn less val es and se that as the first conditonal. Q< !hat is %ata 3ining A< +ata ;inig is the process of sifting thro gh e'tremely large amo nts of +ata to find trends or relevent information. Q< Name the #even layers in the &#+ 3odel. A< Appication, Fresentation, &ession, Transport, )etwor!, +ata -in!, Fhyiscal Q< !hat is one "ay to vie" a uni9 net"or2 share on a !indo"s computer4 "ithin e9plorer A< )F&, The Ini' comp ter can be r nning a )F& &erver +aemon.

Q< /o" "ould you find all the processes running on your computer. A< Ini', is ps 5ef or ps 5a ' depending on version. Q< !hat is %/C$ A< +3CF is a way to dynamically assign IF address to comp ters. +yanmic 3ost Config ration Frotocol Q< !hat is /TT$ Tunneling A< 3TTF T nneling is a sec rity method that encryptes pac!ets traveling thro ght the internet. Dnly the intended reciepent sho ld be able to decrypt the pac!ets. Can be sed to Create 0irt al Frivate )etwor!s. ,0F)/ Q< #cenario< Jou have K identical loo2ing alls4 ho"ever one all is heavier than the others. Jou have t"o chances to use a alance. /o" do you find out "hich all is the heaviest, A< &plit into gro ps of three, randomly choose two gro ps and se balance on them. If one gro p is heavier, then discard the other C balls. If the two gro ps are the same weight. The heavier ball m st be in the gro p that was not on the scale. )ow randomly choose two balls and test on balance. If they are the same weight, the heaviest ball is on one that was not tested. *lse the heaviest ball is already !nown from the balance.

#Q* #erver intervie" (uestions


6. 3ow do yo read transaction logs( =. 3ow do yo reset or reseed the I+*)TITH col mn( B. 3ow do yo persist ob8ects, permissions in tempdb( @. 3ow do yo sim late a deadloc! for testing p rposes( A. 3ow do yo rename an &Q- &erver comp ter( C. 3ow do yo r n 8obs from T5&Q-( K. 3ow do yo restore single tables from bac! p in &Q- &erver K.79=777( In &Q- &erver C.A( ?. #here to get the latest ;+AC from( >. I forgot9lost the sa password. #hat do I do( 67. I have only the .mdf file bac! p and no &Q- &erver database bac! ps. Can I get my database bac! into &Q- &erver( 66. 3ow do yo add a new col mn at a specific position ,say at the beginning of the table or after the second col mn/ sing A-T*. TA1-* command( 6=. 3ow do yo change or alter a ser defined data type( 6B. 3ow do yo rename an &Q- &erver =777 instance( 6@. 3ow do yo capt re9redirect detailed deadloc! information into the error logs( 6A. 3ow do yo remotely administer &Q- &erver( 6C. #hat are the effects of switching &Q- &erver from a;i'ed modeQ to a#indows onlyQ a thentication mode( #hat are the steps re" ired, to not brea! e'isting applications( 6K. Is there a command to list all the tables and their associated filegro ps( 6?. 3ow do yo ship the stored proced res, ser defined f nctions ,I+Fs/, triggers, views of my application, in an encrypted form to my clients9c stomers( 3ow do yo protect intellect al property( 6>. 3ow do yo archive data from my tables( Is there a b ilt5in command or tool for this( =7. 3ow do yo tro bleshoot D+1C timeo t e'pired errors e'perienced by applications accessing &Q- &erver databases( =6. 3ow do yo restart &Q- &erver service a tomatically at reg lar intervals(

==. #hat is the T5&Q- e" ivalent of IIF ,immediate if9ternary operator/ f nction of other programming lang ages( =B. 3ow do yo programmatically find o t when the &Q- &erver service started( =@. 3ow do yo get rid of the time part from the date ret rned by J*T+AT* f nction( =A. 3ow do yo pload images or binary files into &Q- &erver tables( =C. 3ow do yo r n an &Q- script file that is located on the dis!, sing T5&Q-( =K. 3ow do yo get the complete error message from T5&Q- while error handling( =?. 3ow do yo get the first day of the wee!, last day of the wee! and last day of the month sing T5 &Q- date f nctions( =>. 3ow do yo pass a table name, col mn name etc. to the stored proced re so that I can dynamically select from a table( B7. *rror inside a stored proced re is not being raised to my front5end applications sing A+D. 1 t I get the error when I r n the proced re from Q ery Analy:er. B6. 3ow do yo s ppress error messages in stored proced res9triggers etc. sing T5&Q-( B=. 3ow do yo save the o tp t of a " ery9stored proced re to a te't file( BB. 3ow do yo 8oin tables from different databases( B@. 3ow do yo 8oin tables from different servers( BA. 3ow do yo convert timestamp data to date data ,datetime datatype/( BC. Can I invo!e9instantiate CD; ob8ects from within stored proced res or triggers sing T5&Q-( BK. Dracle has a rown m to access rows of a table sing row n mber or row id. Is there any e" ivalent for that in &Q- &erver( Dr 3ow do yo generate o tp t with row n mber in &Q- &erver( B?. 3ow do yo specify a networ! library li!e TCF9IF sing A+D connect string( B>. 3ow do yo generate scripts for repetitive tas!s li!e tr ncating all the tables in a database, changing owner of all the database ob8ects, disabling constraints on all tables etc( @7. Is there a way to find o t when a stored proced re was last pdated( @6. 3ow do yo find o t all the I+*)TITH col mns of all the tables in a given database( @=. 3ow do yo search the code of stored proced res( 3ow do yo retrieve the generated JII+ val e of a newly inserted row( Is there an 44JII+, 8 st li!e 44I+*)TITH(
:. (escri$e #aria$le scope class mem$er scope and reference countin!. E2hort answers are preferred.F Cy default #aria$le class scope is pri#ate 2. -ist some of your fa#orite pro!rammin! optimi3ations tricks and,or al!orithms4 Minimise the roundtrips session #aria$les data$ase operation should done thro dataset mostly minimi3e the usa!e of more pictures ;. (escri$e the use of the 1roperty keyword in .NET and how it differs from a pu$lic #aria$le. "t is used to !et set the #alues. "t is used to assi!n the #alue inside the function after assi!nment only the #alues !oes to the #aria$le <. 5hat is the fastest method of searchin! a sorted array4 unsorted array4 Cinary search linear for unsorted =. (escri$e an appropriate usa!e of Hser (efined E#ents. For some function in client side e'ecution >. (escri$e your #iews on e'ception handlin!.

"t is used to show the user correspondin! error raised instead of system han!in! @. 5hat is the difference $etween inheritance and implementin! interfaces in .NET4 Hsin! inhertance we can achie#e only sin!le inheritance Cy usin! interface multiple inheritance is achei#ed A. -ist resources utili3ed when you encounter a pro$lem. Tracin! and de$u!!in! B. "f you6re not cheatin! you6re not most e'pertOOOOOOOOOOO enou!h. :0. Hsin! your own codin! philosophies please list the followin! in order of importance and why you ordered them that way+ Ans e c a d $ aF .elia$ility $F 2cala$ility cF Efficiency dF Maintaina$ility eF 2ecurity ::. 5hich is more efficient in an "F statement+ Hsin! AN( or usin! AN(A-2&4 Also descri$e why you feel this way. Andalso $ecausin! it was short circuitin! process $ased for Nuick e'ecution. :2. (escri$e what 8ar$a!e %ollection is. Also descri$e the pros and cons in re!ards to system o#erhead and pro!rammer efficiency. 8% is called $y the %-. when the mana!e heap was filled if we want to call manully 8%.%ollect is used.otherwise finalise and dispose can $e used 5hen we donWt need the #aria$le #alue for further process then we can use dispose :;. 5hy would you want to utili3e an interface4 To implement multiple inheritance And to !i#e the !eneral sketch what are the function used in the pro!ram :<. 1lace an D*D ne't to all that you ha#e e'perience with. 1lace an 6**6 ne't to the ones you en7oy workin! with. OOO GC ;.0 OOO GC <.0 OOO GC =.0,>.0 * OOO GC.NET ** OOO %/ ** OOO Gisual %00 OOO NT <.0 OOO 5indows 2000 * OOO 5indows *1 * OOO Access * OOO M2 2Q- 2er#er OOO &racle OOO 2Q- Ein !eneralF ** OOO ?TM- ** OOO %8" OOO ""2 * OOO A21 OOO A21.NET ** OOO *M- * OOO *2OOO Turtle 8raphics

:=. Hsin! &&1 methodolo!y create a class that e'hi$its any Nualities and $eha#iors that youWd like for a ;) (emensional item Esuch as a $ook fruit furniture etcF. ?a#e this particular class inherit from a $ase class. :>. E'aminin! the classes youW#e 7ust created ) 5hat are the pros if any of polymorphism4 :@. A!ain e'aminin! the classes youW#e 7ust created ) 5hat are the cons if any of polymorphism4 :A. 5hy would you define a #irtual function4 :B. 5hat is a strin!4 ?ow does it relate to threadin!4 20. 5hat is the difference $etween .NET .emotin! and 5e$ser#ices4 -ist the pros and cons of each. 2:. %omplete the code for these functions. .ead the comment $locks to determine what the function should do. 5rite these functions so that they may $e copied directly into the Gisual 2tudio.NET "(E and compiled. 1u$lic Function "s-eapJearECyGal lJear As -on!F As Coolean \This function accepts a < di!it year and \returns \T.HEW if that year is a leap year End Function

1u$lic Function -istTo2trin!Eo2trin!s As Arraylist s(elimiter As 2trin!F As 2trin! 6This function accepts an Array-ist of strin!s and returns a sin!le strin! 6that is the delimited form of the o2trin!s collection usin! s(elimiter as 6the character to seperate each item in the collection. End Function

1u$lic Function 2tripNum$ersEsTe't As 2trin! s.eplace2trin! As 2trin!F As 2trin! 6This function accepts a strin! of characters and does one of two thin!s+ 6:. "f s.eplace2trin! is specified the num$ers are replaced with that strin!. 62. "f s.eplace2trin! is $lank the num$ers are remo#ed. 6For e'ample if sTe't K D?A11J2(AJD and s.eplace2trin! is $lank 6this function returns D?A11J(AJD. "f sTe't K D?A11J2(AJD and 6s.eplace2trin!KD*D then this function returns D?A11J*(AJD 6This function should $e optimi3ed for speed. 69eep in mind s.eplace2trin! could $e more than one character. End Function

&ptional+ 5hy are :BA0 pennies worth more than :B@B pennies4

Tony likes indi!o $ut not $lue. ?e likes onions $ut not turnips] he likes forms $ut not shapes. Accordin! to the same rule does he like tomatoes or a#ocados4

You might also like