Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to cast object of type MyObject to type MyObject

I have this scenario where a webservice method I'm consuming in C# returns a Business object, when calling the webservice method with the following code I get the exception "Unable to cast object of type ContactInfo to type ContactInfo" in the reference.cs class of the web reference

Code:

ContactInfo contactInfo = new ContactInfo();
Contact contact = new Contact();

contactInfo = contact.Load(this.ContactID.Value);

Any help would be much appreciated.

like image 524
Robert W Avatar asked Sep 17 '09 15:09

Robert W


1 Answers

This is because one of the ContactInfo objects is a web service proxy, and is in a different namespace.

It's a known problem with asmx-style web services. In the past I've implemented automatic shallow-copy to work around it (here's how, although if I were doing it again I'd probably look at AutoMapper instead).

For example, if you have an assembly with the following class:

MyProject.ContactInfo

and you return an instance of it from a web method:

public class DoSomethingService : System.Web.Services.WebService
{
    public MyProject.ContactInfo GetContactInfo(int id)
    {
        // Code here...
    }
}

Then when you add the web reference to your client project, you actually get this:

MyClientProject.DoSomethingService.ContactInfo

This means that if, in your client application, you call the web service to get a ContactInfo, you have this situation:

namespace MyClientProject
{
    public class MyClientClass
    {
        public void AskWebServiceForContactInfo()
        {
            using (var service = new DoSomethingService())
            {
                MyClientProject.DoSomethingService.ContactInfo contactInfo = service.GetContactInfo(1);

                // ERROR: You can't cast this:
                MyProject.ContactInfo localContactInfo = contactInfo;
            }
        }
    }
}

It's on that last line that I use my ShallowCopy class:

namespace MyClientProject
{
    public class MyClientClass
    {
        public void AskWebServiceForContactInfo()
        {
            using (var service = new DoSomethingService())
            {
                MyClientProject.DoSomethingService.ContactInfo contactInfo = service.GetContactInfo(1);

                // We actually get a new object here, of the correct namespace
                MyProject.ContactInfo localContactInfo = ShallowCopy.Copy<MyClientProject.DoSomethingService.ContactInfo, MyProject.ContactInfo>(contactInfo);
            }
        }
    }
}

NOTE
This only works because the proxy class and the "real" class have exactly the same properties (one is generated from the other by Visual Studio).

like image 52
Neil Barnwell Avatar answered Oct 18 '22 04:10

Neil Barnwell