I have couple of string variables that sometimes have text and other times have integers in them. I have a function Add() where I add all the variables when they are integers. Problem is how do I avoid any variable when they are string? Example:
string a = "2";
string b = "3";
string c = "10";
string d = "jk";
string e = "zu";
string f = "15";
public void Add(){
int total = int.Parse(a) + int.Parse(b) + int.Parse(c) + int.Parse(d) + int.Parse(e) + int.Parse(f);
}
Obviously the above code will fail because d and e are string, what I am looking for is it should avoid adding d and e strings and the total should be 30. I can check if the string is an integer or a text but that would take forever if the script I am working on does not have strings as an array.
What is the right and easy way to do this?
>Solution :
If you want to use spesific variables, you can code this use case like this
void Add()
{
int aInt, bInt, cInt, dInt, eInt, fInt;
int.TryParse(a, out aInt);
int.TryParse(b, out bInt);
int.TryParse(c, out cInt);
int.TryParse(d, out dInt);
int.TryParse(e, out eInt);
int.TryParse(f, out fInt);
int total = aInt + bInt + cInt + dInt + eInt + fInt;
}
If you want to use more extendible code, you should use collection
void Add()
{
int total = 0;
foreach (var c in myStrCollection)
{
int.TryParse(c, out int a);
total += a;
}
}
int.TryParse will try to convert the string to int. If it cannot convert, variable a will be 0 as default. 0 is ineffective element for addition. If this method is multiplication, you should change the method like this.
void Multiply()
{
int total = 0;
foreach (var c in myStrCollection)
{
bool s = int.TryParse(c, out int a);
if(!s) a = 1;
total *= a;
}
}