© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
19 replies
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)];
    }
}
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)];
    }
}
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Multiple types in a params without casting?
C#CC# / help
4y ago
❔ Generics
C#CC# / help
3y ago
❔ Generics
C#CC# / help
3y ago
✅ Type Casting
C#CC# / help
4y ago