Link to home
Start Free TrialLog in
Avatar of tbaseflug
tbaseflugFlag for United States of America

asked on

Null check on Convert.ToInt32

I am getting a null expection on
Convert.ToInt32(orgValue);
What is the best way to overcome this?
ASKER CERTIFIED SOLUTION
Avatar of xbrady
xbrady

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Agree with xbrady. I'm posting an practical example how you can use it in case you are unsure:

int newValue = (orgValue== null) ? 0 : Convert.ToInt32(orgValue);
Personal preference:

int orgValueAsInt;
if (!Int.TryParse((orgValue as string), out orgValueAsInt)
{
//Parse Failed.  Assign orgValueAsInt a default value?
orgValueAsInt = -1;
}
Avatar of OblivionSY
OblivionSY

ppittle's TryParse is the ideal option, it's what it is made for :)
Or use the null coalescing operator:

Convert.ToInt32(orgValue ?? 0);

https://www.experts-exchange.com/Programming/Languages/C_Sharp/Q__24398343.html

So pretty ;)
or "0" or whichever, you get the point :)
Avatar of Obadiah Christopher
On second thoughts

doesn't Convert handle nulls by itself? That's why it is recommended to use Convert instead of int.Parse?

http://anuviswan.blogspot.com/2006/03/intparse-vs-converttoint32.html

http://blogs.msdn.com/ianhu/archive/2005/12/19/505702.aspx
It does say that, yes, MSDN would seem to support that too, interesting - What is the Type of orgValue in Convert.ToInt32(orgValue);?

Article does show that the new try parse is much faster if there are conversions that will fail.