Reputation: 475
I have a problem getting a long value safely from indexer. Following code works OK until the value I want is null. Then the indexer returns empty string and my code throws an exception.
long TargetID = 0;
object _targetID = CurrentData[TargetIDKey];
if (_targetID !=null && (Convert.ToInt64(_targetID)) > 0)
TargetID = Convert.ToInt64(_targetID);
else
TargetID = -1;
How do I fix this so instead of exception I go to the else clause?
Upvotes: 0
Views: 22
Reputation: 32286
You could use long.TryParse
instead.
long targetID;
if(_targetID == null || !long.TryParse(_targetID.ToString(), out targetID))
targetID = -1;
Upvotes: 2