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:

  1. Implicit conversions (safe, automatic)

  2. 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); // 9

Other 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 β†’ ToImplicit?Example
int β†’ longβœ… Yeslong l = 42;
int β†’ doubleβœ… Yesdouble d = 42;
double β†’ int❌ No(int)9.8 β†’ 9
long β†’ int❌ No(int)1234567890;
float β†’ doubleβœ… Yesdouble 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 checked to detect overflow.

  • Use Convert methods for safe type conversions.