9.9. Casting for reference types

Like Java, both C#'s variables and objects are typed. [7] Assuming that there are two classes Vehicle and Car, and Vehicle is the superclass of Car, you can have an object of class Car being referred to by a variable of type Vehicle. And, like Java, you cannot have a Vehicle object (object of a super type) referenced by a variable of type Car (variable of subtype). Similarly, you can explicitly cast an object to a superclass type.

[7] This is not the case for some OO programming languages. In Ruby, for example, variables have no types. A variable can refer to any object of any class.

Get From Java to C#: A Developer's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.