How to ask if a string variable can be parsed to an int variable?

What I can use will return a boolean variable that will indicate if I can safely parse the string or not?

1847 will return true 18o2 will return false

And please, nothing complicated ...

+3


source to share


5 answers


You can use int.TryParse

int result = 0;
bool success = int.TryParse("123", out result);

      



Here, success will be true if it is processed successfully, and false the other is wise and the result will be parse int.

+2


source


Use int.TryParse

:



int i;
bool canBeParsed = int.TryParse("1847", out i);
if(canBeParsed)
{
    Console.Write("Number is: " + i);
}

      

+2


source


var str = "18o2"
int num = 0;

bool canBeParsed = Int32.TryParse(str, out num);

      

+2


source


You should take a look at TryParse method

+1


source


I have been using these extension methods for years. Maybe a little more "complicated" in the beginning, but their use is very simple. You can expand the most simple types of values, including Int16

, Int64

, Boolean

, DateTime

and so on, using the same template.

using System;

namespace MyLibrary
{
    public static class StringExtensions
    {
        public static Int32? AsInt32(this string s)
        {
            Int32 result;       
            return Int32.TryParse(s, out result) ? result : (Int32?)null;
        }

        public static bool IsInt32(this string s)
        {
            return s.AsInt32().HasValue;
        }

        public static Int32 ToInt32(this string s)
        {
            return Int32.Parse(s);
        }
    }
}

      

To use them, simply include MyLibrary

in the list of namespaces with a declaration using

.

"1847".IsInt32(); // true
"18o2".IsInt32(); // false

var a = "1847".AsInt32();
a.HasValue; //true

var b = "18o2".AsInt32();
b.HasValue; // false;

"18o2".ToInt32(); // with throw an exception since it can't be parsed.

      

+1


source







All Articles