user2555092
user2555092

Reputation: 3

Wrong data got back from deserializing an object with custom type cast operator

I have a class designed to perform like an UInt16. So instead of doing: UInt16 myProp, I can use Address myProp, which is more descriptive.

Here's a snippet:

public class Address
{
    public UInt16 address { get; set; }
    private static UInt16 add;
    public static implicit operator UInt16(Address address)
    {
        return add;
    }

    public static implicit operator Address(UInt16 i)
    {
        Address temp = new Address(i);
        return temp;
    }

    public Address(UInt16 value)
    {
        address = value;
        add = value;
    }

    public Address() { }
}

Then I have a property: public Address myAddress { get; set; }

The rest of the code works perfectly.

This class need to be serialized and de-serialized as xml.

After serialization, I have in my xml

<myAddress>
  <address>7</address>
</myAddress>

But after I desterilized the xml file, I cannot get myAddress property back to 7.

Maybe a weird question... any idea?

Upvotes: 0

Views: 112

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502406

Your conversion operator back to UInt16 is broken - it's using the static variable, which will be set by whichever value happens to have been constructed most recently. Did you not think it odd that you were ignoring the value that was being passed into the conversion operator?

It's not clear why you've got the static variable at all, but I strongly suspect you should get rid of it, and your conversion opperator should be:

public static implicit operator UInt16(Address address)
{
    return address.address;
}

You should also rename the property to follow .NET naming conventions... and ideally change the name anyway, as it's weird for an Address type to also have an Address property. It's not really clear what the type is meant to represent anyway, but perhaps Value would at least be slightly better?

Upvotes: 2

Related Questions