C#'s 'is' equivalent in D
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Thu Oct 10 15:56:40 UTC 2019
On Thursday, October 10, 2019 9:47:58 AM MDT Just Dave via Digitalmars-d-
learn 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...
D's solution is basically the same as C++'s solution. You cast and then
check whether the result is null. So,
if(cast(Person)obj !is null)
{
}
or since using a pointer or reference in an if condition checks whether it's
null or not
if(cast(Person)obj)
{
}
and you can even declare a variable that way if you want. e.g.
if(auto person = cast(Person)obj)
{
}
When D's is is used to compare two objects, it checks whether they're equal
bitwise. So, it's typically used for comparing pointers or references for
equality (whereas using == with references would compare the objects
themselves for equality).
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list