Coding Better - Example #204
IMO it's all about the willingness to try new things. I used to concatenate short strings using the plus + sign. Thankfully C# offers a much cleaner way to perform simple string concatenation. String has a Format method. Check it out...
OldHyperLink.NavigateUrl =
"~/Sweethearts.aspx?hisId="
+ person.hisId.ToString()
+ "&herId="
+ person.herId.ToString();
NewHyperLink.NavigateUrl =
string.Format("~/Sweethearts.aspx?hisId={0}&herId={1}",
person.hisId, person.herId);
Which do you think is easier (both to look at and code)? The second way is much cleaner because it allows me to write the string plain and simple. Moreover, my example uses just two values. Think of all the times when there are many more string pieces to sew together. The plus sign quickly makes the code messy and harder to conceptualize. If you don't believe me, just look at whatever VBScript or Java code is nearby. You'll no doubt find liberal use of & and + in string concatenation.
Note: I used more line breaks than I normally would due to the layout of this blog.