← C# from Scratch
Lesson 5 of 39 · 10 XP
Type conversion
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
Implicit (widening) — when no data can be lost: char → int → long → float → double.
int a = 7;
double d = a; // 7.0 — automatically
Explicit — when data may be lost; you write the type in parentheses:
double price = 9.99;
int whole = (int)price; // 9 — the fractional part is DROPPED, not rounded
int x = 7, y = 2;
Console.WriteLine(x / y); // 3 — both are int, so it's integer division
Console.WriteLine((double)x / y); // 3.5
Conversion methods — for strings and between any types:
int n = Convert.ToInt32("42");
double r = Convert.ToDouble("3.5");
string s = n.ToString();
int k = int.Parse("15");
Console.WriteLine(Convert.ToInt32(2.5)); // 2 — Convert ROUNDS; a .5 goes to the nearest even number
Task. Given int total = 17 and int parts = 5, print on three lines:
the integer quotient (3), the exact quotient (3.4) and (int) of 9.99 (9).
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.