Search code examples
c#npoi

How can I make my decimal variable 0 if the parse fails?


I am using the NPOI lib to read an excel file and one column has a price that is not always set, when the cell is empty my code crashes so I am trying to see how I can make my variable 0 if the cell is empty or if the parse fails, whichever is the best way

my code is as follows

 decimal grossPrice = decimal.Parse(row.GetCell(10).ToString());

Solution

  • A bit depending on the C# version you are using you can use TryParse, which is also available vor int, float, etc.:

    decimal grossPrice = decimal.TryParse(row.GetCell(10).ToString(), out var val) ? 
                         val : your_default_value; //your_default_value = 0 in your case
    

    or

    decimal val = 0;
    if (decimal.TryParse(row.GetCell(10).ToString(), out val)
    {
       //value set
       //not needed, but handy for the completeness of this example
    }
    
    else
    {
       //value not set (error; assign default value to val)
       //not needed, but handy for the completeness of this example
    }