Search code examples
c#unity-game-engine.net-2.0

Forcing a Class to have a .Parse Method


TLDR Question:

How to cast a string to a specific type of object?

Long Question

I want to make a PlayerPrefs wrapper where I can store whatever data I want.

so it goes like this

void Set<T>(string Key, T Value)
{
   PlayerPrefs.SetString(Key, Value.ToString());
}

T Get<T>(string Key)// where T : IParseable
{
    //Code that checks for errors and throws exceptions
    return T.Parse(PlayerPrefs.GetString(Key));
}

The problem in this is that it "relies" on the data to be parseable (or implement IParseable that I invented XD) and primitive data types don't implement it even thought they all have a Parse Method

  1. Is there already an IParseable interface I can use?

  2. If not, is there a way to know if the T type is a primitive data type?

  3. Is there a better way to achieve what I want to do?

  4. Would it be better if I used JSON for this?


Solution

  • The comments are correct, you shouldn't be using ToString() and Parse. What you are doing (or trying to do) is serialization. Here are a couple of resources to look to for figuring out how to serialize and deserialize your data:

    If you use one of the above examples, the data should be serialized to a human-readable format. It's less efficient, but serializing to a string is already less efficient than serializing to bytes. If you need that level of efficiency, you shouldn't be using PlayerPrefs.