Solved

Cast Generic List to Specific List

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

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
The viewer will learn how to implement Singleton Design Pattern in Java.
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

758 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

21 Experts available now in Live!

Get 1:1 Help Now