C# also supports both implicit and explicit casts and gives you some different choices when you need to switch types. Plus you have a runtime that’s ready to throw an InvalidCastException. But even if you don’t hit an exception, there’re some things you should be aware of. This is still casting.
This is a short episode that builds on the previous episode and describes how you cast types in C#. You don’t have initializer lists or named casts like in C++. But you do have a runtime that will help make sure that your casts are well behaved. If not, the runtime will throw an InvalidCastException.
You have four options to perform casts in C#:
- You can use C-style casts.
- You can define an operator in your class that knows how to return the type you want to cast to.
- You can implement the IConvertible interface if you want your class to be able to be converted to base types such as int.
- You can implement a Parse or a TryParse method if you want to be able to convert to your class from a string. This of course requires that your class be able to generate a suitable string in the first place that the Parse method can use to reconstruct your class.
And you also have two keyword operators in C# to help you test and cast types. The “is” operator allows you to test if an instance really is another type. And the “as” operator allows you to perform a cast but if the cast fails, then instead of throwing an InvalidCastException, the “as” operator will return null.