C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
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"
However: To fix the problem, be careful to review the syntax of your casting expressions to match a compiling example.
Quote: 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 (Visual Studio).