I am using a WCF service in my project. This service returns a class called “Store”. I created a new local class which inherits from “Store”. My class is called “ExtendedStore”.
My ExtendedStore looks like this:
class ExtendedStore : StoreManagerService.Store
{
public int Id;
....
}
Now I am using the WCF service to cast to my class using the following code:
StoreManagerService.StoreClient client = new StoreManagerService.StoreClient();
ExtendedStore store = (ExtendedStore) client.GetStore(); // bombs here
I am not able to cast the returned Store class from the service to my ExtendedStore class.
I get the below error message:
Unable to cast object of type
‘ConsoleApplication1.StoreManagerService.Store’
to type
‘ConsoleApplication1.ExtendedStore’.
Shouldn’t I be able to cast it? If not, is there a workaround?
You should not inherit from a proxy type returned from WCF. Consider that the type does not belong to you!
You can do some “extension” using the partial class feature of C#, since the proxy classes are generated as partial classes. Instead of creating class
ExtendedStorewith theIdproperty, try:This adds an Id property to the
Storeclass. You can also add methods events, etc. in this manner.The partial class will need to be defined in the same project tha contains the service reference.
Consider a project with root namespace “Project”. You have a service reference named “Commerce” to a web service that returns a “Store” object. That means there is a class named
Project.Commerce.Store:You will create a folder under your project root named “Commerce”. This is so that the namespaces of classes you create there will be “Project.Commerce”. Then create your partial class: