Deep C# - Casting the Escape from Strong Typing |
Written by Mike James | |||||
Page 1 of 4 Casting is one of the most confusing aspects of any modern language and it often makes beginners think hard. But if you know why you are doing it, then the how makes a lot more sense. We have encountered casting earlier in the context of strong typing but there is more to it. Find out in this extract from my new book, Deep C#: Dive Into Modern C#. Deep C#Buy Now From Amazon Chapter List
Extra Material <ASIN:1871962714> <ASIN:B09FTLPTP9> CastingCasting, stating the type of an object to override variable typing, is an odd business that has found its way into many modern languages via C and C++. Both Java and C# make use of it to allow programmers to escape the confines of strong typing without being able to create anything too unsafe. The big problem is that it confuses two aspects of dealing with variables – type and representation. Type is simply a system of classification that is used by strongly-typed languages to determine what sort of data a variable can store or reference. Type conversion can just mean changing the classification of an object or variable, or it can mean changing the actual representation of the data, for example from integer to floating point. In an ideal world we wouldn’t need to convert or even mix types – an integer would always be combined with other integers and why would you ever want to convert an integer to a floating point number? Of course, if you want to write useful programs you have to allow a certain interplay between data types and this is where casting as conversion comes in. Originally, in C, casting was all about type conversion and this is how it is usually introduced, but in fact there is more to it as there are some very confused semantics behind a simple piece of syntax – just write the type name in brackets in front of the variable you want to convert – but does this mean passive type conversion or active representation conversion? What is worse is that most books on C# don’t venture very deeply into the idea beyond presenting the basic idea that casting is just type conversion. It’s actually more tricky, so let’s start simple with casting value types and then look at the more interesting reference type casting. |