Monday, August 21, 2006

Visual Studio 2003 SP1 finally released!

For those like me who have not yet fully migrated to Visual Studio 2005, MS has finally released the very long-waited service pack for Visual Studio 2003.

The list of bug fixes can be found at http://support.microsoft.com/?kbid=918007

The SP1 fixes a large number of issues, which were bugging us every day. One regret is that it took 3 years for Microsoft to get it out. Let's be positive and say that it will make my last months of work with VS 2003 less painful before I move completely to VS 2005...

Tuesday, August 01, 2006

Int32.Parse() vs Convert.ToInt()

What's the difference between Int32.Parse() and Convert.ToInt()?

That's a good question, isn't it? At least, that's a question that I often hear.

Int32.Parse converts a string variable (or some other valid types) into a variable of type int. However if you pass a non-recognized value (text string, empty string or null string), it will throw an exception (System.NullArgumentException if null else System.FormatException)

Below is the code of Int32.Parse(string) using Reflector

public static int Parse(string s)
{
return int.Parse(s, NumberStyles.Integer, null);
}

It calls internally another signature of the method with all arguments


public static int Parse(string s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo info1 = NumberFormatInfo.GetInstance(provider);
NumberFormatInfo.ValidateParseStyle(style);
return Number.ParseInt32(s, style, info1);
}

Convert.ToInt32 also converts a string (or some other valid types) into a variable of type int. It basically behaves the same way as Int32.Parse() except that it won't throw an exception System.NullArgumentException if a null string is passed to the method, instead it will return 0.

Below is the code of Convert.ToInt32(string) using Reflector

public static int ToInt32(string value)
{
if (value == null)
{
return 0;
}
return int.Parse(value);
}

You may download http://julien.jacobs.free.fr/download/ConvertProject.zip, a windows application, which highlights each case.

You should therefore use the method that better suits your scenario.

Finally for those who are already using .Net 2.0, you may prefer to use the new Int32.TryParse method, which accepts a string, an ouput int and returns true or false if the conversion succeeds. If the conversion succeeds, the output int is set to the result.