HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Cleanest way to place values into strings

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
intoplacewaycleanestvaluesstrings

Problem

I am trying to standardize the way I write code. Which is the best way to place the values into a string, method 1 or 2?

string myCat = "persian";

// Method 1
Console.WriteLine("I have a wild {0} cat that likes to visit", myCat);

// Method 2
Console.WriteLine("I have a wild " + myCat + " cat that likes to visit");


I would like to point out that I am intending this for simple uses, where StringBuilder would be overkill.

Solution

For simple straightforward string concatenation like your "persian" cat example, I agree with @Malachi - being slightly memory-inefficient over a few bytes will not hurt anyone, and if there's a gain in readability then it's worth it.

However, since you're looking to standardize the way you're doing string concatenations, you should go with string.Format() all the way, without hesitation*.

Say you're writing a program for some petshop (say, one that only sells cats), you'll potentially want to format/concatenate the cat's breed, birthdate/age and price tag. With string + string your only option is essentially to hard-code the date and currency formats, while this:

string.Format("{0} cat, born {1:d} ({2} weeks) | {3:C2}", cat.Breed, 
                                                          cat.BirthDate, 
                                                          cat.AgeInWeeks, 
                                                          cat.Price)


...has an obvious advantage, especially when you consider that

"{0} cat, born {1:d} ({2} weeks) | {3:C2}"


is a string all by itself (as mentioned by Daniel Cook).

*At the end of the day, common sense should prevail. If you end up doing this:

var result = string.Format("{0}{1}", string1, string2);


...then you know you've gone overboard.

Code Snippets

string.Format("{0} cat, born {1:d} ({2} weeks) | {3:C2}", cat.Breed, 
                                                          cat.BirthDate, 
                                                          cat.AgeInWeeks, 
                                                          cat.Price)
"{0} cat, born {1:d} ({2} weeks) | {3:C2}"
var result = string.Format("{0}{1}", string1, string2);

Context

StackExchange Code Review Q#33952, answer score: 11

Revisions (0)

No revisions yet.