Why ISaveable interface isn't generic?

Hi guys,
I’m just wondering why ISaveable interface uses object instead of generic types? I didn’t check details of saving system implementation so maybe there is some specific reason why we are working on objects instead of generic types but IMHO using public class ISaveable where both methods will use same type would be much easier and there will be no need to casting in RestoreState method. I will be glad if you tell me the reason why you decided to do this in that way.


With Generic classes (and interfaces), a new class is created for each instance where we use the class… These classes are not interchangeable.
You can see this in action with the following piece of code, implementing variations on the Generic class List:

List<string> stringList=new List<string>();
List<int> intList = new List<int>();
//this will not compile 
stringList = intList;

In this case, A List is a completely different class than a List.

It can be further demonstrated with a Generic static…

public class ValueTest
public static int MyValue;

void Start()
    ValueTest<int>.MyValue = 1;
    Debug.Log($"{ValueText<int>.MyValue} = {ValueTest<string.MyValue}");

Your console will print 1 = 2 as these values are actually distinct to each created class.

The same will apply to ISaveable…
If you made this interface generic:

public interface ISaveable<T>
      T CaptureState();
      void RestoreState(T state);

Then suppose Health returned a float, and Inventory returned a list of InventoryItems…

public class Health: Monobehavior, ISaveable
public class Inventory: MonoBehavior, ISaveable<List>

Our master CaptureState and RestoreState objects would have to explicitly look for each ISaveable by type AFTER casting the value retrieved to that type (which it will have no way of knowing).

I actually tried to make a generics based saving system and hit a brick wall.

1 Like

Thanks, Brian it totally make sense for me.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms