Sean Thoman
Sean Thoman

Reputation: 7489

Implicit conversion of collections

If I define an explicit conversion operator between two types, shouldn't it follow that I can explicitly convert between collections of those types? Ie.

    public static explicit operator FooEntity(Entity entity)
    {
        FooEntity e = new FooEntity(entity);
        return e; 
    }

And thus I could do this,

    IEnumerable<Entity> entities = GetEntities();
    IEnumerable<FooEntity> fooEntities = (IEnumerable<FooEntity>)entities;

or

    IEnumerable<FooEntity> fooEntities = entities as IEnumerable<FooEntity>

Is this possible somehow or do I also have to create my own operator to convert between the collections? I am getting a run-time error that says the conversion is not possible.

Thanks.

Upvotes: 3

Views: 1572

Answers (1)

John Rasch
John Rasch

Reputation: 63445

C# does not support this method of generic type variance on collection assignment, you'll have to use something like:

IEnumerable<FooEntity> fooEntities = entities.Select(e => (FooEntity)e);

Upvotes: 3

Related Questions