Martin
Martin

Reputation: 397

Cast object in lambda expression

I'm trying to cast a List to my custom list which is ProjectList

IList<Project> projects = cm.GetOrAdd("projectList", () => (ProjectList)ProjectService.GetAllProjects().ToList(), new CacheItemPolicy(5));

ProjectList contains only:

public class ProjectList : List<Project>
{
    public override string ToString()
    {
        return string.Format("Projects: {0}", this.Count());
    }
}

However it's giving a runtime error that it cant cast the object.

Error:

System.Collections.Generic.List`1[sidc.Framework.Data.Entities.Project] can't be converted to type sidc.Framework.Web.Helpers.ProjectList.

Am I overseeing something? I'm using the lambda because my cm (CacheManager) will evaluate the Func<> when the object is not in cache.

Upvotes: 0

Views: 6654

Answers (2)

rasmeta
rasmeta

Reputation: 475

This is just how inheritance works - you can cast ProjectList to List<Project>, but not the other way - List<Project> is not of type ProjectList

Upvotes: 0

CodeCaster
CodeCaster

Reputation: 151588

You can't downcast a List<T> to any type that inherits from List<T>, because the runtime can't fill in the blanks for you. It wouldn't know how to create a "Dog" from an "Animal". That's what the compiler tries to tell you.

Add a constructor that accepts an enumerable of Project, and populates itself with that list:

public class ProjectList : List<Project>
{
    public ProjectList() { }
    public ProjectList(IEnumerable<Project> projects)
        : this()
    {
        this.AddRange(projects);
    }

    public override string ToString()
    {
        return string.Format("Projects: {0}", this.Count());
    }
}

Then change your lambda from:

() => (ProjectList)ProjectService.GetAllProjects().ToList() 

To:

() => new ProjectList(ProjectService.GetAllProjects())

But by introducing a concrete type (ProjectList for List<Project>) you're pretty much annihilating the use of generics: not having to specify a type per record type. You probably don't need ProjectList at all.

Upvotes: 3

Related Questions