4

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?

Martin
  • 12,469
  • 13
  • 64
  • 128
  • 2
    2) - `typeof(IConvertible).IsAssignableFrom(typeof(T))` 4) - yes, serialize/deserialize instead of `.ToString()` / `Parse()` – Vladi Pavelka Jul 03 '18 at 21:01
  • 1
    Don't reinvent the wheel your own "IParsable". What you look for is serialization/deserialization. Not sure about what (de)serializers Unity3D comes with, though. What you should do is using a serializer (of your choice) to serialize data (objects) into some text representation. The respective deserializer associated with the serializer you chose can be used to derserialize that text representation back to an object. I you like/want Json, look into using Json.NET (again, not sure if it is usable with Unity3D/Mono) –  Jul 03 '18 at 21:01

1 Answers1

2

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.

Semimono
  • 664
  • 1
  • 6
  • 14