Solved

Cast Generic List to Specific List

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

If you haven’t already, I encourage you to read the first article (http://www.experts-exchange.com/articles/18680/An-Introduction-to-R-Programming-and-R-Studio.html) in my series to gain a basic foundation of R and R Studio.  You will also find the …
This article will show, step by step, how to integrate R code into a R Sweave document
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.

929 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now