Type Conversion
Type conversion is like pouring water from a small cup into a big one, which is fine, versus big into small, which might spill. C# changes a value from one kind to another, sometimes automatically and sometimes only when you ask.
In this page:
Syntax
double widened = wholeNumber; // implicit
int narrowed = (int)decimalValue; // explicit cast
int parsed = int.Parse(text);
Convert.ToInt32(text);
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Casting a large
longtointwith(int)xand getting an overflow that silently wraps around. - Using
int.Parseon bad input, which throwsFormatException; useint.TryParse. - Assigning a
doubleto anintwithout a cast, which does not compile.
Chapter Summary
- The
varkeyword lets the compiler infer a variable's type. - Types like
int,float,double,decimal,bool,char, andstringstore different kinds of values. constfields hold fixed values, and type conversion changes a value from one type to another.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: