Technology Made Easy

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. source            The location of the file you want to use. dest       The location you want a file to go to. Managesfiles. Section97.1:ReadingfromafileusingtheSystem.IO.Fileclass YoucanusetheSystem.IO.File.ReadAllTextfunctiontoreadtheentirecontentsofafileintoastring. stringtext=System.IO.File.ReadAllText(@”C:\MyFolder\MyTextFile.txt”); YoucanalsoreadafileasanarrayoflinesusingtheSystem.IO.File.ReadAllLinesfunction: string[]lines=System.IO.File.ReadAllLines(@”C:\MyFolder\MyTextFile.txt”); Section97.2:Lazilyreadingafileline-by-lineviaan IEnumerable When working with large […]

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 { staticintSquare(intx) { returnx*x; } staticintCube(intx) { returnx*x*x; } } TheexampledelegateinstanceisexecutedinthesamewayastheSquaremethod.Adelegateinstanceliterallyacts asadelegateforthecaller:thecallerinvokesthedelegate,andthenthedelegatecallsthetargetmethod.This indirection decouples the caller from the target method. You can declare a generic delegate type, and in that case you may […]

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; } } Section95.2:Readinganattribute MethodGetCustomAttributesreturnsanarrayofcustomattributesappliedtothemember.Afterretrievingthis arrayyoucansearchforoneormorespecificattributes. varattribute=typeof(MyClass).GetCustomAttributes().OfType<MyCustomAttribute>().Single(); Oriteratethroughthem foreach(varattributeintypeof(MyClass).GetCustomAttributes()){ Console.WriteLine(attribute.GetType()); } GetCustomAttributeextension method from System.Reflection.CustomAttributeExtensionsretrieves a custom attributeofaspecifiedtype,itcanbeappliedtoanyMemberInfo. varattribute=(MyCustomAttribute)typeof(MyClass).GetCustomAttribute(typeof(MyCustomAttribute)); GetCustomAttributealsohasgenericsignaturetospecifytypeofattributetosearchfor. varattribute=typeof(MyClass).GetCustomAttribute<MyCustomAttribute>(); Booleanargumentinheritcanbepassedtobothofthosemethods.Ifthisvaluesettotruetheancestorsof element would be also to inspected. Section95.3:Usinganattribute [StackDemo(Text=”Hello,World!”)] publicclassMyClass { [StackDemo(“Hello,World!”)] […]

Section94.1:Declaringa struct publicstructVector { publicintX; publicintY; publicintZ; } publicstructPoint { publicdecimalx,y; publicPoint(decimalpointX,decimalpointY) { x=pointX; y=pointY; } } Vectorv1=null;//illegal Vector?v2=null;//OK Nullable<Vector>v3=null//OK //Bothoftheseareacceptable Vectorv1=newVector();v1.X=1; v1.Y=2; v1.Z=3; Vectorv2; v2.X=1; v2.Y=2; v2.Z=3; However,thenewoperatormust be usedin orderto usean initializer: Vectorv1=newMyStruct{X=1,Y=2,Z=3};//OK Vectorv2{X=1,Y=2,Z=3};//illegal Astructcandeclareeverythingaclasscandeclare,withafewexceptions: Section94.2:Structusage Withconstructor: Vectorv1=newVector(); v1.X=1; v1.Y=2; v1.Z=3; Console.WriteLine(“X={0},Y={1},Z={2}”,v1.X,v1.Y,v1.Z); //OutputX=1,Y=2,Z=3 Vectorv1=newVector(); //v1.Xisnotassigned v1.Y=2; v1.Z=3; Console.WriteLine(“X={0},Y={1},Z={2}”,v1.X,v1.Y,v1.Z); //OutputX=0,Y=2,Z=3 Pointpoint1=newPoint(); point1.x=0.5; point1.y=0.6; Pointpoint2=newPoint(0.5,0.6); […]

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 log.Error(“SomeFunc”,ex); #endif HandleException(ex); } } Section93.2:OtherCompilerInstructions Line #linecontrolsthelinenumberandfilenamereportedbythecompilerwhenoutputtingwarningsanderrors. voidTest() { #line42″Answer” #linefilename”SomeFile.cs” intlife;//compilerwarningCS0168in”SomeFile.cs”atLine42 #linedefault //compilerwarningsresettodefault } PragmaChecksum #pragmachecksumallowsthespecificationofaspecificchecksumforageneratedprogramdatabase(PDB)for debugging. #pragmachecksum”MyCode.cs””{00000000-0000-0000-0000-000000000000}””{0123456789A}” Section93.3:DefiningandUndefiningSymbols A compiler symbol is a keyword that is defined at compile-time […]

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();

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 possible”.Thus,inthecaseofHello(0),noconversionisneededforthemethodHello(int)butanimplicitnumeric conversion is needed for the method Hello(double). Thus, the first method is chosen by the compiler. InthecaseofHello(0.0),thereisnowaytoconvert0.0toanintimplicitly,sothemethodHello(int)isnoteven consideredforoverloadresolution.Onlymethodremainsandsoitischosenbythecompiler.Section91.2:”params”isnotexpanded,unlessnecessaryThefollowing program: classProgram { staticvoidMethod(paramsObject[]objects) { System.Console.WriteLine(objects.Length); } staticvoidMethod(Objecta,Objectb) { System.Console.WriteLine(“two”); } staticvoidMain(string[]args) { […]

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 Expression tree, which holds the actual elements (i.e. code) of the query, but not its result. Expression trees make the structure of a lambda expression transparent and explicit. Section90.1:CreateExpressionTreeswithalambda expression Followingismostbasicexpressiontreethatiscreatedbylambda. Expression<Func<int,bool>>lambda=num=>num==42; […]

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 a price change). Classescandefineeventsandtheirinstances(objects)mayraisetheseevents.Forinstance,aButtonmaycontaina Click event that gets raised when a user has clicked it. Event handlers are then methods that get called when their corresponding event is raised. A form may […]

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 voidRaisePropertyChanged([CallerMemberName]stringpropertyName=null)=>PropertyChanged?.Invoke(this,newPropertyChangedEventArgs(propertyName)); //interfaceimplemetation publiceventPropertyChangedEventHandlerPropertyChanged; } IfyouhaveseveralclassesimplementingINotifyPropertyChanged,youmayfinditusefultorefactoroutthe interfaceimplementationandthehelpermethodtothecommonbaseclass: classNotifyPropertyChangedImpl:INotifyPropertyChanged { protectedvoidRaisePropertyChanged([CallerMemberName]stringpropertyName=null)=>PropertyChanged?.Invoke(this,newPropertyChangedEventArgs(propertyName)); //interfaceimplemetation publiceventPropertyChangedEventHandlerPropertyChanged; } classC:NotifyPropertyChangedImpl { intoffset; publicintOffset { get{returnoffset;} set{if(offset!=value){offset=value;RaisePropertyChanged();}} } } Section88.2:INotifyPropertyChangedWithGenericSet Method TheNotifyPropertyChangedBaseclassbelowdefinesagenericSetmethodthatcanbecalledfromanyderived type. publicclassNotifyPropertyChangedBase:INotifyPropertyChanged { protectedvoidRaisePropertyChanged([CallerMemberName]stringpropertyName=null)=>PropertyChanged?.Invoke(this,newPropertyChangedEventArgs(propertyName)); publiceventPropertyChangedEventHandlerPropertyChanged; publicvirtualboolSet<T>(refTfield,Tvalue,[CallerMemberName]stringpropertyName=null) { if(Equals(field,value)) […]