Type Conversion
In this page:
Type Conversion
C# converts between compatible types either implicitly (widening, like int to double) or explicitly with a cast (narrowing, like double to int). The Convert class and Parse/TryParse methods handle converting strings to numbers safely. Explicit narrowing casts can silently lose data if you're not careful.
Warning: Casting a double like 9.9 to int truncates it to 9 — it does not round.
Example: Type Conversion
using System;
class Program
{
static void Main(string[] args)
{
int wholeNumber = 10;
double asDouble = wholeNumber; // implicit widening
double preciseValue = 9.9;
int truncated = (int)preciseValue; // explicit narrowing
string numericText = "42";
int parsed = int.Parse(numericText);
Console.WriteLine(asDouble);
Console.WriteLine(truncated);
Console.WriteLine(parsed + 8);
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: