Letβs go through built-in numeric conversions in C# β a key concept for working with numbers of different types.
π 1. What Are Numeric Conversions?
In C#, numeric conversion happens when you assign a value of one numeric type (like int, double, byte) to another numeric type.
There are two main kinds:
-
Implicit conversions (safe, automatic)
-
Explicit conversions (casts) (possible data loss, requires
cast)
π 2. Implicit Numeric Conversions
These are safe conversions because thereβs no risk of losing data.
Smaller β larger type automatically works.
Examples
int i = 42;
double d = i; // Implicit conversion (int β double)
float f = 10; // int β float (safe)
long l = i; // int β long (safe)β Allowed implicit conversions include:
-
sbyteβshort,int,long,float,double,decimal -
byteβshort,ushort,int,uint,long,ulong,float,double,decimal -
shortβint,long,float,double,decimal -
intβlong,float,double,decimal -
longβfloat,double,decimal -
charβushort,int,uint,long,ulong,float,double,decimal -
floatβdouble -
uintβlong,ulong,float,double,decimal -
ulongβfloat,double,decimal
π 3. Explicit Numeric Conversions (Casting)
When thereβs a risk of data loss (like narrowing), you must use an explicit cast.
Example
double d = 9.8;
int i = (int)d; // Explicit cast, fractional part is lost
Console.WriteLine(i); // 9Other cases:
int big = 1000;
byte small = (byte)big; // Explicit cast required, may overflow
Console.WriteLine(small); // 232 (overflowed)β οΈ Explicit conversions can:
-
truncate fractional parts (e.g.,
9.8 β 9) -
overflow (e.g., assigning 1000 to a
byte)
π 4. Checked vs Unchecked Contexts
-
By default, overflow in explicit conversions doesnβt throw an error.
-
But you can force a runtime error using
checked:
checked
{
int big = 1000;
byte small = (byte)big; // Throws OverflowException in checked context
}π 5. Converting with Helper Methods
Sometimes you should use conversion helpers to avoid surprises:
-
Convert.ToInt32(),Convert.ToDouble(), etc. -
Safer than casting, because they handle rounding and nulls.
string number = "123";
int result = Convert.ToInt32(number); // 123π 6. Summary Table
| From β To | Implicit? | Example |
|---|---|---|
int β long | β Yes | long l = 42; |
int β double | β Yes | double d = 42; |
double β int | β No | (int)9.8 β 9 |
long β int | β No | (int)1234567890; |
float β double | β Yes | double d = 3.14f; |
decimal β double | β No | (double)decimalValue; |
β Summary:
-
Implicit conversions = safe, automatic (no data loss).
-
Explicit conversions = require
(cast), possible data loss/overflow. -
Use
checkedto detect overflow. -
Use
Convertmethods for safe type conversions.