Search code examples
c#dictionarygenerics

Return a generic type from various lists


I'm not sure if this is possible or not but I have a couple of dictionaries of different value types.

public Dictionary<int, Type1> type1;
public Dictionary<int, Type2> type2;

And I want to be able to use generics to grab an object of a specific type.

public T Get<T>(int ID)
{
    // somehow find the correct dictionary and return its value
}

I could use a switch statement but is there a smarter way?


Solution

  • You can try using reflection, if those fields are class fields in the same class as the Get method.

    Example implementation:

    public class TestArea
    {
        public Dictionary<int, Type1> type1 = new Dictionary<int, Type1> { { 1, new Type1() } };
        public Dictionary<int, Type2> type2 = new Dictionary<int, Type2> { { 1, new Type2() } };
        
        public T Get<T>(int ID)
        {
            var dictionaryType = typeof(Dictionary<int, T>);
    
            var dictionaryProperty = GetType()
                .GetFields()
                .FirstOrDefault(x => x.FieldType == dictionaryType);
    
            if (dictionaryProperty is null) throw new Exception("No dictionary found!");
    
            var dictionary = (Dictionary<int, T>)dictionaryProperty.GetValue(this);
    
            return dictionary[ID];
        }
    }