Force deserialization with invalid data.

  • Thread starter Thread starter zlf
  • Start date Start date
Z

zlf

I have a class.

[Serializable]
public class A
{
private int id=0;

public int Id
{
get { return id; }
set { if (value < 1) { throw ArgumentException("Id cannot be less
than 1."); } id = value; }
}
}

And an instance A a = new A().
If I serialize this instance, then deserialize it back, I will get an
exception thrown by setter of Id since id is zero. Can u tell me how to make
deserializer to ignore those exceptions and finish the deserialization?
Thanks
 
Can u tell me how to make deserializer to ignore those exceptions and finish the deserialization

Under XmlSerlializer? Trick.
One option here is to switch the the DataContractSerializer in .NET
3.0, and mark your entity as [DataContract] rather than
[Serializable]; In WCF you can specify [DataMember] against both
fields and properties, allowing you (via field usage) to bypass the
property setter. If you need to keep the case intact, then
[DataMember(Name="Id")] will continue to serialize it as Id (rather
than id).

Perhaps.

Marc
 
I have a class.

[Serializable]
public class A
{
private int id=0;

public int Id
{
get { return id; }
set { if (value < 1) { throw ArgumentException("Id cannot be less
than 1."); } id = value; }
}

}

And an instance A a = new A().
If I serialize this instance, then deserialize it back, I will get an
exception thrown by setter of Id since id is zero. Can u tell me how to make
deserializer to ignore those exceptions and finish the deserialization?
Thanks

Why do you initialize your private field to an invalid value to start
with? If 0 is not a valid value for Id, why do you initialize it to
that in the first place?

Chris
 
Back
Top