C#'s 'is' equivalent in D

jmh530 john.michael.hall at gmail.com
Thu Oct 10 15:58:02 UTC 2019


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...
>     }
>
> where you can check the type of an object prior to casting. 
> Does D have a similar mechanism? It's so widely useful in the 
> C# realm that they even added syntactic sugar to allow:
>
>     if (obj is Person person)
>     {
>         // do stuff with person...
>     }
>
> I would presume since D has reference objects there must exist 
> some mechanism for this...

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);
     }
}


More information about the Digitalmars-d-learn mailing list