Matthew The Terrible
Matthew The Terrible

Reputation: 1643

IEnumerable<> to List<> Cannot Resolve symbol Add

I am having an issue with classes that implement an interface that has a list of type some other interface. Tried to create a simple example below.

    public interface IPerson
{
    IEnumerable<IPersonEntry> Persons { get; set; }
    DateTime LastUpdated { get; set; }
}

public class PersonType1 : IPerson
{
    public IEnumerable<IPersonEntry> Persons { get; set; }
    public DateTime LastUpdated { get; set; }

    public PersonType1()
    {
        Persons = new List<NormalEntry>();
    }
}

public class PersonType2 : IPerson
{
    IEnumerable<IPersonEntry> Persons { get; set; }
    public DateTime LastUpdated { get; set; }

    public PersonType2()
    {
        Persons = new List<SomethingDifferent>();
    }
}

public interface IPersonEntry
{
    string Name { get; set; }
}

public class NormalEntry : IPersonEntry
{
    // some other props

}

public class SomethingDifferent  : IPersonEntry
{
    // something different
}

public class SomeOtherClass
{
    public SomeMethod()
    {
        PersonType2 p2 = new PersonType2();
        p2.Persons.Add(new SomethingDifferent{
            // blah = 5;
        })

    }
}

But in my SomeOtherClass method I want to be able to add to the List but its still getting treated like IEnumerable and not List<>. So I can't add to it. Any help would be greatly appreciated.

Upvotes: 0

Views: 3889

Answers (2)

aufziehvogel
aufziehvogel

Reputation: 7297

Adding to Selman22's answer: The point is that the publicly visible definition of PersonType2.Persons is an IEnumerable, so it has to be treated like an IEnumerable - even if you chose List as an implementation for it. And as Selman said, you cannot add to an enumerable.

Upvotes: 2

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101680

You can't add to an IEnumerable<T>. Add method is defined in IList<T>, so you need to change your parameter type:

IList<IPersonEntry> Persons { get; set; }

Upvotes: 8

Related Questions