Solved

Cast Generic List to Specific List

Posted on 2010-11-17
5
620 Views
Last Modified: 2013-12-17
Hello everybody!

I have an issue casting Generic List into Specific List. The details are below:

Class Person
public class Person 
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Open in new window


and class People
 
public Class People : List<Person>
{
    public static People listFromDataBase()
    {
        //Connects to DataAccess Layer to get all people
    }
}

Open in new window


and when I filter the list using FindAll like in the example:
 
public static void main(string[] args)
{
    People p = People.listFromDataBase();
    p = (People) p.FindAll(FilterByAge);

    foreach(Person per in p)
    {
        Console.WriteLine("Name: {0}, Age: {1}", per.Name, per.Age.ToString());
    }
}

private bool FilterByAge(Person p)
{
    if (p.Age > 18)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Open in new window


It throws an Exception in the cast and I don't know why. This is the Error Message:

Unable to cast object of type 'System.Collections.Generic.List`1[Person]' to type 'People'.


In advance many many thanks :)
0
Comment
Question by:karelog
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
5 Comments
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 34155951
You can't cast from a less-derived class into a derived class.

i.e.
class ObjectA
{
  int SomeMethod() { return 1; }
}
class ObjectB : ObjectA
{
  int SomeOtherMethod() { return 2; }
}
int main()
{
  ObjectB objb = new ObjectB();
  ObjectA obja = (ObjectA)objb;
  // The above cast is valid because objb is know to implement at least all of ObjectA

  ObjectA obja = new ObjectA();
  ObjectB objb = (ObjectB)obja;
  // This cast is invalid because obja is not known to also implement methods in ObjectB
}

Open in new window

0
 
LVL 22

Expert Comment

by:p_davis
ID: 34155987
p = p.FindAll(FilterByAge) as People;

0
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 500 total points
ID: 34155994
It throws it because it cannot upcast from List<Person> to People. People is a derived type, and you can't upcast from a base type to a derived type.

If you want to have FindAll return a People object then you will need to override the base class implementation:

    public class People : List<Person>
    {
        public static People listFromDatabase()
        {
            // ...
        }

        public new People FindAll(Predicate<Person> match)
        {
            People people = new People();
            people.AddRange(base.FindAll(match));

            return people;
        }
    }

Open in new window

0
 
LVL 18

Expert Comment

by:Richard Lee
ID: 34156056
Contravariance for generic types is not support in .NET 3.5. You are trying to convert a base type into a derived type. The reverse would work which is covariance.

For you code to work you would probably need a method that converts a List<Person> to a People object.

DaTribe
public People ConvertToPeople(IEnumerable<Person> persons)
{
   People p = new People();
   foreach(var person in persons)
   {
      p.Add(person);
   }

   return p;
}

Open in new window

0
 

Author Closing Comment

by:karelog
ID: 34158319
Thanks!!

this worked perfect!!

I hope that the .NET guys make this posible in the new frameworks
0

Featured Post

Application Discovery Service in AWS

In the era of the cloud, customers migrating away from their existing on-premise infrastructure. This requires lots of planning, strategies, and effort to identify their existing resources and determine how best to migrate.  Datacenter migrations happen in four phases -

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will show, step by step, how to integrate R code into a R Sweave document
Q&A with Course Creator, Mark Lassoff, on the importance of HTML5 in the career of a modern-day developer.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

623 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question