What is the difference between Convert.ToInt32 and (int)?

The following code generates a compile-time error, for example

Cannot convert type 'string' to 'int'

string name = Session["name1"].ToString(); int i = (int)name; 

while the code below compiles and runs successfully:

 string name = Session["name1"].ToString(); int i = Convert.ToInt32(name); 

I'd like to know:

  • Why does the first code generate a compile-time error?

  • What is the difference between two pieces of code?

+49
c # type-conversion
Oct 22 '09 at 17:40
source share
12 answers

(int)foo is just casting to Int32 ( int in C #). This is built into the CLR and requires foo be a numeric variable (e.g. float , long , etc.). In this sense, it is very similar to a cast in C.

Convert.ToInt32 designed to be a common conversion function. It does a lot more than casting; namely, it can convert from any primitive type to int type (in particular, string analysis). You can see the full list of overloads for this method here on MSDN .

And as Stefan Steiger mentions in a comment :

Also note that at the numerical level (int) foo foo ifoo = Math.Floor(foo) foo ( ifoo = Math.Floor(foo) ), and Convert.ToInt32(foo) uses half to even rounding (rounds x. 5 to the nearest integer EVEN, which means ifoo = Math.Round(foo) ). Thus, the result is not only in terms of implementation, but also numerically not the same.

+62
Oct 22 '09 at 17:45
source share

(this line refers to the question that has been merged). You should never use (int)someString - this will never work (and the compiler will not let you).

However, int int.Parse(string) and bool int.TryParse(string, out int) (and their various overloads) are fair play.

Personally, I mostly use Convert when dealing with reflection, so for me the choice is Parse and TryParse . First, when I expect a value as a real integer and want it to throw an exception differently. Secondly, when I want to check if it is a valid integer, I can decide what to do when it is / not.

+18
Feb 27 '11 at 9:17
source share

To quote an article by Eric Lippert :

Cast means two conflicting things: "check if this object really has this type, drop it if it is not" and "this object is not of this type, find me an equivalent value belonging to this type."

What you tried to do in 1.) states that yes, String is an Int. But this statement fails because String is not an int.

Reason 2.) succeeds because Convert.ToInt32 () parses the string and returns an int. It may still fail, for example:

 Convert.ToInt32("Hello"); 

Will throw an Argument exception.

To summarize, the conversion from String to Int is a structure problem, and not something implicit in a system like .Net.

+5
Oct 22 '09 at 17:50
source share

A string cannot be passed to int via explicit casting. It must be converted using int.Parse .

Convert.ToInt32 basically wraps this method:

 public static int ToInt32(string value) { if (value == null) { return 0; } return int.Parse(value, CultureInfo.CurrentCulture); } 
+4
Oct 22 '09 at 17:48
source share

You are talking about C # casting operation against .NET Conversion utilities

  • C # language level casting uses brackets - for example. (int) - and conversion support for it is limited, relying on implicit compatibility between types or explicitly defined developer instructions through conversion operators .
  • Many conversion methods exist in the .NET Framework, for example. System.Convert to allow conversion between the same or disparate data types.
Syntax

(Casting) works with numeric data types, as well as with "compatible" data types. Compatible data types for which there is a relationship established through inheritance (e.g. base / derived classes) or through implementation (i.e. interfaces).

Casting can also work between disparate data types that are defined

+4
Oct 22 '09 at 17:50
source share

1) C # is a safe language and does not allow you to assign a string to a number

2) the second case analyzes the string for a new variable. In your case, if the session is an ASP.NET session, you do not need to store the string there and convert it when retrieving

 int iVal = 5; Session[Name1] = 5; int iVal1 = (int)Session[Name1]; 
+1
Oct 22 '09 at 17:44
source share

In .NET, there is no default value from a string in an int. You can use int.Parse () or int.TryParse () for this. Or, as you did, you can use Convert.ToInt32 ().

However, in your example, why ToString () and then completely convert it to int? You can just save the int in the session and get it like this:

 int i = Session["name1"]; 
+1
Oct 22 '09 at 17:47
source share

Short enough: in different circumstances (for example, if you convert double, & c to Int32), you may also worry about rounding when choosing between the two. Convert.Int32 will use Banker Rounding ( MSDN ); (int) will just truncate to an integer.

+1
Jul 25 '11 at 10:27
source share

Convert.ToInt32

     return int.Parse (value, CultureInfo.CurrentCulture);

but (int) is a type, so (int) "2" will not work, since you cannot distinguish a string from an int. but you can parse it like Convert.ToInt32 do

0
Oct 22 '09 at 17:45
source share

The difference is that the first fragment is cast, and the second is a converter. Although, I think, perhaps a compiler error creates more confusion here because of the wording. Perhaps it would be better if he said: "You can not use the type" string "for" int ".

0
Oct 22 '09 at 17:45
source share

This is old, but another difference is that (int) does not round numbers in case you have double ej: 5.7. ouput using (int) will be 5, and if you use Convert.ToInt (), the number will be rounded to 6.

0
May 27 '17 at a.m.
source share

This has already been discussed, but I want to share dotnetfiddle.

If you are dealing with arithmetic operations and use float, decimal, double, and so on, you better use Convert.ToInt32 ().

 using System; public class Program { public static void Main() { double cost = 49.501; Console.WriteLine(Convert.ToInt32(cost)); Console.WriteLine((int)cost); } } 

Exit

 50 49 

https://dotnetfiddle.net/m3ddDQ

0
Jun 07 '19 at 14:32
source share



All Articles