Overcoming WebServices unsupported serialization of Dictionary/Hashtables (Generic Collections)

27 Oct


In a scenario that you intend to use WebService for retrieving collection (list) of data that is a bundled with related objects (Dictionary or Hashtable).
To make the things even more complex, you want that one of the related objects will be generic.
You are likely to face an error indicating that C# cannot serialize IDictionary related classes.

Returning generic classes is not allowed though.


Very simple. Use non generic class to hold generic classes and all other related classes as members.
This way you hold in one class representative a bundle of classes that are related (similar to the idea of Dictionary, even more extended).
Make that class an array and you have related object collection.
Return this class as the result set.

Review this diagram to get the point:

WebService – Manager – Example code:


/* MyEntities.cs*/
public class ResultSet
	public GenericEntity<MyType>[] myObjectsList;

public class GenericEntity<T>
	public Object internalObject;

/* MyManager.cs */
public ResultSet GetMyObjectsList(){
	ResultSet resultSet = new ResultSet();

	// Use List to store all the entries to return.
	List<GenericEntity<MyType>> ObjectsList = new List<GenericEntity<MyType>>();

	// Create new entry.
	GenericEntity<MyType> newObject = new GenericEntity<MyType>();
	newObject.internalObject = new Object();

	// Add the entry to the resultset.
	resultSet.myObjectsList = ObjectsList.ToArray();

	return resultSet;

/* WebService.asmx */
/// <summary>
/// Summary description for CrossComponentCommunicationProtocol1
/// </summary>
[WebService(Namespace = "http://localhost/WebService.asmx/")]
public class MyWebService : System.Web.Services.WebService

	public ResultSet GetMyResultSet()
		MyManager _myManager = new MyManager();

		// Object to be returned.
		CccpResultSet resultSet = new CccpResultSet();

		resultSet = _myManager.GetMyObjectsList();

		// If nothing returned, throw en error.
		if (resultSet == null) throw new Exception("No pending messages found");

		// return the result.
		return resultSet;


Leave a comment

Posted by on October 27, 2011 in Uncategorized


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: