views:

61

answers:

1

I have some code that creates an IWebProxy and then casts it to a WebProxy. I ran my program and it worked. Then I inserted a break point and it all of a sudden stopped working and gives me the error: "Unable to cast object of type 'WebProxyWrapperOpaque' to type 'System.Net.WebProxy'."

Another thing is that we use this method in 2 other programs. I ran these programs and there was no issue with the cast.

Why did it change all of a sudden? What happened to break it? I did nothing to the code and now it's permanently broken.

How do I fix this? I have to use the IWebProxy object because it's returned from a method in code that is not my code (otherwise I'd change it), but in the end I need to use a WebProxy.

EDIT: Here's some code...

public IWebProxy ToIWebProxy(string targetAddress)
{
    //Does some proxy validation then returns an IWebProxy
}

somewhere else in the code I do this...

WebProxy myProxy = (WebProxy)(ToWebProxy(myAddress));

even tried this...

IWebProxy myIWebProx = ToWebProxy(myAddress);
WebProxy myProx = (WebProxy)(myIWebProx);

Again, this worked 20 minutes ago.

+1  A: 

You cannot cast WebProxyWrapperOpaque to WebProxy. Only IWebProxy:

internal class WebProxyWrapperOpaque : IAutoWebProxy, IWebProxy
{
    // etc...
}
Hans Passant
It is an IWebProxy. The method is: 'public IWebProxy ToWebProxy(string targetAddress)' The cast is: 'WebProxy myProx = (WebProxy)(ToWebProxy(address)); This all worked until 20 minutes ago. I don't have any clue as to why it now says it's a 'WebProxyWrapperOpaque'
Mike Webb
@Mike, this answer mark would be useful if you explained what you actually discovered. Please follow up.
Hans Passant
@Hans, I marked it, partly because it is the only answer, but also because I never knew that you could not cast these and realized because of this there was a type mismatch that the debugger was not catching and that I needed to take a different approach. So because of that I looked at all of the classes I was using and found that they were using an IWebProxy in the first place and not a WebProxy (duh!). Wound up scrapping all code that used the WebProxy and just used the IWebProxy. Works fine now.
Mike Webb
@Hans, yours is a better answer than one that just fixes my code and allows me to cast these because your post had me looking for alternative methods and now it is more solid than it would have been otherwise.
Mike Webb