C#C
C#2y ago
Camster

Generics without Casting

Is there any possible way to do what the code below is doing with generics, but without the casting?

public interface IItemCollection 
{
    int AddItem<T>(T item);
    T GetItem<T>(int id);
}

public class ItemCollection : IItemCollection {
    private Dictionary<Type, Dictionary<int, object>> _items = new();

    public int AddItem<T>(T item) 
    {
        var dictionary = GetDictionary<T>();
        int next = dictionary.Keys.Max() + 1;
        dictionary.Add(next, item);
        return next;
    }

    public T GetItem<T>(int id) 
    {
        var dictionary = GetDictionary<T>();
        return (T)dictionary[id];
    }

    private Dictionary<int, object> GetDictionary<T>() 
    {
        if (!_items.ContainsKey(typeof(T)))
            _items.Add(typeof(T), new Dictionary<int, object>());
        return _items[typeof(T)];
    }
}
Was this page helpful?