F# Downcast and upcast Example

Cast objects in the type hierarchy with the upcast and downcast keywords.

Downcast, upcast. Imagine a tree. This is not a palm tree or an oak tree. It is a type hierarchy, a tree of types that an individual type inherits from.

With upcast and downcast, we traverse this tree and change the type of an object. An int is a subtype of obj. So we can move up and down between int and obj.

An example. Let us begin with a simple example that uses upcast and downcast. We create a variable with value 5. Then we cast it.

Upcast: We use upcast on the int to move upwards in the type hierarchy to obj (which is the root object type).

Downcast: Next we move back down from obj to int with the downcast operator. It works from less derived, to more derived.

F# program that uses upcast, downcast let value = 5 printfn "%A" value // With upcast we move up the type hierarchy. // ... And int inherits from obj to this cast is valid. let valueObj = upcast value : obj printfn "%A" valueObj // With downcast we move down the type hierarchy. // ... We move down from obj to its derived type int. let valueInt = downcast valueObj : int printfn "%A" valueInt Output 5 5 5

Type match. It is wonderful to be able to cast an object. But how do we know what type an obj is? We can use a match construct with a special type-testing operator.

Here: Think of text() as a function that receives and object and returns a special string message if that object is of string type.

F# program that uses match on types let value = "carrot" // Cast the string to an obj. let valueObj = upcast value : obj // Match the type of the obj. // ... See if it is a string or not. let text (v : obj) = match v with | :? string -> "Is a string" | _ -> "Not a string" // Call text function with object. printfn "%A" (text valueObj) Output "Is a string"

An error. Be careful with the syntax when casting in F#. If you omit a type or omit the ":" part of a downcast or upcast statement, a scary problem will appear.

However: To fix the problem, be careful to review the syntax of your casting expressions to match a compiling example.

Text: Error FS0013: The static coercion from type 'a to 'b involves an indeterminate type based on information prior to this program point. Static coercions are not allowed on some types. Further type annotations are needed.

A summary. Types, and casting types to other types, is a complex process. With upcast and downcast and type pattern-matching operators, we traverse the type tree.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to