Solved

Cast Generic List to Specific List

Posted on 2010-11-17
5
612 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
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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…

803 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