How to convert empty string in int32?

c# html-agility-pack

Question

I'm working on software that extracts information from html tables. this sentence:

team.SelectSingleNode(".//td[@class='number total won total_won']")?.InnerText.Trim();

returns: ""

(I am manipulating the DOM using the HTML Agility Pack.)

The whole line reads as follows:

Convert.ToInt32(
  team.SelectSingleNode(
    ".//td[@class='number total won total_won']")
  ?.InnerText.Trim());

This throws an error (incorrect format exception).

Have a solution for this?

1
-2
10/13/2017 5:33:20 PM

Accepted Answer

You may utilizeint.TryParse in place ofConvert.ToInt32

int myInt;
if(!int.TryParse(team.SelectSingleNode(".//td[@class='number total won total_won']")?.InnerText.Trim(), out myInt))
{
  myInt = 0;
}

I know, but I've 30+ lines of code, so I should add a lot of if conditions... – Ilnumerouno just now

Instead, you may create a helper method.

public static class Converter{
    public static int ConvertToInt(string stringAsInt){
      int myInt;
      return int.TryParse(stringAsInt, out myInt) ? myInt : 0;
    }
}

executing code.

var parsedInt = Converter.ConvertToInt(team.SelectSingleNode(".//td[@class='number total won total_won']")?.InnerText.Trim());
3
10/13/2017 2:53:30 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow