CJCoding With Joseph

Safe Downcast with Pattern Matching

Sometimes you must check an object's real type before using a method only the derived class has. The Animal and Dog classes are complete; only Dog has a Fetch() method. In Handler, finish TryFetch(Animal a) so it returns the result of Fetch() when the animal is actually a Dog, and returns Cannot fetch otherwise. Use the type-pattern a is Dog d. Do NOT write a Main method.

For a Dog the program prints:
Fetching
For a plain Animal it prints:
Cannot fetch

Expected Output:

Fetching
Topics:
Polymorphism
Code Editor
1
Tab to indent ยท Ctrl+Enter to run ยท Ctrl+Space to expand shortcuts (cw, cr, fori)

Your Output

Run your code to see the output here...

Test Cases

Run your code to see test case results.