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 =
The Cast<> extension method does not apply user-defined conversions. It can only cast to interfaces or within the class heirarchy of the supplied type.
User defined conversions are identified at compile time based on the static types involved in the expression. They cannot be applied as runtime conversions, so the following is illegal:
public class SomeType
{
public static implicit operator OtherType(SomeType s)
{
return new OtherType();
}
}
public class OtherType { }
object x = new SomeType();
OtherType y = (OtherType)x; // will fail at runtime
It doesn't matter whether a UDC exists from SomeType to OtherType - it cannot be applied through a reference of type object. Trying to run the above code would fail at runtime, reporting something like:
System.InvalidCastException:
Unable to cast object of type 'SomeType' to type 'OtherType'
Cast<>() can only perform representation preserving conversions ... that's why you can't use it to apply user-defined conversions.
Eric Lippert has a great article about the behavior of the cast operator in C# - always a worthwhile read.