tbaseflug
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?
Convert.ToInt32(orgValue);
What is the best way to overcome this?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Personal preference:
int orgValueAsInt;
if (!Int.TryParse((orgValue as string), out orgValueAsInt)
{
//Parse Failed. Assign orgValueAsInt a default value?
orgValueAsInt = -1;
}
int orgValueAsInt;
if (!Int.TryParse((orgValue as string), out orgValueAsInt)
{
//Parse Failed. Assign orgValueAsInt a default value?
orgValueAsInt = -1;
}
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 ;)
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 :)
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
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.
Article does show that the new try parse is much faster if there are conversions that will fail.
int newValue = (orgValue== null) ? 0 : Convert.ToInt32(orgValue);