Arkaine80
Arkaine80

Reputation: 186

Convert to a IList type from type specified in dictionary

I have 4 methods with different return types. I would like to get a count in a generic method, however, the casting I have tried is giving a compiler error

enum PayRecType {AA, AB, AC, AD};

private int GetDataPartCount(PayRecType useRecType)
{
    Dictionary<PayRecType, GetValuesStruct> mapAllGet = new Dictionary<PayRecType, GetValuesStruct>()
    {
        { PayRecType.AA, new GetValuesStruct() { RunMethod = GetAARecords, CastAsType = typeof(IList<DDF_AARecord>) } },
        { PayRecType.AB, new GetValuesStruct() { RunMethod = GetABRecords, CastAsType = typeof(IList<DDF_ABRecord>) } },
        { PayRecType.AC, new GetValuesStruct() { RunMethod = GetACRecords, CastAsType = typeof(IList<DDF_ACRecord>) } },
        { PayRecType.AD, new GetValuesStruct() { RunMethod = GetADRecords, CastAsType = typeof(IList<DDF_ADRecord>) } }
    };
    
    //this part works just fine
    var dataList = mapAllGet[useRecType].RunMethod();
    
    if (dataList == null)
    {
        return -1;
    }
    else
    {
        // this is not working as I need to cast it to get the count - but how?
        return ((mapAllGet[useRecType].CastAsType)dataList).Count;
    }
}

struct GetValuesStruct
{
    public Func<object> RunMethod {get;set;}
    public Type CastAsType {get;set;}
}

Upvotes: 1

Views: 123

Answers (1)

Guru Stron
Guru Stron

Reputation: 142048

Usually you can use non-generic interfaces for the cast. For example ICollection, which exposes Count property:

return ((ICollection)dataList).Count;

If it is not possible in your case, then you will need either to dive into reflection or to consider refactoring your GetValuesStruct.

Upvotes: 2

Related Questions