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.
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);
}
}
You can replace those two lines with a single line as follows:
else if(o is Enemy)
{
((Enemy)o).Update(time, player);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With