Start learning free

LESSON 14 OF 674 · VARIABLES

Type Conversion in C#

Lesson

In C#, every value has a type: int, double, string, and so on. Sometimes you need to convert a value from one type to another.

Common type conversion methods:

x.ToString()            // converts int or double → string
int.Parse(s)            // converts string → int
double.Parse(s)         // converts string → double
(int) x                 // casts double → int (drops decimal)

Here are some examples:

int score = 42;
string scoreStr = score.ToString();         // "42"

double weight = 70.8;
int weightInt = (int) weight;               // 70  (decimal dropped)

string count = "100";
int countInt = int.Parse(count);            // 100

Note that casting a double to int with (int) simply drops the decimal - it does not round.


Assignment
Follow the Coding Tutorial and convert each variable to a different type!


Hint
Use ToString(), (int) casting, and int.Parse().

STEP 1 OF 3
    Ctrl + Enter to check