there are many ways to cast/convert object to another by what the difference between those and if there is no difference why there are so many ways to achieve one thing? Isn't that damage to language?
let's say object obj to string.
obj.ToString()
obj as string
(string)obj
Convert.ToString(obj)
The two types of type casting in C are: Implicit Typecasting. Explicit Typecasting.
Implicit conversion is the conversion in which a derived class is converted into a base class like int into a float type. Explicit conversion is the conversion that may cause data loss. Explicit conversion converts the base class into the derived class.
Type casting refers to changing an variable of one data type into another. The compiler will automatically change one type of data into another if it makes sense. For instance, if you assign an integer value to a floating-point variable, the compiler will convert the int to a float.
There are two types of conversion: implicit and explicit. The term for implicit type conversion is coercion. Explicit type conversion in some specific way is known as casting. Explicit type conversion can also be achieved with separately defined conversion routines such as an overloaded object constructor.
You are doing different things here:
ToString()
method of the object. The object returns a string as it was programmed to.null
), no exception will be thrown.obj
to the type string
, you are telling the compiler that obj
is a string
. If obj
is not a string type, you will get a cast exception.obj
.There are these many different ways to get a string
from an object
because each one is different and have subtle differences. Yes, in many cases the returned string will be the same, but this is not guaranteed.
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