Apprentice Squirrel
Apprentice Squirrel

Reputation: 23

Problem with lists, polymorphism and casting in C#

Good afternoon, I am looking to transfer a list of objects that implement a certain interface ("IRecord"), what I do is to filter in a new list the objects that implement the interface in the following case "IEntry", until there is no problem, however, I have problems when I try to caste the filtered list to the type "IList" to use the properties that this last one has, this produces an exception, how can I solve this, Is there a way to avoid going through the whole list, and create a new one again?

interface IRecord
{
    string Details { get; set; }
}

interface IEntry : IRecord
{
    decimal TotalValue { get; set; }
}

interface IEgress : IRecord
{
    string Type { get; set; }
}

class Entry : IEntry
{
    public string Details { get; set; }
    public decimal TotalValue { get; set; }

    public void Foo() { }
}

class Egress : IEgress
{
    public string Details { get; set; }
    public string Type { get; set; }
}

This is the code I am trying to execute

var records = new List<IRecord>() { new Entry() { Details = "foo" }, new Egress() { Details = "bar" } };

var filteredList = records.Where(entry => entry is Entry).ToList();

var sum = (IList<IEntry>)filteredList;
var x = sum.Sum(en => en.TotalValue);

Error Desc.

Upvotes: 1

Views: 112

Answers (1)

Squirrel5853
Squirrel5853

Reputation: 2406

As already mentioned in comments you can Cast your query before calling ToList()

var filteredList = records.Where(entry => entry is Entry).Cast<IEntry>().ToList();

So the end result would be

var records = new List<IRecord>() 
{ 
    new Entry() { Details = "foo", TotalValue = 12 }, 
    new Egress() { Details = "bar" } 
};

var filteredList = records.Where(entry => entry is Entry).Cast<IEntry>().ToList();

var sum = (IList<IEntry>)filteredList;
var x = sum.Sum(en => en.TotalValue);

I added a value to your Entry type too, which then allows you to prove your code works :D

Here is a link to Microsoft document on inheritance

Upvotes: 2

Related Questions