I would like to create a "List" of items which contains unique Type
keys, keyed by the type of the item itself. I created a collection that holds a Dictionary<Type, V>
and manages it.
internal class TypeCollection<V>
{
public TypeCollection()
{
items = new Dictionary<Type, V>();
}
private Dictionary<Type, V> items;
public void Add<T>(T value) where T : V
{
items.Add(typeof(T), value);
}
public void Remove(Type type)
{
items.Remove(type);
}
public bool TryGetValue<T>(out T value) where T : V
{
if (items.TryGetValue(typeof(T), out V foundValue))
{
value = (T)foundValue;
return true;
}
value = default(T);
return false;
}
}
I have to iterate through the values. A for-loop
is not possible, because I have to access a value by its type but a foreach-loop
can do the job. I implemented the IEnumerable
interface
TypeCollection<V> : IEnumerable<V>
and added the required interface methods
public IEnumerator<V> GetEnumerator()
{
foreach (V value in items.Values)
{
yield return value;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
When I want to remove all the values from that collection I would have to implement this
public void Clear()
{
items.Clear();
}
As you might have noticed I was going to reinvent a Dictionary and why should I do that...
I created this
internal class TypeCollection<V> : Dictionary<Type, V>
{
public void Add<T>(T value) where T : V
{
Add(typeof(T), value);
}
public bool TryGetValue<T>(out T value) where T : V
{
if (TryGetValue(typeof(T), out V foundValue))
{
value = (T)foundValue;
return true;
}
value = default(T);
return false;
}
}
but I am not able to override the default Add
and TryGetValue
method. I would always have both methods, Add
and Add<>
so what is the "cleanest" way? I would like to hide the default Add
and TryGetValue
methods because there is no need to use them anymore.