0

To read an integer from user input, you can use:

int number = Convert.ToInt32(Console.ReadLine());

But why won't the following work?

int number = (int) Console.ReadLine();

What's the difference between Convert.ToInt32 and casting with (int)?

closed as unclear what you're asking by gnat, durron597, user40980, GlenH7, Robert Harvey Aug 6 '15 at 21:30

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 2
    Do you understand what a cast is (in programming terms)? – Philip Kendall Aug 2 '15 at 8:07
  • when you explicitly convert from a double to a int for exmple.Right? – Dan Aug 2 '15 at 8:44
  • 1
    There is a huge difference between casting and parsing (which you need to use). See my answer for more information @Daniel :) – die maus Aug 2 '15 at 12:08
  • I updated my answer with some further information. – die maus Aug 6 '15 at 20:23
  • 1
    possible duplicate of Stack Overflow difference between Convert.ToInt32 and (int) – durron597 Aug 6 '15 at 22:17
6

There is no way to cast a System.String to a System.Int32


Unlike many other languages (e.g. PHP or JavaScript), C# is strongly typed. This means numbers (int in your case), and strings are two very different things. One cannot be cast to the other, because the C# compiler has no idea of how to make an implicit conversion between the two types. In a loosly typed language there are no real types, the compiler usually makes an educated guess about which type your variable has.

So, casting is for when you have a type that "may be" another type. You may for instance have an integer boxed as an object. In this case it is perfectly legal to write int number = (int)someObject; but you need to know beforehand that someObject can be cast to an integer, otherwise an InvalidCastException will be thrown at runtime.

You can also "cast" a type to (one of) its base-type(s), this commonly referred to as down-casting. For example: var enumerable = (IEnumerable<string>)new List<string>();. This however, is usually done implicitly in method calls, there are no common use-cases where you explicitly have to down-cast a type.

It's important to note that down-casting will not "convert" a type. My variable named enumerable in the above example is still a List<string>. The difference is that it is now boxed as a IEnumerable<string>. You can unbox your list via a new cast: var list = (List<string>)enumerable; or via the as-keyword if you are using a reference-type (class).

C# also supports casting between the different number types. For instance a System.Decimal or a System.Double can be cast to a System.Int32. But the decimals will get truncated. For instance int truncatedPI = (int)Math.PI; will give you 3. But as far as i know; this is just compiler-magic.

What you need to look into is something called parsing.


Parsing is the mechanism in which you have a value, that is not in the desired type (commonly a string) and parse it to the type you want, either by using a built-in parser or by writing your own parser.

Most of the common value-types (structs and enums) in .NET have built-in static Parse-methods.

For integers: int.Parse("15"), for dates: DateTime.Parse("2015-08-02 00:00") and so on. These are built-in parsers, which are included in the .NET framework.

Console.ReadLine returns a string which cannot be implicitly converted to a integer by casting (boxing or unboxing). To solve your problem you need to use one of the parsing-methods mentioned above.

In your case int number = int.Parse(Console.ReadLine()); would most likely suffice. But be careful, if you enter something like "HELLO" in your console-application, int.Parse will throw a FormatException since what you have entered cannot be interpreted by the parser.

This is where TryParse and TryParseExact, come in. They are usually more viable alternatives for handling user input.


As a general rule — try to avoid Convert.To[Type] when parsing strings. These are generally just "lazy" implementations of the Parse method anyways. Using the parsing methods mentioned above comes with more options, better scalability and also prompts the programmer with more precise information of what is going on in your code.

1

That is because no explicit or implicit conversion exists between those two types in .NET framework. In other words explicit conversion operator is not overloaded in string class. More on converting strings to numbers in C# is in this article. Also read about casting.

0

This might help understand why this doesn't work.

"Hi " + "there" = "Hi there", right?

1 + 3 = 4

What does "Hi " + 2 = ?

It makes no sense.

Since Console.ReadLine returns a string, the language has no way of knowing whether you're going to enter a number or not. So it requires you to instead make an explicit statement that you're going to turn the input into a number, and that's what int.Parse does. Convert calls this method - but like said above it's not as precise as calling Parse.

Not the answer you're looking for? Browse other questions tagged or ask your own question.