Parse vs TryParse vs ConvertTo in C#

Home Forums General Programming C# Parse vs TryParse vs ConvertTo in C#

Tagged: , ,

This topic contains 2 replies, has 3 voices, and was last updated by  Ankur 3 years, 4 months ago.

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #5009

    Pavan
    Moderator

    I am developing c# window application then i find these 3 parsing keywords but i am unable to find who is best and where to use?
    Please provide me detail with performance wise so i can enhance my application and speed up.

    #5065

    In the below I am explaining you in the context of integer.

    Suppose you have the string ‘i’ and you use the Int32.Parse method converts the string ‘i’ then the following results will be:

    When i is a null reference, it will throw ArgumentNullException.
    If i is other than integer value, it will throw FormatException.
    When i represents a number less than MinValue or greater than MaxValue, it will throw OverflowException.

    And now I use the Convert.ToInt32 method then the following results will be:
    When ‘i’ is a null reference, it will return 0 rather than throw ArgumentNullException.
    If ‘i’ is other than integer value, it will throw FormatException.
    When ‘i’ represents a number less than MinValue or greater than MaxValue, it will throw OverflowException.

    When I use the TryParse method then the results will be:
    When ‘i’ is a null reference, it will return 0 rather than throw ArgumentNullException.
    If ‘i’ is other than an integer value, the out variable will have 0 rather than FormatException.
    When ‘i’ represents a number less than MinValue or greater than MaxValue, the out variable will have 0 rather than OverflowException.

    thanks

    #5066

    Ankur
    Moderator

    So Should we use TryParse in every scenario to parse a value in Int to prevent any exception ?

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.