This just shows the difference in the way the 3 functions behave. To be truly informative, the article should have mentioned some situations where one of the methods should be preferred over another.



Message Closed



thank you.



Informa��o extremamente �til

ultra useful

=)



Simple and well written



Nice work man. learn the difference and there is miner spelling mistake(just ignore this).



anyway keep up the good work.



Thilina Chandima wrote: there is miner spelling mistake

You mean like this? minor not miner

Failure is not an option; it's the default selection.



Good example for beginers



This is misleading. The C# team rewrote the convert class and later added the .tryparse to overcome coraling developers into exception handling. The .TryParse method is the superoir solution.



If you expect the conversion to succeed most of the time, and fail only in exceptional cases, than using Int32.Parse inside a try/catch block might be a better approach: cleaner, and possibly faster (because most of the time you don run into an exception).



If you expect the conversion to fail fairly often, than you might go with a TryParse approach.



Remember: Exceptions are not your enemy. Learn how to leverage them to your benefit.



Nothing to see here.



I agree with concluding that TryParse is generally the best choice, but I would never choose Convert over Parse. Nearly the whole Convert class is pointless.



Other than that, I see little point in the article.



This is a good crib sheet of what exceptions are thrown for various pieces of invalid input to a variety of methods that do a similar job. It could, however, do with a little tidy up. Could you add some section headers to it?



In your article you say: Convert.ToInt32 is better than Int32.Parse, since it return 0 rather than exception. But,again according to the requirement this can be used. TryParse will be best since it handles exception itself always.



Why is that better? Does TryParse even generate an Exception internally that it handles on your behalf?



Why is it better that Convert.ToInt32 returns a 0 instead of an exception. What happens if the valid range of values I'm trying to parse includes zero? How do I tell the difference between something that converted correctly and something that did not in that instance?



* Developer Day Scotland 2 - Free community conference

* The Blog of Colin Angus Mackay



Vogon Building and Loan advise that your planet is at risk if you do not keep up repayments on any mortgage secured upon it. Please remember that the force of gravity can go up as well as down.



Colin Angus Mackay wrote: Why is it better that Convert.ToInt32 returns a 0 instead of an exception.



There are advantages to having an integer-conversion method that will never throw an exception. I don't see an advantage to having one that throws an exception in every invalid case except when the input parameter is a null reference (note that Convert.ToInt32 will throw an exception on an empty string).



Incidentally, at least in Basic there are a couple of other ways of converting numbers: Val and CInt. These are willing to accept more input formats than the other methods, but they have different semantics for conversion. For example: val("&hFF00")=-256.0 val("&hFF00&")=65280.0 cint("&hFF00")=65280 cint("&hFF00&") -> Exception (invalid cast) val("&hFF000000")=-16777216.0 cint("&hFF000000") -> Exception (overflow) val("&h1FF000000")=8573157376.0 val("&h0FF000000")=-16777216.0 val("&h0FF000000&")=-16777216 (grr....) val("1z9")=1 cint("1z9") -> Exception (invalid cast) val("1.46E1")=14.6 cint("1.46E1")=15 val("1e9999") -> Exception (overflow) cint("1e9999") -> Exception (overflow)



I don't think C# has any equivalent of Val, but I think an equivalent to CInt exists as a type-casting operator. Too bad there's no "try" version of it.



supercat9 wrote: I don't see an advantage to having one that throws an exception in every invalid case except when the input parameter is a null reference (note that Convert.ToInt32 will throw an exception on an empty string).



You now appear to be contradicting yourself. You said in the article "Convert.ToInt32 is better than Int32.Parse, since it return 0 rather than exception".





supercat9 wrote: Val and CInt. These are willing to accept more input formats than the other methods



But you can also get that out of Int32.TryParse[^] Int32.Parse[^] Convert.ToInt32[^].



You still have not answered why it is better that no exception is thrown?



* Developer Day Scotland 2 - Free community conference

* The Blog of Colin Angus Mackay



Vogon Building and Loan advise that your planet is at risk if you do not keep up repayments on any mortgage secured upon it. Please remember that the force of gravity can go up as well as down.

modified on Tuesday, January 27, 2009 5:27 PM







You still have not answered why it is better that no exception is thrown?



There are times when it is best for a failure to return an exception; there are other times when it is better for it not to. It's cleaner to say: If Not Integer.TryParse(SomeString, IntVar) Then IntVar = DefaultValue End If than Try IntVar = Integer.Parse(SomeString) Catch Ex As FormatException IntVar = DefaultValue Catch Ex As OverflowException IntVar = DefaultValue Catch Ex As NullReferenceException IntVar = DefaultValue End Try

The former approach is clear: if the conversion works, use it; if not, use the default value. The latter approach is a lot bulkier; worse, it requires that one enumerate all the exceptions one wants to handle. If the some particular input will cause the Parse method to throw an unanticipated exception, the program will die. Catching a generic Exception would avoid that problem, but would run the risk that real exceptions like "out of memory" might go unhandled.



supercat9 wrote: I didn't write the original article.



Oops! My bad!



* Developer Day Scotland 2 - Free community conference

* The Blog of Colin Angus Mackay



Vogon Building and Loan advise that your planet is at risk if you do not keep up repayments on any mortgage secured upon it. Please remember that the force of gravity can go up as well as down.



System.Exception catch block. Moreover, the exception handler can identify and classify exceptions that derive from System.Exception by their derived type. For example, in my AppExceptionLogger class, there is a private method, ReformatExceptionMessage , which formats specific types of exceptions in ways not supported by their native Message properties.



Its first argument is an Exception . As always, Exception can be either a true System.Exception or an object that derives from System.Exception . The second executable statement calls the GetType ( ) method on the Exception, and stores the value of the FullName from the returned system.Type object into a string, which is the index into a Dictionary<string, string=""> of prefixes to be stripped from the beginning of the Message property of the supplied Exception object; the remainder of the string is retained, and becomes part of the final message that gets displayed and/or recorded.



private static string ReformatExceptionMessage ( Exception pexAnyKind , string pstrRoutineLabel , string pstrMessageTemplate ) { const string MESSAGE_PADDING = @" {0} " ; string strRawMsg = pexAnyKind.Message; string strExceptionTypeName = pexAnyKind.GetType ( ).FullName; string strTrimStartPoint = GetMessageTruncationStart ( strExceptionTypeName ); string strTrimmedMsg = null ; if ( string .IsNullOrEmpty ( strTrimStartPoint ) ) strTrimmedMsg = strRawMsg; else if ( strRawMsg.IndexOf ( strTrimStartPoint ) == MagicNumbers.STRING_INDEXOF_NOT_FOUND ) strTrimmedMsg = strRawMsg; else strTrimmedMsg = strRawMsg.Substring ( MagicNumbers.STRING_SUBSTR_BEGINNING , strRawMsg.IndexOf ( strTrimStartPoint ) ); return string .Format ( pstrMessageTemplate , new string [ ] { strExceptionTypeName , pstrRoutineLabel , WizardWrx.StringTricks.ReplaceToken ( strTrimmedMsg , Environment.NewLine , string .Format ( MESSAGE_PADDING , Environment.NewLine ) ) , Environment.NewLine } );

