C# Casting Quiz

There are several ways to convert and cast values in .NET. For example, DirectCast versus System.Convert and if you are a VB.NET'er, you have the CInt, CBool, Cxxx functions. It is along these lines that I offer this quiz: What are the differences between the following ways to cast an object?


Casting quiz
/// Technique #1 object item = GetIt(); Dog dog = (Dog)item; /// Technique #2 object item = GetIt(); Dog dog = item as Dog; public object GetIt() { object x = null; /// Does something that tries to get an instance of an object ... ... ... return x; } 

What is the difference between these 2 techniques of casting and when would you want to use one over the other?

Tweet Post Share Update RSS

Hi, I'm John Papa. I author this blog, create courses for Pluralsight and am a Google Developer Expert and Microsoft Regional Director. I travel speaking at events and train technology thought leaders