C# provides us with a couple of keywords for checking the type of an object: as and is.
Here’s how we can use them in our ClockIn implementation:
public void ClockIn(object item)
{
if (item is INamedPerson)
{
ClockIn(item as INamedPerson);
}
else
{
Console.WriteLine("We can't check in a '{0}'", item.GetType());
}
}Notice how we are using the type name to check if the item is of that type. And then we call our other overload of ClockIn by explicitly converting to a reference of our INamedPerson type, using as.
It checks to see if our object would be accessible through a reference of the specified type. It looks at the whole inheritance hierarchy for the object (up and down) to see if it matches, and if it does, it provides us a reference of the relevant type.
What if you don’t bother with the is check and just use as? Conveniently, the as operation just converts to a null reference if it can’t find a suitable type match:
public void ClockIn(object item)
{
INamedPerson namedPerson = item as INamedPerson;
if(namedPerson != null)
{
ClockIn(namedPerson);
}
else
{
Console.WriteLine("We can't check in a '{0}'", item.GetType());
}
}This is the form in which you most often see a test like this, because it is marginally more efficient than the previous example. In the first version, the runtime has to perform the expensive runtime type checking twice: once for the if() statement and once to see whether we can actually perform the conversion, or whether null is required. In the second case, we do the expensive check only once, and then do a simple test for null.
This bestselling tutorial shows you how to build web, desktop, and rich Internet applications using C# 4.0 with .NET's database capabilities, UI framework (WPF), extensive communication services (WCF), and more. The sixth edition covers the latest enhancements to C#, as well as the fundamentals of both the language and framework. You'll learn concurrent programming with C# 4.0, and how to use .NET tools such as the Entity Framework for easier data access, and the Silverlight platform for browser-based RIA development.




Help






