Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 566
  • Last Modified:

conerting string to long

for the following piece of code:
long Priority = Convert.ToInt64(IsPdto.Priority);

I want to make sure that I do not get a runtime error, in case IsPdto.Priority is not a number in string format. How can I make sure that I do not perform this operation if it is not convertible to int?
0
vivekj2004
Asked:
vivekj2004
1 Solution
 
MisbahCommented:
you need to use long.TryParse method


long Priority = 0;
bool isCorrect = long.TryParse(IsPdto.Priority, out Priority);
if(isCorrect)
{
// 
}

Open in new window

0
 
sshullCommented:
If you want, you could put it in a try catch and ignore the error. For example:

try
{
long Priority = Convert.ToInt64(IsPdto.Priority);
}
catch
{
}

Since the error is handled by the code (even though it doesn't do anything), a runtime error won't occur. If you want you can even generate your own error message in your catch statement if it's a field that must be a valid numeric or you can set Priority to 0 if the field doesn't matter.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now