3

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.

Satpal
  • 132,252
  • 13
  • 159
  • 168
user3049768
  • 31
  • 1
  • 2

4 Answers4

9

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;
David Pilkington
  • 13,528
  • 3
  • 41
  • 73
4

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.

Habib
  • 219,104
  • 29
  • 407
  • 436
0

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

Tobberoth
  • 9,327
  • 2
  • 19
  • 17
0

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);
}
Jerry Bian
  • 3,998
  • 6
  • 29
  • 54
  • With a catch: `Convert.ToInt32` accepts null arguments, in which case it returns the default value (i.e., 0) – dcastro Nov 29 '13 at 14:55