C# Type casting is when you assign a value of one data type to another type.
In C#, there are two types of casting:
char
-> int
-> long
-> float
-> double
double
-> float
-> long
-> int
-> char
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:
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:
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:
Note that casting is only possible on numerical data types. It is not, therefore, possible to perform casts on string, or bool variables.