Check out and contribute to CodePedia, the wiki for developers.
*/
*/

The Official Programmer's Heaven Blog

Theme Graphic
Theme Graphic

The Official Programmer's Heaven Blog

The blog where the Programmer's Heaven team post stuff.

Subscribe

Author

Often knowledgable, sometimes wise, occasionally funny. The Programmer's Heaven blog team post about a whole range of topics, from practical advice on concurrency control to introductions to lesser known concepts such as functional programming. Don't forget to comment on the posts and let them know what you think, like and hate!

Archive

Tags


Delete Blog
Posted on Saturday, October 20, 2007 at 2:32 PM

Understanding Casting and Coercion in C#

A little while back I answered a post on the PH forums about why you might need to use casts, and particularly why you might need to upcast. This article is a tidied up and extended version of my answer.

Variable vs. value types

Suppose we write a class B that inherits from class A. We can then say that B is a subclass of A. That means that you can use an object of type B anywhere that you can use an object of type A.

To understand upcasting and downcasting better, we need to introduce the idea of container or variable types and contrast them to value types. A variable may contain a value. For reference types, the variable has a type that states what type of value it can contain. However, the type of the value may be different; namely, it may be a subtype of the variable type. Let's clarify this with some examples.

A foo = new A(); // Variable type A, value type A
B bar = new B(); // Variable type B, value type B
A baz = new B(); // Variable type A, value type B...


corner
© 1996-2008 CommunityHeaven LLC. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
North American business development: Nicolai Wadstrom. Publisher: Lars Hagelin.
Resource Listings