C# Method Argument Always Receive as a Value, Not a Reference

87 Views Asked by At

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!

1

There are 1 best solutions below

1
MarkSouls On

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.