Is it possible to store different subclasses in one array?

Leonardo leotada523 at gmail.com
Mon Apr 13 04:15:04 UTC 2020


On Monday, 13 April 2020 at 01:47:11 UTC, Adam D. Ruppe wrote:
> On Monday, 13 April 2020 at 01:42:51 UTC, Leonardo wrote:
>> Is it possible to store different subclasses in one array?
>> In C#, we have this example, but how I do that in D?
>
> Did you try
>
> BaseItem[] GameItems;
> GameItems ~= new Weapon();
>
>
> yet?

Oh, thanks, this works. Now it seems obvious.
But fitting another question, this case is only representative, 
if I want to use one method present in only one of these classes 
like this:

  foreach (ref gi; GameItems)
{
     if (gi == Weapon)
         gi.Attack()
}

How would it be?


More information about the Digitalmars-d-learn mailing list