简体   繁体   中英

Wrapping or Copying During User-Defined Casts

I have a custom collection class that implements IDictionary<TKey, TValue> and actually uses System.Collections.Generic.Dictionary<TKey, TValue> as the underlying storage for my custom collection. I wanted an implicit cast to Dictionary and an explicit cast from it to my custom class.

What I'm not completely sure about is when casting to Dictionary<TKey, TValue> should I be returning the underlying collection, or copy the underlying dictionary to a new object and return that value? Likewise in the opposite direction, from Dictionary<TKey, TValue> , should I be wrapping the casted dictionary or copy the values into a new dictionary?

My implementation isn't immutable, but instead just adds some additional features. I personally cannot see a problem that would arise from either method of conversion. In this specific case a modification of the underlying collection won't cause a problem with the state of the wrapped collection. Therefore is there a non-performance based reason to use one method over the other?

Example Class:

public class MyDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
    ...
    public static implicit operator Dictionary<TKey, TValue>(MyDictionary<TKey, TValue> myDict)
    {
        return myDict.dictionary;
    }

   //OR

    public static implicit operator Dictionary<TKey, TValue>(MyDictionary<TKey, TValue> myDict)
    {
        return new Dictionary(myDict);
    }

    ...
}

PS: I'm not looking for "best-practice" or a subjective answer. If the answer is "NO, there is no objective non-performance backed difference in using one method or the other" that is an acceptable answer.

Aside from performance, the only concern is mutability. As your implementation is not immutable, the first way is probably more correct as it allows direct mutability of the underlying dictionary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM