Monday 9 June 2008

Using TryParse() in C#

When we are validating integer input, usually from a textbox, we need to make sure that the text is a valid integer before we set the properties in our class.

We would normally have done this using the following type of code:

try
{
SomeInt = Convert.ToInt32(tbSomeInt.Text);
}
catch (Exception ex)
{
MessageBox.Show("Some int must be a valid integer");
return;
}

By using a try catch in this manner we add quite a bit of overhead to the work that the .Net framework has to do for us. We can use the TryParse() method to get round this.

int intSomeInt;
if (int.TryParse(tbSomeInt.Text, out intSomeInt) == true)
{
//if the conversion succeded
csSomeClass._SomeInt= intSomeInt;
}
else
{
MessageBox.Show("Some int must be a valid integer");
return;
}

This avoids the overhead of using the try and will run faster. Please note that you cannot use a class property in the out parameter of the method and must use a variable as above.

Here is a link to another blog that I found useful.

No comments:

Free Hit Counter