IBot
IBot

Reputation: 364

How can i return a generic List<T> from a generic method<T>()

Good morning,

I have a class Product{} that has a Dictionary:

Dictionary<Type, List<IPropertyItem>> extensions;

I save my data with this method:

public void SaveItem<T>(T item)
    {
        Type currentType = typeof(T);

        if (!extensions.ContainsKey(currentType))
        {
            extensions.Add(currentType, new List<IPropertyItem>());
        }

        if (currentType == typeof(Discount))
        {
            Discount newDiscount = (Discount)Convert.ChangeType(item, typeof(Discount));                
            extensions[currentType].Add(newDiscount);
        }
        else if(currentType == typeof(Tax))
        {
            Tax newTax = (Tax)Convert.ChangeType(item, typeof(Tax));
            extensions[currentType].Add(newTax);
        }
        else if(currentType == typeof(Size))
        {
            Size newSize = (Size)Convert.ChangeType(item, typeof(Size));
            extensions[currentType].Add(newSize);
        }           
    }

now i want to get a list of a certain value type stored in my Dictionary, i mean i want that the method returns me a List like this function:

public List<T> GetExtensionsDictionary<T>()
    {
        Type currentType = typeof(T);
        List<T> returnedList = new List<T>();

        if (!extensions.ContainsKey(currentType))
        {
            return null;
        }

        return extensions[T];            
    }

The method that is calling above is:

List<Discount> myDiscounts = myProduct.GetExtensionsDictionary<Discount>();

thnks,

any help will be appreciated...

Upvotes: 0

Views: 91

Answers (1)

bfair
bfair

Reputation: 1111

I believe this is all you want:

public List<T> GetExtensionsDictionary<T>()
{
    Type currentType = typeof(T);
    List<T> returnedList = new List<T>();

    if (!extensions.ContainsKey(currentType))
    {
        return null;
    }

    return extensions[currentType].Cast<T>().ToList();            
}

You have to index into extensions with currentType not T because T is a generic parameter and you need the runtime type that you get with typeof.

You can use the linq methods Cast and ToList to turn the collection at currentType in the dictionary into a List<T>. This is making a copy of the list, so be mindful of performance considerations.

Make sure you are using System.Linq;

Upvotes: 3

Related Questions