Utilizor
Contact Us

C# Type Casting

Converting data types.

C# Type Casting

Type casting is when you assign a value of one data type to another type.

In C#, there are two types of casting:

  • Implicit Casting (automatically) - converting a smaller type to a larger type size
    char -> int -> long -> float -> double
  • Explicit Casting (manually) - converting a larger type to a smaller size type
    double -> float -> long -> int -> char

Type Conversion Methods

It is also possible to convert data types explicitly by using built-in methods, such as Convert.ToBoolean, Convert.ToDouble, Convert.ToString, Convert.ToInt32 (int) and Convert.ToInt64 (long).

Examples

Implicit Casting

Automatically converting int to double.

using System;

class Program
{
  static void Main(string[] args)
  {
    int myInt = 9;
    double myDouble = myInt;       // Automatic casting: int to double

    Console.WriteLine(myInt);      // Outputs 9
    Console.WriteLine(myDouble);   // Outputs 9
  }
}

Explicit Casting

Manually converting double to int.

using System;

class Program
{
  static void Main(string[] args)
  {
    double myDouble = 9.78;
    int myInt = (int) myDouble;    // Manual casting: double to int

    Console.WriteLine(myDouble);   // Outputs 9.78
    Console.WriteLine(myInt);      // Outputs 9
  }
}

Type Conversion Methods

Using Convert class methods.

using System;

class Program
{
  static void Main(string[] args)
  {
    int myInt = 10;
    double myDouble = 5.25;
    bool myBool = true;

    Console.WriteLine(Convert.ToString(myInt));    // convert int to string
    Console.WriteLine(Convert.ToDouble(myInt));    // convert int to double
    Console.WriteLine(Convert.ToInt32(myDouble));  // convert double to int
    Console.WriteLine(Convert.ToString(myBool));   // convert bool to string
  }
}

String to Int

Converting string to integer.

using System;

class Program
{
    static void Main()
    {
        string numStr = "123";
        int num = Convert.ToInt32(numStr);
        Console.WriteLine(num + 1); // 124
    }
}