2

I am coding in Unity3D in C#, and when printing or using debug statements or console statements, I have always used something like this:

Debug.Log("The sum of these two variables is :" + SumOfVariables);

However, I am going through a new book to try and learn to be a better programmer, and they often use this instead:

Debug.Log("The sum of these two variables is {0}", SumOfVariables);

I assume it doesnt matter either way, but is there an advantage of using the later? Also, for anyone that uses unity, I am getting an error message when I try to use it that way, but it works fine when I use the first method. It says basically that Debug.Log doesnt have a parameter for that. And also that I cant convert a string expression to type UnityEngine.Object. The variable I am using is a String Property of a class.

My question is less about the unity peice and more about which is better. But for extra credit if you want to tell me why I get that error that would be great. I am sure this has been asked before, but I was getting all kinds of different topics when I tried to search, so I apologize in advance, thanks for answering!!

MAV
  • 7,260
  • 4
  • 30
  • 47
Mike Davis
  • 49
  • 1
  • 7

5 Answers5

4

The reason why you should use format strings instead of string concatenation is because it makes localization possible. It's easy to translate a format string into a different language, but it's harder to rewrite code.

"{0}: invalid photoscamp (id={1}) inside flange"

In pig latin,

"{0}: invaliday otoscamphay (iday={1}) insidea angeflay"

There are also other reasons to use format strings, such as performance, code readability, and the ability to store format strings in a file or database. See C# String output: format or concat? and Why use String.Format?.

Community
  • 1
  • 1
Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
3

It makes it easier to repeat variables when using the format string {} version.

Additionally, it makes it easy to read the string as one item, with the placeholders and to add placeholders (just tack another {} with the right index and throw another parameter in).

Format strings in general tend to be easier to read and to change later on.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • So lets say I have like 5 variables, I could say this? Print("variable one is {0} and variable two is {1} and..", variable1, variable2); etc, etc? – Mike Davis May 19 '13 at 19:57
  • 1
    @MikeDavis: exactly. You could also do `"Variables are {0},{1},{2} and in reverse order {2},{1},{0}"`. That is to say you can reuse them if you want to and put them in whatever order you want. – Chris May 19 '13 at 20:01
  • Wow, that does seem better. I will try to do more research to see why I am getting an error message as this seems to be the better way to go. Thanks very much. – Mike Davis May 19 '13 at 20:02
0

It's just a different type of string interpolation. Mostly it's just for cosmetic reasons, but some find the brackets easier to use as well

anomaaly
  • 833
  • 4
  • 15
0

Have a look at the signature for the Debug.Log method. The second version will have something like:

string format, params object[] p

So the first parameter is the format and the "second" parameter is actually a variable number of parameters which represent the replacements in the format string.

The second one is preferred from a code maintenance perspective - it's easier to read the intent of the code and to modify later - thus better than concatenating strings.

So to answer your question as to why it doesn't work the second way, it's likely that there is no overload of Debug.Log that takes a format string as the first parameter. For other logging frameworks, (and, for example, Debug.WriteLine) there will commonly be a format parameter.

Craig Shearer
  • 14,222
  • 19
  • 64
  • 95
0

One important advantage of the {} mechanism over the simple concatenation is one of separation of concerns. Thing about this problem from an abstract point of view: here you have a number of data elements, which need to combined in a sequence to compose a piece of text.

With the concatenation method, the exact rules by which of the data elements are to be combined is pretty much fixed in code. With the {} mechanism, the list of components that need to be combined is still fixed in code - which is Ok because the datum list usually depends only on the program's logic. However, the exact nature of that composition is isolated in a single string, which means it can be easily controlled and adapted based on user preferences or other environment factors without changing the logic.

That sounds very obscure and theoretical, but it's not. By far, the most common use of this power is "localization". By storing different versions of the pattern string for different languages or "cultures", you can easily produce messages that are grammatically correct on any language of your choice, based perhaps on a user option. Doing the same thing by the concatenation method is nearly impossible except for the simplest cases (if nothing else because you can't change the order of the elements at runtime).

It's not the only possibility: you could have a multi-client system that produces different messages based on the needs of each different client. Or perhaps a system that composes a complex detailed error message for a technically sophisticated user (say, a specialist who works for your company's technical support) and a much simpler one when the user is a casual user (say, a customer).

Euro Micelli
  • 33,285
  • 8
  • 51
  • 70