LINQ .Cast() extension method fails but (type)object works.

Posted by Ben Robinson on Stack Overflow See other posts from Stack Overflow or by Ben Robinson
Published on 2010-05-12T13:59:53Z Indexed on 2010/05/12 14:04 UTC
Read the original article Hit count: 209

To convert between some LINQ to SQL objects and DTOs we have created explicit cast operators on the DTOs. That way we can do the following:

DTOType MyDTO = (LinqToSQLType)MyLinq2SQLObj;

This works well.

However when you try to cast using the LINQ .Cast() extension method it trows an invalid cast exception saying cannot cast type Linq2SQLType to type DTOType. i.e. the below does not work

List<DTO.Name> Names = dbContact.tNames.Cast<DTO.Name>()
                                               .ToList();

But the below works fine:

DAL.tName MyDalName = new DAL.tName();
DTO.Name MyDTOName = (DTO.Name)MyDalName;

and the below also works fine

List<DTO.Name> Names = dbContact.tNames.Select(name => (DTO.Name)name)
                                               .ToList();

Why does the .Cast() extension method throw an invalid cast exception? I have used the .Cast() extension method in this way many times in the past and when you are casting something like a base type to a derived type it works fine, but falls over when the object has an explicit cast operator.

© Stack Overflow or respective owner

Related posts about c#

Related posts about explicit-cast-operator