Passing base classes and their derived classes as arguments, and my weird hack

I have a working prototype for my save/load system in Unity but it relies on a weird hack I came up with. But if it works with a hack then I am clearly not doing something C# fundamentally cannot do, so I would really like to know what the non-hacky way of doing this is.

So, the short version is that I have Base class and Derived class. And I have a function, lets call it SaveGame(), in a third class. And I want SaveGame() to be able to take Base or Derived as an argument. If I make the function SaveGame(Base myBase) it rejects any attempt to invoke SaveGame(myDerived) [I don't have the code in front of my right now, so maybe it takes the argument but it can't access any of the Derived-specific elements, maybe; either way, not what I need it to do].

The hack I came up with is to put myDerived into an array of Base classes (of which it is the only entry), and then send the array to the function. So SaveGame is actually SaveGame(Base[] myBases). The array will accept either Base or Derived as an entry, and I can then pass the array to the function, and it can then process it as either Base or Derived.

It feels like the variable equivalent of money laundering to be honest! I spent hours trying to come up with a solution that used up/down-casting or trying to make a function that used generics but this was the only one that I could get working.

It works, but it feels wrong. Is there a more elegant way to do this?

​

EDIT:

I probably should have waited until I had my code in front of me before I posted. So, I need the SaveGame function to return the same type that it receives. So it will accept Derived as an argument, but then the variable needs to be cast into Derived to access Derived functionality, which means there is no way to return the modified Derived.

I've been fiddling around and I want it to look something like this: https://dotnetfiddle.net/XiBSMO (sorry if this doesn't look quite right, I normally only use C# in Unity and the formatting here is a bit different to what I am used to)

But that relies on invalid upcasting.

Posted Mar 25, 2019, 1:58 PM UTC · edited

325
Loading comments…