Serialization Hates Me and My Deadline

D

DonJefe

I am getting a strange message from serialization, and I cannot figure
out what I am doing wrong:

I have a class:

[Serializable]
public class Foobar
{
public Foobar () {}

public Func<Foobar, string> NameFunction
{
get;
set;
}

public string LastName { get; set;}
public string FirstName { get; set;}
public string DisplayName
{
get
{
if (NameFunction != null)
return NameFunction.Invoke(this);
else
return String.Format("{0},{1}", LastName, FirstName);
}
}
}

When I try to serialize this class, I get an error message saying
".... cannot be serialized because it does not have a parameterless
constructor". Clearly, class Foobar has a parameterless constructor,
so this cannot be the case. Is there any way to get around this? Is it
not possible to serialize this type of delegate? Is this an impossible
task?


Thanks.
 
M

Marc Gravell

Which serializer are you using? It isn't possible to serialize
delegates with data-centric serializers like XmlSerializer /
DataContractSerializer, although BinaryFormatter might work for
delegates that target objects within the same data graph.

What exactly are you trying to represent? There might be other
approaches...

Marc
 
M

Marc Gravell

I just checked with XmlSerializer, and the message (2 levels down)
was:
{"System.Func`2[ConsoleApplication1.Foobar,System.String] cannot be
serialized because it does not have a parameterless constructor."}

Is this the one you mean? In which case - indeed, delegates aren't
going to serialize with XmlSerializer.

Marc
 
I

Ignacio Machin ( .NET/ C# MVP )

I am getting a strange message from serialization, and I cannot figure
out what I am doing wrong:

I have a class:

[Serializable]
public class Foobar
{
   public Foobar () {}

   public Func<Foobar, string> NameFunction
   {
        get;
        set;
   }

   public string LastName { get; set;}
   public string FirstName { get; set;}
   public string DisplayName
   {
       get
       {
          if (NameFunction != null)
              return NameFunction.Invoke(this);
          else
              return String.Format("{0},{1}", LastName, FirstName);
       }
   }

}

When I try to serialize this class, I get an error message saying
".... cannot be serialized because it does not have a parameterless
constructor". Clearly, class Foobar has a parameterless constructor,
so this cannot be the case. Is there any way to get around this? Is it
not possible to serialize this type of delegate? Is this an impossible
task?

Thanks.

Do a reverse engineer of the code and see how the compiler declare the
class. Of course you will have to remove the [Serialize] attribute
first :)
 

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