Explicit/implicit cast operator fails when using LINQ’s .Cast() operator

When you define explicit/implicit cast operators, they are bound at call-sites at compile-time. That’s why the first line works: the compiler can work out all the type information needed, and so it can substitute your custom explicit cast operator for the default one.

However, since the Cast<T> just performs a generic cast, the compiler doesn’t know about your operator, and thus it is ignored. Result: invalid cast exception.

You can get around this by instead performing a .Select(x => (DatabaseInfo)x). Alternatively, you could add on a method called ToDatabaseInfo(), so that you’re not hiding what’s actually going on.

Leave a Comment