Get the class name without casting the type
bauss
jacobbauss at gmail.com
Tue Nov 15 14:09:01 UTC 2022
On Tuesday, 15 November 2022 at 11:42:59 UTC, Alexander Zhirov
wrote:
> Is there any way to get the name of class B?
>
> ```d
> interface A {
> string text();
> }
>
> class B : A {
> override string text() {
> return ": It's ok!";
> }
> }
>
> void main() {
> A[] a = cast(A[]) new B[3];
> B b = new B();
> fill(a, b);
> foreach (val ; a) {
> writeln(typeof(val).stringof, val.text());
> }
> }
> ```
>
> Output:
>
> ```sh
> A: It's ok!
> A: It's ok!
> A: It's ok!
> ```
If you cast to Object and use classinfo.name then you get the
expected result of B.
```d
interface A {
string text();
}
class B : A {
override string text() {
return ": It's ok!";
}
}
void main() {
A[] a = cast(A[]) new B[3];
B b = new B();
fill(a, b);
foreach (val ; a) {
writeln((cast(Object)val).classinfo.name, val.text()); //
Here is the magic.
}
```
Output:
```
onlineapp.B: It's ok!
onlineapp.B: It's ok!
onlineapp.B: It's ok!
```
More information about the Digitalmars-d-learn
mailing list