Typecasting is used when you have to convert the type of value. This is only possible when the two types you are converting are compatible.
when you get an error saying "Cannot implicitly convert one type to another type" is when the two types you are converting are not compatible
int integer; // declaring integer as int
integer = "Hello World"; // put string into int type
This code will give you the error above.
Two kinds of Type Casting
- Implicit Type Casting
- Explicit Type Casting
Implicit Type Casting
Implicit conversion is automatically done by the compiler.
public static void Main(string[] args)
{
int intToDouble = 10;
double doubleFromInt;
doubleFromInt = intToDouble;
Console.WriteLine(doubleFromInt);
}
This will convert the int type to double type without data loss since it is a smaller type to a larger type.
Output
Explicit type casting
When you convert larger type to smaller type then we have to use explicit type casting. or it will give an error.
public static void Main(string[] args)
{
double doubleToInt = 11.1;
int intFromDouble;
intFromDouble = (int)doubleToInt;
Console.WriteLine(intFromDouble);
}
This will result in data loss. the starting value of double is 11.1 but when it converts to a smaller data type. it will output 11.
Output
Do We always lose some part of the data when we convert larger data type to smaller data type?
The short answer to that is No! when the bigger data type holds a small enough number that can be handled by the smaller data type that we are converting to, it will hold full data even after conversion
For example
public static void Main(string[] args)
{
int intToByte = 100;
byte byteFromInt = (byte)intToByte;
Console.WriteLine(byteFromInt);
}
This will print out 100 without losing value
Output
But if it goes over 255 byteFromInt can only hold intToByte - 255, because Byte can hold upto 255
public static void Main(string[] args)
{
int intToByte = 511;
byte byteFromInt = (byte)intToByte;
Console.WriteLine(byteFromInt);
}
This will print out 255, why not 256? cause byte counts start with 0 and it will do 0-255
Output
Type casting by Parse() method
In C# we have a built-in method called Parse(), this method performs incompatible type conversion, like between number type and string.
public static void Main(string[] args)
{
string stringToInt = "100";
int number = int.Parse(stringToInt);
Console.WriteLine(stringToInt.GetType());
Console.WriteLine(number.GetType());
}
Output
The other way around is Convert.ToString(intvalue);
public static void Main(string[] args)
{
int intToString = 100;
string stringFromInt = Convert.ToString(intToString);
Console.WriteLine(intToString.GetType());
Console.WriteLine(stringFromInt.GetType());
Console.WriteLine(stringFromInt);
}
Output
But when it comes to word-to-number type conversion, such as int gives you a runtime error.