If only life were as simple as the others have suggested. Unless you
want exceptions thrown left and right every other time you attempt
this, you need something like the following - even this is incomlete
since it returns 0 for 3 cases where the string isn't an integer (you
may want exceptions in those cases):
internal static int StringToInt(string MyString)
{
if (MyString == null)
//default null to 0 - this may or may not be what you want !
return 0;
MyString = MyString.Trim();
double dValue=0;
if (double.TryParse(MyString, NumberStyles.Any,
CultureInfo.CurrentCulture, out dValue))
if (dValue <= int.MaxValue && dValue >=
int.MinValue)
return (int)(System.Math.Round(dValue));
else
//return 0 if out of range - this may not be what you
want!
return 0;
else
//return 0 if not a number - this may not be what you want!
return 0;
}