digitalmars.D.learn - Expression for: foo is derived from Clock
- Brother Bill (11/11) Feb 18 ```Object foo``` is a class instance, perhaps null, perhaps a
- Nick Treleaven (6/18) Feb 18 Use a cast:
- Brother Bill (10/29) Feb 18 That's it!
- Steven Schveighoffer (10/22) Feb 22 FYI, a very nice idiom for D:
```Object foo``` is a class instance, perhaps null, perhaps a
Clock or AlarmClock or Vegetable.
What is the expression to ask the boolean question:
Is foo of type Clock or a type derived from Clock, such as
AlarmClock?
I tried the obvious ```foo is Clock```, but this did not compile.
```
Error: type `Object` is not an expression
bool isClock = (o is Clock)
^
```
Feb 18
On Wednesday, 18 February 2026 at 14:49:56 UTC, Brother Bill wrote:```Object foo``` is a class instance, perhaps null, perhaps a Clock or AlarmClock or Vegetable. What is the expression to ask the boolean question: Is foo of type Clock or a type derived from Clock, such as AlarmClock?Use a cast: https://dlang.org/spec/expression.html#cast_classI tried the obvious ```foo is Clock```, but this did not compile. ``` Error: type `Object` is not an expression bool isClock = (o is Clock) ^ ```That use of `is` is a different expression: https://dlang.org/spec/expression.html#identity_expressions
Feb 18
On Wednesday, 18 February 2026 at 14:55:50 UTC, Nick Treleaven wrote:On Wednesday, 18 February 2026 at 14:49:56 UTC, Brother Bill wrote:That's it! ``` const(Clock) clock = cast(const Clock)o; ``` If clock is null, then o is either ```null``` or not derived from Clock. Otherwise o, such as AlarmClock will have access to only the Clock features of o.```Object foo``` is a class instance, perhaps null, perhaps a Clock or AlarmClock or Vegetable. What is the expression to ask the boolean question: Is foo of type Clock or a type derived from Clock, such as AlarmClock?Use a cast: https://dlang.org/spec/expression.html#cast_classI tried the obvious ```foo is Clock```, but this did not compile. ``` Error: type `Object` is not an expression bool isClock = (o is Clock) ^ ```That use of `is` is a different expression: https://dlang.org/spec/expression.html#identity_expressions
Feb 18
On Wednesday, 18 February 2026 at 15:05:16 UTC, Brother Bill wrote:On Wednesday, 18 February 2026 at 14:55:50 UTC, Nick Treleaven wrote:FYI, a very nice idiom for D: ```d if(auto clock = cast(const Clock)o) { // use clock in here as a `Clock` type } ``` This leaves no chance to use clock as a `null` reference. -SteveThat use of `is` is a different expression: https://dlang.org/spec/expression.html#identity_expressionsThat's it! ``` const(Clock) clock = cast(const Clock)o; ``` If clock is null, then o is either ```null``` or not derived from Clock. Otherwise o, such as AlarmClock will have access to only the Clock features of o.
Feb 22








Steven Schveighoffer <schveiguy gmail.com>