What's the best way to do the equivalent of int.TryParse (which is found in .net 2.0 onwards) using .net 1.1.
What's the best alternative to int.TryParse for .net 1.1
Obviously,
class Int32Util
{
public static bool TryParse(string value, out int result)
{
result = 0;
try
{
result = Int32.Parse(value);
return true;
}
catch(FormatException)
{
return false;
}
catch(OverflowException)
{
return false;
}
}
}
@Pondidum: Good call! Thanks. –
Swanskin
try
{
var i = int.Parse(value);
}
catch(FormatException ex)
{
Console.WriteLine("Invalid format.");
}
Doesn't the exception throwing/handling create a fair bit of overhead though? –
Ardenia
Koistya almost had it. No var command in .NET 1.1.
If I may be so bold:
try
{
int i = int.Parse(value);
}
catch(FormatException ex)
{
Console.WriteLine("Invalid format.");
}
There is a tryparse for double, so if you use that, choose the "NumberStyles.Integer" option and check that the resulting double is within the boundaries of Int32, you can determine if you string is an integer without throwing an exception.
hope this helps, jamie
private bool TryIntParse(string txt)
{
try
{
double dblOut = 0;
if (double.TryParse(txt, System.Globalization.NumberStyles.Integer
, System.Globalization.CultureInfo.CurrentCulture, out dblOut))
{
// determined its an int, now check if its within the Int32 max min
return dblOut > Int32.MinValue && dblOut < Int32.MaxValue;
}
else
{
return false;
}
}
catch(Exception ex)
{
throw ex;
}
}
© 2022 - 2024 — McMap. All rights reserved.
return True
somewhere in that? – Ramsey