What is type casting, what's the use of it? How does it work?
Type Casting is basically a process in C in which we change a variable belonging to one data type to another one. In type casting, the compiler automatically changes one data type to another one depending on what we want the program to do.
Type casting is when you assign a value of one primitive data type to another type. In Java, there are two types of casting: Widening Casting (automatically) - converting a smaller type to a larger type size. byte -> short -> char -> int -> long -> float -> double.
An example of typecasting is converting an integer to a string. This might be done in order to compare two numbers, when one number is saved as a string and the other is an integer. For example, a mail program might compare the first part of a street address with an integer.
Casting is usually a matter of telling the compiler that although it only knows that a value is of some general type, you know it's actually of a more specific type. For example:
object x = "hello";
...
// I know that x really refers to a string
string y = (string) x;
There are various conversion operators. The (typename) expression
form can do three different things:
int
)XAttribute
to string
)object
to string
)All of these may fail at execution time, in which case an exception will be thrown.
The as
operator, on the other hand, never throws an exception - instead, the result of the conversion is null
if it fails:
object x = new object();
string y = x as string; // Now y is null because x isn't a string
It can be used for unboxing to a nullable value type:
object x = 10; // Boxed int
float? y = x as float?; // Now y has a null value because x isn't a boxed float
There are also implicit conversions, e.g. from int
to long
:
int x = 10;
long y = x; // Implicit conversion
Does that cover everything you were interested in?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With