Char and bool
Learn to store single characters with char and logical values with bool.
Type conversion
Sometimes you need to convert one type to another. Implicit conversion happens automatically from a smaller type to a larger one: double d = 5; turns the int 5 into a double.
Explicit conversion (cast) goes from large to small; because data may be lost, you must ask for it: int n = (int)3.9; gives 3.
A cast writes the type name in parentheses. Implicit conversion is safe; explicit casting puts the responsibility on you.
Convert and Parse
When you need to turn a string into a number, two options exist. int.Parse("42") converts the text directly to an int; it throws on invalid input.
Convert.ToInt32("7") does the same; the Convert class gathers many type conversions under one roof.
Both throw an exception on null or non-numeric text. You will learn TryParse for safe parsing in later lessons.
Exercise Parse a string into an int
Assign "42" to a string text variable. Convert it into an int number using int.Parse(text). Then print number + 10 with Console.WriteLine.
Show example solution
string text = "42"; int number = int.Parse(text); Console.WriteLine(number + 10);
Example solution:
using System;
class Program {
static void Main() {
string text = "42";
int number = int.Parse(text);
Console.WriteLine(number + 10);
}
}
Test yourself
-
Which one is an implicit conversion?
- double d = 5;
- int n = 3.14;
- int n = (int)3.14;
- string s = "5";
Show answer
double d = 5; — Correct! Implicit int-to-double conversion is safe; no cast needed.
-
Explicitly cast a double to int
int n = ____ 3.9;Show answer
int n = (int) 3.9; -
Match each conversion to its purpose
- (int)3.9
- cast to truncate
- int.Parse("42")
- string to int
- Convert.ToInt32("7")
- Convert class
- double d = 5
- implicit widen