KeyedCollection serialization with SoapFormatter

W

Wiebe Tijsma

Hi,

I'm trying to serialize a KeyedCollection with the SoapFormatter,
however I'm getting the exception:

System.Runtime.Serialization.SerializationException: Soap Serializer
does not support serializing Generic Types :
System.Collections.Generic.GenericEqualityComparer`1[System.String]

I didn't expose any generic types however, so it's internal to the Keyed
Collection. Any alternatives or workarounds to this?

my test case:

[TestFixture()]
public class SoapTests
{
[Test]
public void TestKeyedCollectionSoapSerialization()
{
TestKeyedCollection collection = new TestKeyedCollection();
collection.Add(new TestItem("Test"));
using (FileStream stream = File.OpenWrite("test.soap"))
{
SoapFormatter formatter = new SoapFormatter();
formatter.Serialize(stream, collection);
}
}
}

[Serializable()]
public class TestKeyedCollection : KeyedCollection<string,TestItem>
{
protected override string GetKeyForItem(TestItem item)
{
return item.Name;
}
}

[Serializable()]
public class TestItem
{
string _name;

public TestItem(string name)
{
_name = name;
}

public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
}

Best Regards,

Wiebe Tijsma
 
D

Dave Sexton

Hi,

The work around is to use a base class that isn't generic, but since there
isn't a non-generic KeyedCollection implementation, AFAIK, you'll have to
create your own using Hashtable.
 
W

Wiebe Tijsma

Hi Dave,

Thanks, but I thought it wasn't a problem to inherit from a generic
class, as long as it doesn't expose any generic parameters/fields.

Best Regards,

Wiebe Tijsma
 
D

Dave Sexton

Hi Wiebe,

A generic type may be serialized as long as its generic parameters are
serializable as well:

".NET Development (General) Technical Articles, Generics FAQ: Best Practices
§ How Do I Serialize Generic Types?"
http://msdn2.microsoft.com/en-us/library/aa479858.aspx#bestpractices_topic7

But as the error you encountered states, the SoapFormatter doesn't support
serialization of generic types:

"Issues When Using Microsoft Visual Studio 2005
§ 2.36 Using generic types with .NET Remoting and SOAP Serialization"
http://msdn2.microsoft.com/en-us/vstudio/aa718685.aspx

There are no workarounds offered by the article I've cited above.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top