Click here to Skip to main content
15,849,996 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:

I have a "T GetConfig<t>" method. This could return a base type or a List<int>

I now have a case where T is List<int>, my result is List<int>, but I "cannot cast List<int> to Type T".

Is there an easy way around this?
Or do I have to create a "List<t> GetConfigList<t>" method?


What I have tried:

Well this didn't work:
(T)SelectMenu.SelectByIdAndSelected(menuId.Value, (int)config.Value)
Updated 2-Sep-16 1:27am
Mehdi Gholam 2-Sep-16 6:00am    
Generally you should return the one thing, if not return object and have the caller figure it out.
Tomas Takac 2-Sep-16 6:02am    
I'm afraid you have to add more context. For example how does you example relate to the GetConfig method?
Richard MacCutchan 2-Sep-16 6:09am    
You can't because the compiler needs to know what is being returned. If you really need this then you can change it to return some composite object, and let the caller figure it out. Alternatively, create another method that always returns a list.

1 solution

I'm very proud of myself for this:

I didn't explain it fully, but the methods do need to do different things to get the base type or list type setting. I could have shunted this down to the Configuration class, but I had already started creating a second List method anyway.

Separating the <list<T>> from the <T> method is prolly a good thing anyway so each method doesn't get too complex

//This is an object in my MembershipUserClass
public T GetCompanySetting<t>(string key)
    //Check if the generic type
    if (typeof (T).IsGenericType && typeof (T).GetInterfaces().Contains(typeof (System.Collections.IEnumerable)))
        //Assume the enumerable is generic.  The caller should know this
        var t = typeof (T).GetGenericArguments()[0];

        //Only way to use t is with reflection (this was the knowledge I was missing)
        MethodInfo method = typeof (Configuration).GetMethod("QueryList").MakeGenericMethod(new[] {t});

        //Convert works fine here 
        return (T)method.Invoke(null,new object []{ CompanyId, null, "AccountManagement", key, null});
    //Normal call with T not enumerable.  This method does check for nullable types so it will return the correct default if the setting does not exist.  Again, the caller should know this
    return Configuration.Query<t>(CompanyId, null, "AccountManagement", key);


I wanted this method to be "on rails" for the caller. My colleague who will use this method writes in VB and isn't too familiar with generics.

Thanks for taking a look, guys ^_^
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900