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

后端 未结 12 1497
星月不相逢
星月不相逢 2020-11-27 03:11

The following code throws an compile-time error like

Cannot convert type \'string\' to \'int\'

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


        
相关标签:
12条回答
  • 2020-11-27 03:56

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

    0 讨论(0)
  • 2020-11-27 03:57

    There is not a default cast from string to int in .NET. You can use int.Parse() or int.TryParse() to do this. Or, as you have done, you can use Convert.ToInt32().

    However, in your example, why do a ToString() and then convert it back to an int at all? You could simply store the int in Session and retrieve it as follows:

    int i = Session["name1"];
    
    0 讨论(0)
  • 2020-11-27 03:57

    Convert.ToInt32

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

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

    0 讨论(0)
  • 2020-11-27 04:00

    (this line relates to a question that was merged) You should never use (int)someString - that will never work (and the compiler won't let you).

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

    Personally, I mainly only use Convert when I'm dealing with reflection, so for me the choice is Parse and TryParse. The first is when I expect the value to be a valid integer, and want it to throw an exception otherwise. The second is when I want to check if it is a valid integer - I can then decide what to do when it is/isn't.

    0 讨论(0)
  • 2020-11-27 04:00

    To quote from this Eric Lippert article:

    Cast means two contradictory things: "check to see if this object really is of this type, throw if it is not" and "this object is not of the given type; find me an equivalent value that belongs to the given type".

    So what you were trying to do in 1.) is assert that yes a String is an Int. But that assertion fails since String is not an int.

    The reason 2.) succeeds is because Convert.ToInt32() parses the string and returns an int. It can still fail, for example:

    Convert.ToInt32("Hello");
    

    Would result in an Argument exception.

    To sum up, converting from a String to an Int is a framework concern, not something implicit in the .Net type system.

    0 讨论(0)
  • 2020-11-27 04:06

    The difference is that the first snippet is a cast and the second is a convert. Although, I think perhaps the compiler error is providing more confusion here because of the wording. Perhaps it would be better if it said "Cannot cast type 'string' to 'int'.

    0 讨论(0)
提交回复
热议问题