Exception "Field in TypedReferences cannot be static or init only"

  • Thread starter Thread starter Wolfgang Portugaller
  • Start date Start date
W

Wolfgang Portugaller

When deserializing a simple object graph using BinaryFormatter I get an
ArgumentException: "Field in TypedReferences cannot be static or init only".
I have digged into that problem and I've found some strange circumstances.



The basic scenario has the following structure:

An OuterType has a readonly field of type MiddleType which has a field of
type InnerType.

Depending on variations of OuterType, MiddleType and InnerType an
ArgumentException ("Field in TypedReferences cannot be static or init only")
is thrown when deserializing an object graph using a BinaryFormatter.

An Exception is thrown when:
OuterType does not implement ISerializable (just tagged with [Serializable])
AND
MiddleType is a ValueType (struct) and does not implement ISerializable AND
InnerType is a ValueType (struct) and does implement ISerializable
(InnerType must not be a System.DateTime; DateTime seems to be treated
different from ordinary ValueTypes)

Fails when deserializing this object graph[Serializable]

public class|struct OuterType
{
private readonly MiddleType field;
// ...
}

[Serializable]
public struct MiddleType
{
private InnerType field;
// ...
}


[Serializable]
public struct InnerType : ISerializable
{
private int i;

public InnerType(SerializationInfo info, StreamingContext context)
{
this.i = info.GetInt32("i");
}

public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("i", this.i);
}

// ...
}


An Exception is not thrown if any of the conditions above is changed (as far
as I have investigated the circumstances).
OuterType implements ISerializable OR
MiddleType is a class OR
MiddleType implements ISerializable OR
InnerType is a class OR
InnerType does not implement ISerializable.

I admit, that I'm a little bit confused! Can anyone tell if I'm doing
something wrong?

Wolfgang
 
Back
Top