C# logging data technique

Spread the love

C# Logging Data Technique

The last few weeks I have been having to conduct some C# code reviews. While doing so, I came across a great, flexible C# logging data technique using just String.Format(), a List<string>(), and a Dictionary<string,string>() object.


C# logging data code I typically come across is as follows:

The above code presents challenges. For instance:

  • What if there’s a requirement to not display the “Distance:” section if there’s no data?
  • What if from one part of the code the “Title:” section has to be called something else like “Caption:”? There’s no easy way around that without some conditional logic in the current model.
  • What if the ordering needs to be dynamic based on another set of conditions?


After the code review, here’s the technique that was implemented using List<string>. Ready?

Look at the difference in code, have a stop, and think as to why the latter would be preferred before reading further.

Ready? There are spoilers from this point!


Some of the advantages to using the latter C# logging data technique:

  • You can change the heading text dynamically, more easily:

    results.Add(string.Format(itemFormat, (sourceItem["Title"].ToLower() != "new" ? "Locations:" : "Location:"), sourceItem["Location"]));
  • You can have parts not displayed if there’s no data:

    if (!String.IsNullOrWhiteSpace(sourceItem["Title"]))
    results.Add(string.Format(itemFormat, "Title:", sourceItem["Title"]));
  • You have a flexible way to reorder the output sections just by changing the calling order of results.Add()


Winning! 🙂


Do you have any tips or techniques to share? Leave them in the comments below or send me a message so we can let others know. 🙂


Spread the love

David Lozinski