← Retour au cours: C# from scratch

User input, conversions and review

Vidéo bientôt disponible

Until now your programs expected nothing from anybody. In this lesson you will learn to read data typed by the person, convert it to the right type and react when they type something invalid. It is the last step to create truly interactive programs. We also close week 2 with a review and a five-question quiz.

Console.ReadLine and the string? type

Console.ReadLine() waits for the person to press Enter and returns the typed text. Because the project has nullability enabled, its type is string?, which means "a string or null"; it returns null when the input is closed. A simple solution for now is the ?? operator, which gives an alternative value if the left side is null: Console.ReadLine() ?? "". Important: even if the person types 25, what you receive is the text "25", not the number. You cannot add it or compare it as a number until you convert it.

Converting with Parse and TryParse

Each numeric type has int.Parse, double.Parse, decimal.Parse and so on. Parse converts, but if the text is not valid it throws a FormatException and the program stops. For input from people, TryParse is almost always better: it returns true or false depending on whether it worked and hands you the number through an out parameter. That way you can ask again instead of breaking the program. The syntax int.TryParse(text, out int number) declares the variable in the same place. There is also the Convert class and the ToString() method, but for text coming from people TryParse is the right tool.

csharp
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

Console.Write("Your name: ");
string name = Console.ReadLine() ?? "";

Console.Write("Your age: ");
string ageText = Console.ReadLine() ?? "";

if (int.TryParse(ageText, out int age))
{
    Console.WriteLine($"Hi {name}! Next year you will be {age + 1}.");
}
else
{
    Console.WriteLine($"'{ageText}' is not a valid number.");
}

Console.WriteLine(int.Parse("42") + 1);           // 43
Console.WriteLine(double.Parse("3.5") * 2);       // 7
Console.WriteLine(int.TryParse("abc", out int n)); // False (n is 0)
// int.Parse("abc");                              // FormatException

Conversions between numbers

When you convert between numeric types there are two cases. If no information is lost (from int to long or to double) the conversion is implicit and C# does it by itself. If information can be lost (from double to int, or from long to int) you have to ask for it with an explicit cast, and you must know that the decimal part is truncated rather than rounded: (int)3.9 is 3. To really round, use Math.Round. When a result may go out of range, a checked block makes the overflow throw an exception instead of silently giving a wrong number.

csharp
int small = 100;
long big = small;            // implicit: nothing lost
double d = small;            // implicit
double price = 3.9;
int cut = (int)price;        // explicit cast: 3
int rounded = (int)Math.Round(price); // 4
Console.WriteLine($"{big} {d} {cut} {rounded}");

int max = int.MaxValue;
try
{
    int boom = checked(max + 1);
    Console.WriteLine(boom);
}
catch (OverflowException)
{
    Console.WriteLine("Overflow detected");
}

Testez vos acquis

Question 1 sur 6

What type does Console.ReadLine() return with nullability enabled?

✎ Mes notes

Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères

← PrécédenteSuivante →