I would like to know that what are differences between,
(int)Something;
int.Parse(Something);
Convert.ToInt32(Something);
I asked my friends and no body helped me about this subject.
Any help will be appreciated.
thanks.
I would like to know that what are differences between,
(int)Something;
int.Parse(Something);
Convert.ToInt32(Something);
I asked my friends and no body helped me about this subject.
Any help will be appreciated.
thanks.
1) that is a cast
2) Parsing taking in a string and attempts to convert it to a type.
3) Convert accepts an object as its paramerter
One major difference is that Convert does not throw a ArgumentNullException while Parse does. Your cast would also throw an exception if it null. You can get around that by using
(int?)Something;
Your first case:
(int)Something;
is Explicit cast, so something would be a double/float etc. If it is a string you will get an error.
Second case:
int.Parse(Something)
int.Parse takes sting as parameter so Something has to be a string type.
Third case:
Convert.ToInt32(Something);
Convert.ToInt32 has many overloads which takes parameter of type object, string, bool etc.
There is no difference, just read MSDN.
Using the ToInt32(String) method is equivalent to passing value to the Int32.Parse(String) method.
Source: http://msdn.microsoft.com/en-us/library/sf1aw27b(v=vs.110).aspx
Convert.ToInt32(string) is a static wrapper method for Int32.Parse(string).
The Convert.ToInt32 is defined like (from ILSpy):
// System.Convert
/// <summary>Converts the specified string representation of a number to an equivalent 32-bit signed integer.</summary>
/// <returns>A 32-bit signed integer that is equivalent to the number in <paramref name="value" />, or 0 (zero) if <paramref name="value" /> is null.</returns>
/// <param name="value">A string that contains the number to convert. </param>
/// <exception cref="T:System.FormatException">
/// <paramref name="value" /> does not consist of an optional sign followed by a sequence of digits (0 through 9). </exception>
/// <exception cref="T:System.OverflowException">
/// <paramref name="value" /> represents a number that is less than <see cref="F:System.Int32.MinValue" /> or greater than <see cref="F:System.Int32.MaxValue" />. </exception>
/// <filterpriority>1</filterpriority>
[__DynamicallyInvokable]
public static int ToInt32(string value)
{
if (value == null)
{
return 0;
}
return int.Parse(value, CultureInfo.CurrentCulture);
}