Serialization - bug in framework.

G

Guest

I know you should be careful before blaming internal frameworks,
but this definitely does look like an internal bug.

When serializing a ChildClass that inherits a BaseClass containing
a struct that contains an object (phew..) the serialization fails.
Error message: "FieldInfo does not match the target Type"

I can serialize the struct, serialize the baseclass (containing the struct),
serialize the childclass when its empty, but _not_ when it contains the
struct.

Paste the following code in a new console application:

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace SharpSerializeBug
{
class MyClass
{
[Serializable]
public class BaseClass
{
public ContainedStruct Contained;
}

[Serializable]
public class ChildClass : BaseClass{}

[Serializable]
public struct ContainedStruct
{
int[] SomeObject;

public ContainedStruct(int[] anArray)
{
this.SomeObject = anArray;
}
}

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
BaseClass bs = new BaseClass();
ChildClass cs = new ChildClass();
ContainedStruct contained = new ContainedStruct(new int[] {1,2,3});

TrySerialize("Empty Base Class", bs);
TrySerialize("Empty Child Class", cs);
TrySerialize("Contained struct", contained);

bs.Contained = contained;
cs.Contained = contained;

TrySerialize("Non-Empty Base Class", bs);
TrySerialize("Non-Empty Child Class", cs);

Console.ReadLine();
}

static public void TrySerialize(string message, object o)
{
try
{
IFormatter formatter = new BinaryFormatter();
// Serialize qr
Stream stream = new FileStream("MyFile.bin", FileMode.Create,
FileAccess.Write, FileShare.None);
formatter.Serialize(stream, o);
stream.Close();

// Deserialize qr
stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read,
FileShare.Read);
object obj = formatter.Deserialize(stream);
stream.Close();

Console.WriteLine("Serialization of " + message + " succeeded.");
}
catch(Exception exp)
{
Console.WriteLine("Serialization of " + message + " failed: " +
exp.Message);
}
}
}

}
 
C

Chris

Just a random thought: Doesn't the object to serialized have to have
a default parameterless constructor? I ran into issues when
serializing and that was the problem although I was not getting the
same error message you are getting.
 

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