Question about using '+'

Hi.
It’s a stupid problem but I don’t know the terminology to google it well I’m just screwing around in code and I noticed if I write Debug.Log(a + b + c) where a,b,c are just ints, I get the sum of them added together. But if I write Debug.Log(a + “Hello” + c) I get the individual value of a and c with the word Hello in the middle. Debug.Log((a) + (b) + (c)) gets me the same as Debug.Log(a + b + c). Like, I want it to concatenate, but it’s doing the operation. Is it possible to some how write out a line that forced the Log to print these individually? I don’t really have any use case or whatever, I’m just trying to learn the basics.

I did find this:Addition operators - + and += - C# reference | Microsoft Learn

So right after I submitted this, I thought of a workaround:
Debug.Log(a +" " + b +" "+c);

Is that the best way to do this if I wanted to?

Debug.Log(a + " " + b + " " + c); will do it for you.

1 Like

That may be because as only ints it defaults to adding them together, whereas the example with the string resorts to concatenating as a string.
You could also do:

Debug.LogFormat("{0} {1} {2}",a,b,c);
//or
Debug.Log(a + " " + b + " " +c);
1 Like

You could use LogFormat like @methos5k mentioned or a other good method that works everywhere is.

Debug.Log(string.Format("{0} {1} {2}", a, b, c));

You could also use ToString

Debug.Log(a.ToString() + b.ToString() + c.ToString());

Anyway, the key to understanding this is to understand how C# handles method overloads and implicit type casts.

For starters + is just a regular method. Its overloaded for several types (and you can overload it for your own types). In psuedo code the signature for int addition looks like this

+ (int a, int b) {
    return Math.Add(a,b);
}

And the signature for string addition looks like this

+ (string a, string b) {
    return String.Concatenate(a,b);
}

There is no signature to add a string to a int.

When you call an overloaded method C# first looks for an overload that matches the arguments exactly. If it can’t find an exact match, it looks for a overload that can be called with the least number of implicit casts.

So when you add two ints, it calls the int overload. When you add two strings, it calls the string overload. When you add an int and a string, it looks to find the lowest number of implicit casts. There is an implicit cast from int to string, but there is no implicit casts from string to int. Therefore C# resolves the method to the string overload.

1 Like