Wednesday, 3 September 2014

C# When to use convert and tryparse





When converting values in C#, we have three options : ParseConvert, and TryParse. My suggestion would be to use which method based on where the conversion is taking place. If you are validating input, an int parse or a convert will allow you to give specific error messages.
I am giving you a short example of int.TryParse:-

  internal class Program
    {
        public static void Main(string[] args)
        {
            string str = "";
            int intStr;
            if (int.TryParse(str, out intStr))
            {
                Console.WriteLine(intStr);
            }
           else
            {
                Console.WriteLine("Input is not in integer format");
            }
            Console.ReadLine();
        }
    }



In above Program str is not a integer. Whenever we use int.TryParse it returns boolean value.
First of all it validate your string. If your string is integer it returns True else False.
int.TryParse contain two arguments first is string and another is int(out type). If the input string is integer it returns 2nd arguments(out type int). Else it returns first argument(string).





untitled.JPG 

Convert:



Convert.ToInt32(string s) method converts the specified string representation of 32-bit signed integer equivalent. This calls in turn Int32.Parse () method. When s is a null reference, it will return 0 rather than throw ArgumentNullException. If s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException. For example:

   try
        {
            Convert.ToInt32(value);
        }
        catch(FormatException)
        {
            //If we can't parse the string
        }
        catch (OverflowException)
        {
            //If the string is outside the possible integer values
        }






Int32.TryParse(string, out int)
Int32.Parse(string, out int) method converts the specified string representation of 32-bit signed integer equivalent to out variable, and returns true if it is parsed successfully, false otherwise. This method is available in C# 2.0. When s is a null reference, it will return 0 rather than throw ArgumentNullException. If s is other than an integer value, the out variable will have 0 rather than FormatException. When s represents a number less than MinValue or greater than MaxValue, the out variable will have 0 rather than OverflowException

     
int number;
bool result = int.TryParse(value, out number);
 
if (result)
{
    //We now have our converted integer.
}
else
{
    //Something went wrong with the conversion. Our number variable will be equal to zero.
}


Summary

We used the int.TryParse method in a C# program. This method is ideal for parsing strings into numbers, when the strings may not be valid or may contain erroneous characters. The method returns true if it succeeds, and false if it doesn't.





No comments:

Post a Comment