Category Archives: C# Programming

Chapter97:FileandStreamI/O

Parameter                                                                Details path                The locationof thefile. append           Ifthefileexist,truewilladddatatotheendofthefile(append),falsewilloverwritethefile. text Text to be written or stored. contents        A collection of strings to be written.…
Continue reading

Chapter96:Delegates

Section96.1:Declaringadelegatetype ThefollowingsyntaxcreatesadelegatetypewithnameNumberInOutDelegate,representingamethodwhichtakes an intand returns an int. publicdelegateintNumberInOutDelegate(intinput); Thiscanbeusedasfollows: publicstaticclassProgram { staticvoidMain() { NumberInOutDelegatesquare=MathDelegates.Square; intanswer1=square(4); Console.WriteLine(answer1);//Willoutput16 NumberInOutDelegatecube=MathDelegates.Cube; intanswer2=cube(4); Console.WriteLine(answer2);//Willoutput64 } } publicstaticclassMathDelegates {…
Continue reading

Chapter95:Attributes

Section95.1:Creatingacustomattribute //1)AllattributesshouldbeinheritedfromSystem.Attribute //2)Youcancustomizeyourattributeusage(e.g.placerestrictions)byusingSystem.AttributeUsage Attribute //3)Youcanusethisattributeonlyviareflectioninthewayitissupposedtobeused //4)MethodMetadataAttributeisjustaname.Youcanuseitwithout"Attribute"postfix-e.g. [MethodMetadata("Thistextcouldberetrievedviareflection")]. //5)Youcanoverloadanattributeconstructors [System.AttributeUsage(System.AttributeTargets.Method|System.AttributeTargets.Class)] publicclassMethodMetadataAttribute:System.Attribute { //thisiscustomfieldgivenjustforanexample //youcancreateattributewithoutanyfields //evenanemptyattributecanbeused-asmarker publicstringText{get;set;} //thisconstructorcouldbeusedas[MethodMetadata] publicMethodMetadataAttribute() { } //Thisconstructorcouldbeusedas[MethodMetadata("String")] publicMethodMetadataAttribute(stringtext) { Text=text;…
Continue reading

Chapter94:Structs

Section94.1:Declaringa struct publicstructVector { publicintX; publicintY; publicintZ; } publicstructPoint { publicdecimalx,y; publicPoint(decimalpointX,decimalpointY) { x=pointX; y=pointY; } } structinstancefieldscanbesetviaaparametrizedconstructororindividuallyafterstructconstruction. Privatememberscanonlybeinitializedbytheconstructor. structdefines a sealed type…
Continue reading

Chapter93:Preprocessordirectives

Section93.1:ConditionalExpressions Whenthefollowingiscompiled,itwillreturnadifferentvaluedependingonwhichdirectivesaredefined. //Compilewith/d:Aor/d:Btoseethedifference stringSomeFunction() { #ifA return"A"; #elifB return"B"; #else return"C"; #endif } Conditionalexpressionsaretypicallyusedtologadditionalinformationfordebugbuilds. voidSomeFunc() { try { SomeRiskyMethod(); } catch(ArgumentExceptionex) { #ifDEBUG…
Continue reading

Chapter92:BindingList

Section92.1:Additemtolist BindingList<string>listOfUIItems=newBindingList<string>(); listOfUIItems.Add("Alice"); listOfUIItems.Add("Bob"); Section92.2:AvoidingN*2iteration ThisisplacedinaWindowsFormseventhandler varnameList=newBindingList<string>(); ComboBox1.DataSource=nameList;for(longi=0; i<10000;i++){ nameList.AddRange(new[]{"Alice","Bob","Carol"}); } Thistakesalongtimetoexecute,tofix,dothebelow: varnameList=newBindingList<string>(); ComboBox1.DataSource=nameList; nameList.RaiseListChangedEvents=false; for(longi=0;i<10000;i++){ nameList.AddRange(new[]{"Alice","Bob","Carol"}); } nameList.RaiseListChangedEvents=true; nameList.ResetBindings();
Continue reading

Chapter91:OverloadResolution

Section91.1:BasicOverloadingExampleThiscodecontainsanoverloadedmethodnamedHello: classExample { publicstaticvoidHello(intarg) { Console.WriteLine("int"); } publicstaticvoidHello(doublearg) { Console.WriteLine("double"); } publicstaticvoidMain(string[]args) { Hello(0); Hello(0.0); } } WhentheMainmethodiscalled,itwillprint int double Atcompile-time,whenthecompilerfindsthemethodcallHello(0),itfindsallmethodswiththenameHello.In thiscase,itfindstwoofthem.Itthentriestodeterminewhichofthemethodsisbetter.Thealgorithmfor determiningwhichmethodisbetteriscomplex,butitusuallyboilsdownto"makeasfewimplicitconversionsas…
Continue reading

Chapter90:ExpressionTrees

Parameter                                     Details TDelegate                    Thedelegatetypetobeusedfortheexpression lambdaExpression Thelambdaexpression(ex.num=>num<5) ExpressionTreesareExpressionsarrangedinatreelikedatastructure.Eachnodeinthetreeisarepresentationof an expression, an expression being code. An In-Memory representation of a Lambda expression would be an…
Continue reading

Chapter89:Events

Parameter                                                       Details EventArgsT             ThetypethatderivesfromEventArgsandcontainstheeventparameters. EventName             The name of the event. HandlerName          The name of the event handler. SenderObject         Theobjectthat'sinvokingtheevent. EventArgumentsAninstanceoftheEventArgsTtypethatcontainstheeventparameters. Aneventisanotificationthatsomethinghasoccurred(suchasamouseclick)or,insomecases,isabouttooccur (such as…
Continue reading

Chapter88:INotifyPropertyChanged interface

Section88.1:ImplementingINotifyPropertyChangedinC#6 TheimplementationofINotifyPropertyChangecanbeerror-prone,astheinterfacerequiresspecifyingproperty nameasastring.Inordertomaketheimplementationmorerobust,anattributeCallerMemberNamecanbeused. classC:INotifyPropertyChanged { //backingfield intoffset; //property publicintOffset { get { returnoffset; } set { if(offset==value) return; offset=value; RaisePropertyChanged(); } } //helpermethodforraisingPropertyChangedevent…
Continue reading