C#'s 'is' equivalent in D

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Oct 10 16:33:47 UTC 2019


On Thu, Oct 10, 2019 at 03:58:02PM +0000, jmh530 via Digitalmars-d-learn wrote:
> On Thursday, 10 October 2019 at 15:47:58 UTC, Just Dave wrote:
> > In C# you can do something like:
> > 
> > 
> >     if (obj is Person)
> >     {
> >         var person = obj as Person;
> >         // do stuff with person...
> >     }
[...]
> You mean something like below:
> 
> class Person {
>     int id;
>     this(int x) {
>         id = x;
>     }
> }
> 
> void main() {
>     auto joe = new Person(1);
>     if (is(typeof(joe) == Person)) {
>         assert(joe.id == 1);
>     }
> }

Unfortunately, typeof is a compile-time construct, so this will not work
if you're receiving a Person object via a base class reference. The
correct solution is to cast the base class to the derived type, which
will yield null if it's not an instance of the derived type.


T

-- 
LINUX = Lousy Interface for Nefarious Unix Xenophobes.


More information about the Digitalmars-d-learn mailing list