Parsing/Converting String as INTEGER using C#

Parsing/Converting String as INT using C#

In this blog, we are going to parse the string to specific INT data Type.

Usage:

int a = TryParseInt("234", int.MinValue);//TRUE

int b = TryParseInt("2B4", int.MinValue);//False

Response.Write(string.Format("A:{0},B:{1}", a, b)+"<br/>");

 

OUTPUT:

A:234,B:-2147483648

 

Method1: int.TryParse

Best to use if there is uncertain about the input string.

     

 /// 
        /// Parses the string as Int.
        /// It wont throw error. Instead it gives the ifFail value if error occurs
        /// 
        public int TryParseInt(string input, int ifFail)
        {
            int output;
 
            if (int.TryParse(input, out output))
            {
                output = output;
            }
            else
            {
                output = ifFail;
            }
 
            return output;
        }

 

Method 2: int.Parse

If you sure about the input string going to be valid, then go for this method.

         /// 
        /// Parses the string as Int. But if Int string is invalid, then it throws error
        /// 
        public int ParseInt(string input)
        {
            return int.Parse(input);
        }

Thanks for reading this article. Have a nice day.

Ebook Download
View all
Learn
View all