Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return multiple types from single method in C#

I am working on a basic game and 2D engine in Xna/C# and I am trying to simplify a few things in it. I have a base class of Entity2D from the engine and two classes specific to the game that inherit from it: Tower and Enemy. In my engine, rather than having two separate lists, one for Towers and one for Enemies I would like to combine them together into a single generic list. I then I have the problem of when I need to return a Tower from the list or an Enemy from the list. I know that I can use typecasting from the engine object:

class Entity2D {...} //engine object
class Tower : Entity2D {...} //game specific
class Enemy : Entity2D {...} //game specific

//In engine:
public Entity2D GetEntity(int index) { ...return objects[index];}

//Somewhere in the game
{
    Enemy e = GetEntity(0) as Enemy;
    if(e != null)
        //Enemy returned

    Tower t = GetEntity(0) as Tower;
    if(t != null)
        //Tower returned
}

Of course this seems really inefficient.

I have also looked into the is keyword a bit, and it seems that works like so:

Entity2D entity = GetEntity(0);
if(entity is Tower)
{
    Tower t = (Tower)entity;
    t.DoTowerThings();
}

Still that results in returning a base object and using even more memory to create a second object and typecast into it.

What would really be nice is if there is a way to do something like this:

//In engine:
public T GetEntity(int index) 
{ 
    if(T == Tower) //or however this would work: (T is Tower), (T as Tower), etc
        return objects[index] as Tower;
    else if(T == Enemy) 
        return objects[index] as Enemy;
    else return null;
}

Enemy e = GetEntity(0);

But then that breaks the engine portion of having the engine and game be seperate

I am looking for the clearest as well as most memory efficient way to go about this while still having Entity2D be engine based and avoid having Tower or Enemy in the engine at all.

Any suggestions would be welcome!

Thanks!

like image 477
Colton Avatar asked May 01 '26 01:05

Colton


1 Answers

Nearly there!

//In engine:
public T GetEntity<T>(int index) where T : Entity2D
{ 
    return objects[index] as T;
}
//Somewhere else:
Enemy e = GetEntity<Enemy>(0);

Note: if objects[index] is NOT a T, it will return null instead.

However, if it was my game, I would just keep separate lists for each type of object.

like image 73
It'sNotALie. Avatar answered May 02 '26 14:05

It'sNotALie.