11 - Type Conversion
To start off the Intermediate C# tutorial series we will talk about type conversion and converting from one variable type to another. Type casting is part of an object oriented programming theory called Polymorphism which we will get into in greater detail later in the series. Type conversion is useful when trying to satisfy a variable type that another method is requesting. I.E. A Unity Textbox.text requires a string variable, but we would like to put an integer number of items in it. We can use type casting to make that possible. This tutorial will go over Implicit and Explicit type casting as well as the is and as keywords
Implicit conversion are performed in a type-safe manner. What this means is that no data will be lost from the conversion. Some examples of this is converting from a smaller number variable to a larger number variable as well as converting from a derived class to a base class. For a complete list of implicit numeric conversions check out the following link.
Contrary to Implicit conversion is Explicit conversion. Explicit conversion occurs when loss of information may occur from converting from one type to another. Another name for Explicit conversion is called Casting or Type Casting. To perform casting, simply put parenthesis around the type that you want to convert a variable too. In the example below notice how the .37 is lost by converting from a double to an int. It is not recoverable after the conversion. i.e. converting to a double from an int will only have a double of 120. To see a list of all explicit numeric conversions check out this link.
So currently with explicit conversion if we attempt to type cast to a variable that does not work, we will get an InvalidCastException. What if we would like to test if we are able to convert before we try to convert? We can use the is keyword to do so. When we want the cast to actually occur we can use the as keyword. Check out the example below to see how this actually takes place. A key thing to note with the as keyword is that it must be used with a reference type variable or a variable that is nullable. Integers will not work with the as keyword as they are value types. You will probably mainly use the as keyword predominantly with classes.