O'Reilly logo

Microsoft® Visual C#® 2008 Step by Step by John Sharp

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Casting Data Safely

By using a cast, you can specify that, in your opinion, the data referenced by an object has a specific type and that it is safe to reference the object by using that type. The key phrase here is "in your opinion." The C# compiler will trust you when it builds your application, but the runtime is more suspicious and will actually check that this is the case when your application runs. If the type of object in memory does not match the cast, the runtime will throw an InvalidCastException, as described in the preceding section. You should be prepared to catch this exception and handle it appropriately if it occurs.

However, catching an exception and attempting to recover in the event that the type of an object is not what you ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required