C# Casting Variable Types

C# Casting Variable Types

C# 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

 

1 - C# Implicit Casting

Implicit casting is done automatically when passing a smaller size type to a larger size type.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            int myInt = 9;
            double myDouble = myInt; // Automatic casting: int to double
            Console.WriteLine(myInt);      
            Console.WriteLine(myDouble);   
            Console.ReadLine();
        }
    }
}

Output:

C# Implicit Casting

 

2 - C# Explicit Casting

Explicit casting must be done manually by placing the type in parentheses in front of the value.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

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

            Console.WriteLine(myDouble);
            Console.WriteLine(myInt);
            Console.ReadLine();
        }
    }
}

Output:

C# Explicit Casting

 

C# 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).

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            int myInt = 11;
            double myDouble = 7.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
            Console.ReadLine();
        }
    }
}

Output:

C# Type Conversion Methods

Note that casting is only possible on numerical data types. It is not, therefore, possible to perform casts on string, or bool variables.