Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why in C# Console.ReadLine() stores only string?

Why can't Console.ReadLine() store int/double in C# ? As opposed to "cin >>" in C++, which can store anything depending on the variable.

like image 673
aSim Avatar asked Feb 02 '26 05:02

aSim


2 Answers

Different language, different library, different API, different design decisions, etc.

cin.operator>> is passed a reference to be used an out parameter and it's overloaded on this parameter type. Console.ReadLine returns a value and is not overloaded.

You could write your own extension method for Console like, say, GetValue, which is passed an out parameter and is overloaded on as many types as you wish.

like image 67
Mud Avatar answered Feb 04 '26 18:02

Mud


The console, natively, is just text input. Console.ReadLine() (and the other methods) don't do the parsing for you, and instead leave it up to you to parse yourself.

This has an advantage, however, in that it makes it easier to handle the error cases cleanly (if you want to read in a double, and the user types "foo", for example).

like image 30
Reed Copsey Avatar answered Feb 04 '26 18:02

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!