You're right about the try/catch being a big performance hit for converting
strings to int but the hit mostly comes in the catch. If all works well, it
is pretty fast.
So then the issue, as I see it, is that if you're going to respond to the
user and wait for user action or do nothing because the data is bad then
this hit isn't as significant and you could choose to live with it. If
you're going to handle it yourself in code, such as assigning 0 as a
default, and then continue processing, the overhead of catching the error is
significant and easily noticible.
Your ConvertToInt method fails because if stringNumber is not really
numeric, it will still throw an exception. The second example is still just
a try/catch.
In reality, I think many developers tend to use the try/catch even though it
really is a bad idea in most cases. I don't see any C# code around that has
a method for evaluating a string to see if it can be converted to a numeric
value.
Visual Basic.NET has the IsNumeric method that fills the bill and if Ersin
is developing in VB.NET, that is the solution.
In C#, only the Double structure has some handling for bad numbers in the
form of Double.TryParse() which will return false if the conversion fails.
Look at this link from Microsoft to see how to emulate IsNumeric in C# with
the TryParse method:
http://support.microsoft.com/default.aspx?scid=kb;en-us;329488
Alternatively, a google search on regex AND isnumeric will return a lot of
different ways to validate the string with a regular expression but then you
still have to do the conversion.
Hope this helps,
Dale Preston
MCAD, MCSE, MCDBA