Professional Documents
Culture Documents
Framework FAQ
Framework FAQ
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
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
o o
@.2 %an " create my own metadata attri$utes4 @.; %an " create my own conte't atti$utes4
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
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
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
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
:;.: 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
1. #ntrodu$t%on
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'.
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
" 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.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.
"f you are a %00 pro!rammer you mi!ht like to check out my %/ FAQ.
. 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.
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.
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.
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
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; } }
5. 9ar5a,e "o..e$t%on
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.
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.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.
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
!.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.
!.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.
7. Attr%5utes
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.
{ %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 ); } }
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.
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.
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.
Then to apply the permission set to a code !roup do somethin! like this+
caspol Gc! F.7 Sample=ermSet
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.
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.
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.
(ST"
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
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() ); } }
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
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; } }
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 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'.
11. A%s$e..aneous
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 ); } }
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.
?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.
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 :.'.
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
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
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.+ 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.
%/ 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,
-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.
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.
"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
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
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
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.
2. T-pes
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 ); } }
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
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
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' ); }
.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.
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.
.! #* "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.
+. 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.
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.
$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 ); } } }
!. A%s$e..aneous
// true
!.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.
?owe#er consider usin! this more aesthetically pleasin! E$ut functionally identicalF formattin!+
usin!( ob*F ) usin!( ob*8 ) { ... }
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.
7. "2 2.0
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.
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.
#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 //(
#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(
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(
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
)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/.
;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.
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<
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.
& 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.
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.
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.
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.
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.
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/.
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.
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
} }
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.
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;
)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 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#./
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.
)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);
(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.
// // // // //
%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/.
} } }
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.
.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.
;>. &'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.
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.
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.
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.
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! &+].
?. #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
?. !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.
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.
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.
==. #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