Lecture overview -- Keyboard shortcut: 'u'  Previous page: Static and dynamic types in C# -- Keyboard shortcut: 'p'  Next page: Examples of type test and type conversion -- Keyboard shortcut: 'n'  Lecture notes - all slides and notes together  slide -- Keyboard shortcut: 't'  Textbook -- Keyboard shortcut: 'v'  Help page about these notes  Alphabetic index  Course home  Page 33 : 40
Object-oriented Programming in C#
Specialization, Extension, and Inheritance
Type test and type conversion in C#

It is possible to test if the dynamic type of variable v is class type C

There are two ways to convert (cast) one class type to another

  • v is C

    • True if the variable v is of dynamic type C

    • Also true if the variable v is of dynamic type D, where D is a subtype of C

  • (C)v

    • Convert the static type of v to C in the given expression

    • Only possible if the dynamic type of v is C , or a subtype of C

    • If not, an InvalidCastException is thrown

  • v as C

    • Non-fatal variant of (C)v

    • Thus, convert the static type of v to C in the given expression

    • Returns null if the dynamic type of v is not C, or a subtype of C

The typeof operator can be applied on a typename to obtain the corresponding object of class Type

The Object.GetType instance method returns an object of class Type that represents the run-time type of the receiver.