Force deserialization with invalid data.

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
 
M

Marc Gravell

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
 
C

Chris Dunaway

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
 

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