The difference between Convert and TryParse ASP.NET

by rBellantoni 9/16/2009 11:55:00 AM
The difference between Convert and TryParse is that Convert, is just int.Parse that checks for a null value and then converts it to 0. So a Convert will not break if it is passed a null it will however through a cast exception if a non-numeric character is passed in. TryParse however will not throw a cast exception, it returns an output variable with the successfully casted variable or default value (depending on the type, example: int.TryParse will return a 0 when it is not a valid number) the function also returns a boolean whether the string was parsed correctly or not. See the example code below:

if (int.TryParse(txtText1.Text, out testInteger) == false)

{

testInteger = 0;

}

Here we check to see if the try parse failed if it did we set the integer to 0, otherwise the parsed value is outputted right to the variable and no other code is required.

Tags:

Comments

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

About the author

Name of author Author name
Something about me and what I do.

E-mail me Send mail

Calendar

<<  November 2020  >>
MoTuWeThFrSaSu
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456

View posts in large calendar

Recent comments

Tags

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2020

Sign in