None of the search results for this are from stackoverflow, and many mention Cint() which 'does not exist in the current context'
Is int.Parse(String) the preferred method?
None of the search results for this are from stackoverflow, and many mention Cint() which 'does not exist in the current context'
Is int.Parse(String) the preferred method?
I would use: int.TryParse because then you dont need to trap errors.
Other ways: int.Parse
Third way: Convert.ToInt32
int.Parse is the preferred method if you're sure that the string can be converted, otherwise use int.TryParse.
The CInt function is from classic ASP. In .NET you could do any of the following:
int.TryParse()
int.Parse()
Convert.ToInt32()
TryParse is probably the safest option though, especially if you are parsing user input.
int.TryParse is generally a better bet than int.Parse. If you have the following code, you'll get an exception:
string myInt = "a1";
int value = int.Parse(myInt);
Pre .NET 2, you had to wrap this in a try/catch block to handle cases where there could be failures. With the advent of .NET 2, TryParse was introduced which gives you the following:
int returnValue;
if (!int.TryParse("a1", out returnValue))
{
Console.WriteLine("a1 is not a valid integer");
}
int.TryParse is better way because int.Parse works like: check int.TryParse, if no throw exception (you can check that by reflector).
Also you can write extension method for string like this:
static class StringExtension
{
public static int? ToNullableInt(this String str)
{
int result;
if (int.TryParse(str, out result))
{
return result;
}
return null;
}
}
Usage:
string s = "123";
int? i = s.ToNullableInt(); // i.Value = 123
Amalgamating the various answers:
int.Parse() is the preferred method if you're sure that the string can be converted, or if you handle exceptions
try
{
int value = int.Parse(myInt);
}
catch (FormatException)
{
}
If it is possible the string is not an integer then use int.TryParse()
int value;
if (!int.TryParse("a1", out value))
{
Console.WriteLine("a1 is not a valid integer");
}
Also you can write an extension method for a string like this:
static class StringExtension
{
public static int? ToNullableInt(this String str)
{
int result;
if (int.TryParse(str, out result))
{
return result;
}
return null;
}
}
Usage:
string s = "123";
int? i = s.ToNullableInt(); // i.Value = 123