How to ask if a string variable can be parsed to an int variable?
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.
source to share
Use int.TryParse
:
int i;
bool canBeParsed = int.TryParse("1847", out i);
if(canBeParsed)
{
Console.Write("Number is: " + i);
}
source to share
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.
source to share