Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Easy way to avoid string addition in C#

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading