views:

201

answers:

3

I want to serialize a class which uses an anonymous function in its implementation. The compiler is generating an inner class to implement the anonymous function. The serializer fails with the error: "MyClass+<>c__DisplayClass2 is inaccessible due to its protection level. Only public types can be processed."

public class MyClass {
    public doIt() {
        int objective = 0;
        return List<int> () { 1 }.Any(i => i == objective);
    }
}

new XmlSerializer(typeof(MyClass)).Serialize(writer, myClass);

How do I serialize this class? Thanks.

A: 

Mark the doIt method with XMLIgnore attribute, if you don't want that serialized down.

Joshua Cauble
XmlIgnore is not valid on methods. And the problem is that the compiler is generating additional methods at compile time that I have no direct control over.
No Name
Sorry about that, in that case you might need to implement custom serialization using the `ISerializable` interface. You could also check out this article. www.codeproject.com/KB/cs/AnonymousSerialization.aspx
Joshua Cauble
Another interface you may have to implement could be `IXmlSerializable `. It will allow you to directly control your xml generation. Requires work but you can then use the xml serializer with your class. Or should be able to based on the documentation.
Joshua Cauble
A: 

I cannot reproduce this exception with C# 3.0 and .NET 3.5 SP1 -- which tool-set are you using?

Note that the XmlSerializer doesn't serialize methods; only values and properties. Are you using another serializer by chance? If so, place the SerializableAttribute on the class definition as follows.

[Serializable]
public class MyClass{ ... }

Here is the code I used to try to reproduce your issue, which is semantically equivalent.

public class MyClass
{
    public bool doIt()
    {
        int objective = 0;
        return new List<int>() { 1 }.Any(i => i == objective);
    }
}

static class Program
{
    static void Main(string[] args)
    {
        new XmlSerializer(typeof(MyClass)).Serialize(new MemoryStream(), new MyClass());        
    }
}
Steve Guidi
Your right, my simplification does end up serializing just fine. I'm sure that my problem is caused by the anonymous function, because the serialization error went away when I removed it. Oh well, I can't reproduce it outside of my program.
No Name
A: 

Hiya

Instead of returning a List, you should make a new class marked serializable and send that.

[Serializable]
class MyList : List<int>
{
}
Antony Koch
Nothing returns a list. And the Serializable attribute is not used by the XmlSerializer.
No Name