This post originated from an RSS feed registered with .NET Buzz
by John Papa.
Original Post: C# Casting Quiz
Feed Title: John Papa
Feed URL: /error.htm?aspxerrorpath=/blogs/john.papa/rss.aspx
Feed Description: .NET Code Samples, Data Access, Patterns and Other Musings
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 #1object item = GetIt();
Dog dog = (Dog)item;
/// Technique #2object 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?