Search code examples
c#.netstringmathconverters

Convert string to INT in C# (When String is 'E0305' To convert INT is not Work


I want to convert string to int but some time is not working.

Here is my code:

public static int ToInt(String pStr)
{
     return Convert.ToInt32(Microsoft.VisualBasic.Conversion.Val(pStr));
}

Int i = ToInt("F0005");

Output is 0 - it works fine.

But when I pass in a value like this

Int i = ToInt("E0305");

Then I get an error "Out-of-range exception".

I have a mix of values, some are int and some are strings; I want to pass each and every value in loop and convert it to int, but when I pass this value then I get an error.


Solution

  • If you just want to skip invalid string value, it is better to use TryParse instead of returning 0 (which might be valid value). At your calling code it should look like this:

    string val = "F0005";
    if (int.TryParse(val, out int i) {
       // parse success. you can use i here
    }
    else {
       // parse failed. 
    }
    

    If you really want it to be 0, this should work

    string val = "F0005";
    int i = int.TryParse(val, out int x) ? x : 0;