Course Content
C# Basics
C# Basics
Basic Type Casting
Type Casting is the process of converting a value from one data type to another. This is often possible between types that represent numbers. For example, you can convert a float
to an int
and vice versa. However, converting a string
directly to an int
doesn't make logical sense and is not possible without additional steps.
There are two types of type casting: implicit type casting and explicit type casting.
Implicit type casting occurs automatically when a value is converted from one type to another, usually from a smaller to a larger data type.
main
int val1 = 10; long val2 = val1; // int is automatically converted to long float val3 = var1; // int is automatically converted to float double var4 = var1; // int is automatically converted to double
Implicit type casting happens automatically when a smaller data type is converted to a larger one. The size of a data type is determined by how much data it can hold, measured in bits. For example, an int
can hold 32 bits, while a long
can hold 64 bits, so converting an int
to a long
happens automatically. Similarly, a float
can be converted to a double
without any issues.
Here's a list of data types ordered from smallest to largest:
char
-> int
-> long
-> float
-> double
Explicit type casting is when you, as the programmer, tell the computer to convert a value to a different data type. This is necessary when converting from a larger data type to a smaller one because some data might be lost. For example, converting the float 3.14
to an integer results in 3
, losing the decimal part. That's why you need to explicitly tell the computer to make such conversions.
main
using System; namespace ConsoleApp { internal class Program { static void Main(string[] args) { float val1 = 3.14f; int val2 = val1; // Error: Cannot implicitly convert type 'float' to 'int'. An explicit conversion exists (are you missing a cast?) Console.WriteLine(val1); Console.WriteLine(val2); } } }
To fix the error in the above code, we need to explicitly cast val1
to an integer value.
The syntax of a cast is (datatype) value
, for-example (int) 3.1415
. So in this case we will write (int) val1
:
main
using System; namespace ConsoleApp { internal class Program { static void Main(string[] args) { float val1 = 3.14f; int val2 = (int) val1; Console.WriteLine(val1); Console.WriteLine(val2); } } }
Thanks for your feedback!