views:

64

answers:

2

Hi, this is my first WCF service. I defined a response message that derives from a Dictionary like this:

[CollectionDataContract(ItemName = "Product", KeyName = "ProductNumber", ValueName = "ProductName")]
public class GetAvailableProductsResponse : Dictionary<string, string> { }

When I try to run the following code in a service operation it throws an exception for not being able to cast:

Dictionary<string, string> result = new Dictionary<string, string>();
GetAvailableProductsResponse responseMsg = (GetAvailableProductsResponse)result;

In reality I don't instantiate a new Dictionary but I'm calling a business object which returns a Dictionary so I need to cast this to the response message somehow.

This might be an issue of casting a Dictionary in general rather than a WCF specific question, isn't it?

Many thanks in advance!

+1  A: 

It's an issue of casting in general - you can't cast a reference to a type which isn't actually in the hierarchy of the real object.

You'll need to build a real instance of GetAvailableProductsResponse if you want to be able to cast to it.

Jon Skeet
Right, I ignored the basic rule that you can cast an object to it's base types but not to it's derived types. Thank you, too!
mono68
+1  A: 

You can not cast an instance of the base class object to derived type, if it is not an instance of the derived. You can put the dictionary on the response as a property:

public class GetAvailableProductsResponse
{
public Dictionary<string, string> Products { get; set; }
}

and

Dictionary<string, string> result = new Dictionary<string, string>();
GetAvailableProductsResponse responseMsg = new GetAvailableProductsResponse { Products = result; }

EDIT: if you prefer to keep the inheritance you have to specify a constructor for the class:

public class GetAvailableProductsResponse : Dictinary<string, string>
{
public GetAvailableProductsResponse(Dictionary<string, string> d) : base(d) {}
}

GetAvailableProductsResponse responseMsg = new GetAvailableProductsResponse(result);
onof
Thanks, like this it works and actually this was my first intention but the reason for my other approach was that I wanted to take advantage of the CollectionDataContractAttribute members ItemName, KeyName and ValueName.I wonder why there exists no CollectionDataMemberAttribute with such members.But anyway I'm using your approach with the Dictionary as the member now. Thanks, again!
mono68
I didn't realize. I edited my answer, with a constructor you can achieve your purpose
onof