Category Archives: C# Programming

Chapter50:NamedandOptional Arguments

Section50.1:OptionalArguments Considerprecedingisourfunctiondefinitionwithoptionalarguments. privatestaticdoubleFindAreaWithOptional(intlength,intwidth=56) { try { return(length*width); } catch(Exception) { thrownewNotImplementedException(); } } Herewehavesetthevalueforwidthasoptionalandgavevalueas56.Ifyounote,theIntelliSenseitselfshowsyou the optional argument as shown in the below image.…
Continue reading

Chapter49:NamedArguments

Section49.1:Argumentorderisnotnecessary Youcanplacenamedargumentsinanyorderyouwant. Sample Method: publicstaticstringSample(stringleft,stringright) { returnstring.Join("-",left,right); } CallSample: Console.WriteLine(Sample(left:"A",right:"B")); Console.WriteLine(Sample(right:"A",left:"B")); Results: A-B B-A Section49.2:Namedargumentsandoptionalparameters You can combine named arguments with optional parameters.…
Continue reading

Chapter48:ExtensionMethods

Section48.1:Extensionmethods-overview Extension methods were introduced in C# 3.0. Extension methods extend and add behavior to existing typeswithout creating a new derived type, recompiling,…
Continue reading

Chapter47:Methods

Section47.1:CallingaMethod Callingastaticmethod: //Singleargument System.Console.WriteLine("HelloWorld"); //Multiplearguments stringname="User"; System.Console.WriteLine("Hello,{0}!",name); Callingastaticmethodandstoringitsreturnvalue: stringinput=System.Console.ReadLine(); Callinganinstancemethod: intx=42; //TheinstancemethodcalledhereisInt32.ToString() stringxAsString=x.ToString(); Callingagenericmethod //Assumingamethod'T[]CreateArray<T>(intsize)' DateTime[]dates=CreateArray<DateTime>(8); Section47.2:Anonymousmethod Anonymousmethodsprovideatechniquetopassacodeblockasadelegateparameter.Theyaremethodswitha body, but no name. delegateintIntOp(intlhs,intrhs);…
Continue reading

Chapter46:Objectinitializers

Section46.1:Simpleusage Object initializers are handy when you need to create an object and set a couple of properties right away, but the available…
Continue reading

Chapter45:Partialclassandmethods

Partial classes provides us an option to split classes into multiple parts and in multiple source files. All parts are combined into one…
Continue reading

Chapter44:DependencyInjection

Section44.1:DependencyInjectionC#andASP.NETwithUnity First why we should use depedency injection in our code ? We want to decouple other components from other classes in our…
Continue reading

Chapter43: Singleton Implementation

Section43.1:StaticallyInitializedSingleton publicclassSingleton { privatereadonlystaticSingletoninstance=newSingleton(); privateSingleton(){} publicstaticSingletonInstance=>instance; } Thisimplementationisthread-safebecauseinthiscaseinstanceobjectisinitializedinthestaticconstructor.The CLRalreadyensuresthatallstaticconstructorsareexecutedthread-safe. Mutatinginstanceisnotathread-safeoperation,thereforethereadonlyattributeguaranteesimmutabilityafter initialization. Section43.2:Lazy,thread-safeSingleton(usingLazy<T>) .Net4.0typeLazyguaranteesthread-safeobjectinitialization,sothistypecouldbeusedtomakeSingletons. publicclassLazySingleton { privatestaticreadonlyLazy<LazySingleton>_instance=newLazy<Laz ySingleton>(()=>newLazySingleton()); publicstaticLazySingletonInstance { get{return_instance.Value;} } privateLazySingleton(){} }…
Continue reading

Chapter42:StaticClasses

Section42.1:StaticClasses The"static"keywordwhenreferringtoaclasshasthree effects: Youcannotcreateaninstanceofastaticclass(thisevenremovesthedefaultconstructor) Allpropertiesandmethodsintheclassmustbestaticaswell. Astaticclassisasealedclass,meaningitcannotbeinherited. publicstaticclassFoo { //Noticethereisnoconstructorasthiscannotbeaninstance publicstaticintCounter{get;set;} publicstaticintGetCount() { returnCounter; } } publicclassProgram { staticvoidMain(string[]args) { Foo.Counter++; Console.WriteLine(Foo.GetCount());//thiswillprint1 //varfoo1=newFoo(); //thislinewouldbreakthecodeastheFooclassdoesnothaveaconstructor…
Continue reading

Chapter41:Interfaces

Section41.1:ImplementinganinterfaceAninterfaceisusedtoenforcethepresenceofamethodinanyclassthat'implements'it.Theinterfaceisdefined withthekeywordinterfaceandaclasscan'implement'itbyadding:InterfaceNameaftertheclassname.Aclass canimplementmultipleinterfacesbyseparatingeachinterfacewithacomma.:InterfaceName,ISecondInterface publicinterfaceINoiseMaker { stringMakeNoise(); } publicclassCat:INoiseMaker { publicstringMakeNoise() { return"Nyan"; } } publicclassDog:INoiseMaker { publicstringMakeNoise() { return"Woof"; } } Because they…
Continue reading