Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using string.Format for simple things?

In my early .Net programming days, I used string.Format() only for complex string concatenations, for example to compile strings as

Problem with customer order 234 of date 2/2/2002 and payment id 55543.

But now I use string.Format for almost every string concatenation I have to do, also simple ones such as prefixing a string with something.

Console.WriteLine(string.Format("\t\t{0}", myString));

Is there any possible overhead on this? Maybe I should use the regular + operator to do these simple operations?

What's your opinion on this?

like image 232
Gerrie Schenck Avatar asked Dec 28 '22 22:12

Gerrie Schenck


2 Answers

For simple string concatenations use the + approach. It is clearer for simple things that don't require a format.

For more complex strings that have a certain format and where it is useful to retain the structure of the entire string and provide a placeholder for the input, use String.Format.

And yes, there is an overhead. String.Format uses a StringBuilder underneath the covers. Simple string concatenations will be much quicker in those scenarios. A couple of benchmarks and blog posts on this topic can be found quite easily. Of course it all depends on your usage. If small string concats are occurring in a loop then repeated usage of String.Format will likely be more noticeable than a straightforward + concat. If you are building up a large string in a loop then the classic example is to prefer StringBuilder and related questions on concat versus StringBuilder can be found on SO.

EDIT: To clarify, this serves little purpose: String.Format("{0}{1}", a, b) since there is not much formatting. It's simply a + b. Unfortunately I've come across such examples in production code and as soon as I see String.Format I expect to see something that needs to be structured a certain way, not a straightforward concat.

OTOH, consider this phone number: "(" + area + ") " + number + " x" + extension - there's too much going on and it's not easy to modify. In this case a String.Format is preferable: String.Format("({0}) {1} x{2}", area, number, extension). This is still a trivial example but you get the idea.

like image 55
Ahmad Mageed Avatar answered Jan 11 '23 16:01

Ahmad Mageed


I also tend to use string.Format on most operation which need two or more strings/values to be combined as it produces easier to read code than starting and stopping strings with +'s in the middle.

To expand

string value = string.Format("Hello {0}", user.username);

is much more readable and expandable than

string value = "Hello" + user.username

for instance if you wanted to add the last login date as a system upgrade, you could simply expand the code to the following

string value = string.Format("Hello {0}, you last logged in {1}", user.username, user.lastLogin);
like image 37
GaryDevenay Avatar answered Jan 11 '23 17:01

GaryDevenay