Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast different objects and call a method in same line?

Tags:

c#

I have the code:

        foreach(var o in objects)
        {
            o.Update(time);

            if(o is Portal)
            {
                var a = (Portal)o;
                a.Interact(ref player, player.Interact);
            }
            else if(o is Enemy)
            {
                var e = (Enemy)o;
                e.Update(time, player);
            }
        }

I don't know if anything like this is possible?

I want to do it in one line. This is what I have in mind:

(Enemy)o => Update(time, player);

I know it's stupid but I want something similar. The method that has player as a parameter is unique to the Enemy object. I have to parse to call it.

like image 667
Emily Avatar asked Jan 12 '17 09:01

Emily


2 Answers

You can make your loop simpler (in case you use C# 6 or higher):

foreach(var o in objects)
{
    o.Update(time);

    (o as Portal)?.Interact(ref player, player.Interact);
    (o as Enemy)?.Update(time, player);           
}

For C# 5 or lower you should use:

foreach(var o in objects)
{
    o.Update(time);

    if (o is Portal)
    {
        ((Portal)o).Interact(ref player, player.Interact);
    }
    else if(o is Enemy)
    {
        ((Enemy)o).Update(time, player);
    }
}

In this case you have less lines of code but you cast two times.

You can cast only one time:

foreach(var o in objects)
{
    o.Update(time);

    var e = o is Portal;
    if (e != null)
    {
        e.Interact(ref player, player.Interact);
    }
    else
    {
        ((Enemy)o).Update(time, player);
    }
}
like image 85
Roman Doskoch Avatar answered Nov 14 '22 22:11

Roman Doskoch


You can replace those two lines with a single line as follows:

else if(o is Enemy)
{
    ((Enemy)o).Update(time, player);
}
like image 25
Chris Pickford Avatar answered Nov 14 '22 21:11

Chris Pickford