C sharp - Type casting in C#

In C#, type casting is used to convert a value from one data type to another. There are two main types of casting:

 1. Implicit Casting (Safe / Widening Conversion)

  • Automatically done by the compiler.

  • Safe because there's no data loss.

  • From smaller to larger types (e.g., int to float, char to int).

int num = 10;
float bigNum = num;  // Implicit casting

 2. Explicit Casting (Manual / Narrowing Conversion)

  • You must manually cast.

  • Risk of data loss or overflow.

double pi = 3.14;
int intPi = (int)pi;  // Explicit casting — decimal part is lost

3. Casting Between Reference Types

Using as Keyword

  • Returns null if the cast fails.

object obj = "hello";
string str = obj as string;
if (str != null)
{
    Console.WriteLine(str);
}

4. Convert Class (System.Convert)

  • Useful for safe conversions between base types.

string s = "123";
int x = Convert.ToInt32(s);

5. Boxing and Unboxing

  • Boxing: Converting a value type to object.

  • Unboxing: Converting back to the value type.

int num = 42;
object boxed = num;        // Boxing
int unboxed = (int)boxed;  // Unboxing