Category Archives: C# Programming

Chapter80:Diagnostics

Section80.1:RedirectinglogoutputwithTraceListeners You can redirect the debug output to a text file by adding a TextWriterTraceListener to the Debug.Listeners collection. publicstaticvoidMain(string[]args) { TextWriterTraceListenermyWriter=newTextWriterTraceListener(@"debug.txt"); Debug.Listeners.Add(myWriter);…
Continue reading

Chapter79:Read&Understand Stacktraces

Astacktraceisagreataidwhendebuggingaprogram.Youwillgetastacktracewhenyourprogramthrowsan Exception, and sometimes when the program terminates abnormally. Section79.1:StacktraceforasimpleNullReferenceException inWindowsForms Let'screateasmallpieceofcodethatthrowsanexception: privatevoidbutton1_Click(objectsender,EventArgse) { stringmsg=null; msg.ToCharArray(); } Ifweexecutethis,wegetthefollowingExceptionandstacktrace: System.NullReferenceException:"Objectreferencenotsettoaninstanceofanobject."atWindowsFormsA pplication1.Form1.button1_Click(Objectsender,EventArgse)in F:\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs:line29atSystem. Windows.Forms.Control.OnClick(EventArgse) atSystem.Windows.Forms.Button.OnClick(EventArgse)…
Continue reading

Chapter78:HandlingFormatException whenconvertingstringtoothertypes

Section78.1:Convertingstringtointeger Therearevariousmethodsavailableforexplicitlyconvertingastringtoaninteger,suchas: Convert.ToInt16(); Convert.ToInt32(); Convert.ToInt64(); int.Parse(); ButallthesemethodswillthrowaFormatException,iftheinputstringcontainsnon-numericcharacters.Forthis, we need to write an additional exception handling(try..catch) to deal them in such cases. ExplanationwithExamples: So,…
Continue reading

Chapter77:NullReferenceException

Section77.1:NullReferenceExceptionexplained ANullReferenceExceptionisthrownwhenyoutrytoaccessanon-staticmember(property,method,fieldor event) of a reference object but it is null. CarmyFirstCar=newCar(); CarmySecondCar=null; ColormyFirstColor=myFirstCar.Color;//NoproblemasmyFirstCarexists/isnotnull ColormySecondColor=mySecondCar.Color;//ThrowsaNullReferenceException //asmySecondCarisnullandyetwetrytoaccessitscolor. Todebugsuchanexception,it'squiteeasy:onthelinewheretheexceptionisthrown,youjusthavetolookbefore every '.'or '[', or on rare…
Continue reading

Chapter76:ExceptionHandling

Section76.1:CreatingCustomExceptions You are allowed to implement custom exceptions that can be thrown just like any other exception. This makes sense when you want…
Continue reading

Chapter75:C#3.0Features

Section75.1:Implicitlytypedvariables(var) The varkeyword allows a programmer to implicitly type a variable at compile time. vardeclarations have the same type as explicitly declared variables.…
Continue reading

Chapter74:C#4.0Features

Section74.1:Optionalparametersandnamedarguments We can omit the argument in the call if that argument is an Optional Argument Every Optional Argument has its own default…
Continue reading

Chapter73:C#5.0Features

Method/ModifierwithParameter          Details Type<T>                                                            Tisthereturntype Section73.1:Async&Await asyncandawaitaretwooperatorsthatareintendedtoimproveperformancebyfreeingupThreadsandwaiting for operations to complete before moving forward. Here'sanexampleofgettingastringbeforereturningit'slength: //Thismethodisasyncbecause: //1.IthasasyncandTaskorTask<T>asmodifiers //2.Itendsin"Async" asyncTask<int>GetStringLengthAsync(stringURL){ HttpClientclient=newHttpClient(); //SendsaGETrequestandreturnstheresponsebodyasastring Task<string>getString=client.GetStringAsync(URL); //WaitsforgetStringtocompletebeforereturningitslength stringcontents=awaitgetString;…
Continue reading

Chapter72:C#6.0Features

This sixth iteration of the C# language is provided by the Roslyn compiler. This compiler came out with version 4.6 of the .NET…
Continue reading

Chapter71:C#7.0Features

C#7.0istheseventhversionofC#.Thisversioncontainssomenewfeatures:languagesupportforTuples,local functions,outvardeclarations,digitseparators,binaryliterals,patternmatching,throwexpressions,refreturnand reflocaland extended expression bodied members list. Officialreference:What'snewinC#7 Section71.1:LanguagesupportforTuples Basics Atupleisanordered,finitelistofelements.Tuplesarecommonlyusedinprogrammingasameanstoworkwith one single entity collectively instead of individually working with each of…
Continue reading