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
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.Sign up to join this community
There is no way to cast a
System.String to a
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
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
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.
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.