Could anyone give me a definition of Type Casting and why and when should we use it?
I tried looking for material online, but couldn’t find anything that would explain me why exactly we need type casting and when to use it.
An example would be great!
Type casting is the mechanism of forcing an object into a particular type. In layman’s terms it is picking up a letter (the abstract) from the mailbox and forcing it into a bill (the specific, the concrete).
This is typically relevant in software development because we deal with a lot of abstraction so there are times when we’ll inspect a property of a given object and not immediately know the real concrete type of the said object.
In C# for example I might be interested in examining the contents of a datasource linked to a particular control.
The .DataSource property is of type “object” (which in C# is as abstract as you can get), this is because the DataSource property supports a range of different concrete types and wants to allow the programmer to choose from a wide range of types to use.
So, returning to my examination. With this object type, there isn’t a great deal I can do with “object data”.
That’s because these are the only APIs defined on the class object in C#. To access more interesting APIs I’m going to have to CAST the object into something more specific.
So if, for example I KNOW the object is a ArrayList I can cast it to one:
Now I can use the API of an arraylist (if the cast worked). So I can do things like:
The cast I showed above is what is known as a “hard” cast. It forces the object into whatever datatype I wanted and (in C#) throws an exception if the cast fails. So typically you only want to use it when you are 100% sure that the object is or SHOULD be that type.
C# also supports what is known as a “soft” cast that returns null if the cast fails.
You’d use the soft cast when you’re less sure of the type and want to support multiple types.
Lets say you’re the author of the comboBox class. In that case you might want to support different types of .DataSource so you’d probably write the code using soft casts to support many different types:
Hope that helps explain type casting to you and why it is relevant and when to use it! 🙂