Monday, November 26, 2001 ..:: Home ::.. Register  Login
   TechTidBits (Blog)  

Writing out variable values to the console or string, how hard can it be?

Oct 14

Written by:
Sunday, October 14, 2018 5:00 PM  RssIcon

VS2017Are you debugging some automated C# code? Or maybe you’re just outputting some value to the console? Want to snoop in on something during runtime? How do you do it? Let me count the ways…. No, really, let’s count them,

  1. using string concatenation (using + with multiple strings)
    • image
  2. using string.concat()
    • image
  3. using StringBuilder
    • image
  4. using WriteLine itself
    • image
  5. using String.Format
    • image

I believe those last two are very similar and for the loooooooooongest time, that was the way basically everyone concatenated strings together. But it’s certainly not perfect! Ever gotten one of THESE beauties?! FormatException? In my cooked up example, ALL I changed was the {2} to a {3}. If you’ve every tried to “just add one value to that output string” right before a prod release, you’ve probably seen this mistake before. DOH!


Wouldn’t it be AWESOME if you didn’t have to know ahead of time the order of your output (no ordinal values in your string) but instead could just use the variable name?

Well, there is!!!!! The feature is called String Interpolation and it was introduced in C# ver 6.0. The beauty of this is you just prefix your string with the $ (dollar sign) then simply wrap your variable with braces (“{ }”)


The BEAUTY of this way is the code intellisense you get! Hit one key (ex t in my case) and BINGO, you’re looking at intellisense and you can poke around your variables.


There is ONE caveat to string interpolation! And that is you can’t mix output methods. Doing so will result in unexpected results.


Or going the other way around. I actually think the previous way is worse cause at least THIS way you get a compiler error. The previous way you likely won’t see anything is wrong at runtime (the text might be glossed over and you won’t see anything wrong).


So, apparently there are MANY ways to concatenate string (six by my counts so far LOL). But there is an easier way to use now, and a less error prone way. Now it’s time to grab ac coffee and get coding.

PS Before reading this blog, seriously, did you ever contemplate how many ways there were?


MSDN, $ - string interpolation (C# Reference) =

MSDN Magazine, C# : How C# 6.0 Simplifies, Clarifies and Condenses Your Code =

Location: Blogs Parent Separator TechTidBits

Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Add Comment   Cancel 
Copyright 1999-2012 by   Terms Of Use  Privacy Statement