When you so many types (value types, reference types) and of course built in types and so many custom types that are designed by you, as a developer, you will run into a common scenario. You need to convert one type into another. This can be called as conversion of type, or casting or type casting. Any and all of these words/phrases can be used interchangeably.
There are so many ways of converting types and lets see them one by one
Implicit type casting is when you don’t have to do anything specific – code wise – to make the conversion happen. The compiler will take care of it on its own.
For instance, when you do
int hello_there = 20;
double hello_there_double = hello_there;
You are pushing an int type into a double type. It just gets done with no special intervention from you.
Explicit type conversion is where you do the same thing explicitly.
double hello_there_double_explicit = (double)hello_there;
The third way is when you do the conversion with a helper class.
double hello_there_double_helper = Convert.ToDouble(hello_there);
The fourth way is custom conversions that are of course, user defined, just like user defined types. That means, custom conversions are written by you, to enable a smooth conversion.
This becomes useful when there are scenarios where you have a custom type, and you still want to encourage your custom type instances to be converted into another type.
For instance, suppose you have a complex custom type that represents the many dimensions a water bottle such as its color, weight, height, design, capacity and so on. However, you still would like to allow some sort of a type conversion where in your water bottle instance can be casting into a int type, where in the capacity value of your water bottle is passed over.
This would be very useful when you want to increase efficiency of your project by allowing conversions to value types. That way, in places where the entire object is not needed, you can simply use value types, obtain the necessary values via casting and consume them anyway you please, all the while reducing the memory footprint.
The accompanying code at our repository has this example, along with all the earlier conversions.
Follow me on twitter, facebook and instagram for more updates. Thanks!