C#'s 'is' equivalent in D
jmh530
john.michael.hall at gmail.com
Thu Oct 10 16:49:28 UTC 2019
On Thursday, 10 October 2019 at 16:33:47 UTC, H. S. Teoh wrote:
> 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
Ah, you mean something like below:
class Person {
int id;
this(int x) {
id = x;
}
}
class Employee : Person {
int job_id;
this(int x, int y) {
super(x);
job_id = y;
}
}
void main() {
import std.stdio : writeln;
Person joe = new Employee(1, 2);
if (is(typeof(joe) == Employee)) {
writeln("here"); //not called in this case
}
}
More information about the Digitalmars-d-learn
mailing list