0

Is there a simpler way to add 3 strings together by parsing it as integers and then pass the resulting value to a string?

For example:

public string SumVal;
public string val_1;
public string val_2;
public string val_3;

void Start()
{
    SumVal = int.Parse(val_1) + int.Parse(val_2) + int.Parse(val_3);
}
5
  • this will give compilation error Commented Jun 24, 2020 at 8:11
  • based on this stackoverflow.com/questions/31711326/… there is no better way Commented Jun 24, 2020 at 8:14
  • String interpolation would go best I think Commented Jun 24, 2020 at 8:18
  • @NaveedYousaf define "best" (and also OP define "simplier") ... in readability? In maintainability? In being fail-safe? In performance/efficiency? ... ;) Commented Jun 24, 2020 at 8:34
  • @derHugo I guess performing alot of operations such as converting strings to ints and then back to string, it takes alot of processing power if the values are in 100. So I was looking for a simpler way without converting each string to int. Commented Jun 24, 2020 at 8:51

3 Answers 3

2

You have to take care of the case if the string is not convertible to int also otherwise it will give an exception (System.FormatException: 'Input string was not in a correct format.').

int x;
int y;
int z;
bool b = int.TryParse(val_1, out x);
int.TryParse(val_2, out y);
int.TryParse(val_3, out z);

SumVal = (x + y + z).ToString();

You can check for the return bool variable if it's false` then you can handle the case accordingly

Sign up to request clarification or add additional context in comments.

4 Comments

Where are you taking care of it? ;-)
because the default value of int is 0 so it will give you 0, but again that wont be a perfect solution
So maybe you should at least throw a warning if(!int.TryParse(val_2, out var y) { Debug.LogWarning($"Could not parse Y with input \"{val_2}\""); }
...or better build it robust and clean which includes educating OP how to do so ;-)
1

Use string interpolation

SumVal = $"{int.Parse(val_1)+int.Parse(val_2)+int.Parse(val_3)}";

Comments

0

Ah it did not come to me that I can add all the three values inside a bracket and pass it to ToString(). But looks like it cannot be more simpler than this.

SumVal = (int.Parse(val_1) + int.Parse(val_2) + int.Parse(val_3)).ToString();

1 Comment

This will only work if your val_1, val_2 and val_3 always contain integer values. If one of them is not an integer you get a System.FormatException.