-3

I am working on Unity C# and trying to make my own Serializable Dictionary to use with ScriptableObject s. I am using a generic method and a generic indexed class to do that. I have an Add function that takes in a Key and a Value, both of any data type, quite similar to C# Dictionary. I have also created my own KeyValuePair class to go with it.

However, whenever I pass in a List as a Value it is received as a reference of course. But I want to receive some of the reference based Types & Data Types as a Value only. In a non-generic method I can simply create a new list out of it as soon as I would received it but apparently I can't do that with a generic method.

public bool Add(in S Key, in T Value)
{

    // Apparently I can't do this here:
    
    // T ReceivedValue = new T(Value);

    for (int i = 0; i < KeyValuePairs.Count; i++)
    {
        if (KeyValuePairs[i].Key.Equals(Key))
        {
            Debug.LogError("Key '" + Key + "' already exists in the AMADictionary.");
            return false;
        }
    }

    KeyValuePairs.Add(new AMAKeyValuePair<S, T>(Key, Value));
    return true;
}

To achieve this I always have to do this process in the parenthesis while calling the Add method which is slow and always one extra thing to keep in mind. Is there a way I can achieve this within the method?

Thanks everyone!

derHugo
  • 83,094
  • 9
  • 75
  • 115
  • I am sorry but I am not asking for a fix to a problem. Instead I myself require code or direction for how to achieve said possibility. What I am looking for is a working code for the commented section in the code provided above. – Abdul Moiz Haroon Aug 30 '21 at 23:49
  • I think you could find your answer somewhere between [How to determine whether T is a value type or reference class in generic?](https://stackoverflow.com/questions/7580288/how-to-determine-whether-t-is-a-value-type-or-reference-class-in-generic), [How do I clone a generic list in C#?](https://stackoverflow.com/questions/222598/how-do-i-clone-a-generic-list-in-c), [Clone a generic type](https://stackoverflow.com/questions/7501758/clone-a-generic-type) ... and similar questions. You know btw that this anyway will only be serializable if both `S` and `T` are serializable, right? – derHugo Aug 31 '21 at 07:55

1 Answers1

0

One possible way is to use System.ICloneable interface for class T.

public class Test<S, T> where T : ICloneable
{
    public void Add(in S key, in T value)
    {
        T ReceivedValue = (T)value.Clone();

        /* ... */
    }
}

In this case you will have to implement Clone method for all possible value types.

MarkSouls
  • 982
  • 4
  • 13
  • Will not be possible if OP wants to use base value types like `int`, `byte`, `bool`, `float` etc – derHugo Aug 31 '21 at 07:49