Aaronontheweb
Aaronontheweb

Reputation: 8414

c# implicit cast from dependent assembly throws InvalidCastException

Suppose I have two projects:

Project1

A class library

using System;

namespace Project1
{
    public class Foo
    {
        public Foo(object bar){
            Bar = (Bar)bar;
        }

        public Bar Bar { get;}
    }

    public class Bar{
        public string MyBar {get; set;}
    }
}

Project2

An exe

using System;
using Project1;

namespace Project2
{
    public class BarTrip
    {
        public string MyFoo {get;set;}

        public static implicit operator Bar(BarTrip trip){
            return new Bar{ MyBar = trip.MyFoo };
        }
    }

    public static class Program{
        public static void Main(params string[] args){
            var trip = new BarTrip(){ MyFoo = "Aaron" };
            var foo = new Foo(trip);

            Console.WriteLine(foo.Bar.MyBar);
        }
    }
}

I would expect that when I run my exe that the implicit cast operator I defined inside BarTrip would be invoked once the casting operation inside Foo's constructor is invoked.

Instead I get the following error:

System.InvalidCastException: Unable to cast object of type 'Project2.BarTrip' to type 'Project1.Bar'.
   at Project1.Foo..ctor(Object bar)
   at Project2.Program.Main(String[] args) in D:\TestProjects\Project2\src\Project2\Program.cs:line 18

What's the reason for this error and what could I do to make this scenario workable if Project1 is a blackbox DLL?

Upvotes: 1

Views: 84

Answers (1)

Daniel A. White
Daniel A. White

Reputation: 191048

When this is compiled, there's no type information passed to the context of Foo's constructor, it's just object. So then the implicit cast isn't resolved. The explicit cast fails because there isn't a well defined path.

This seems like the perfect case for an interface defined in your class library.

Upvotes: 5

Related Questions