Cat Zimmermann
Cat Zimmermann

Reputation: 1420

TypeConverter for serialization

Is it normal practice to use a TypeConverter for serialization? There is a class that I do not own that has a "lossy" TypeConverter. When converting to a string, it formats its floating point data with "G4", so that when this type is displayed in a PropertyGrid, it's easily readable.

I would like to also use this TypeConverter to convert from a string, creating an instance of this class. Right now I'm checking the CultureInfo passed to TypeConverter.ConvertTo and only using the pretty, lossy conversion if the CultureInfo is not InvariantCulture.

I'd like to know if I'm going about this the wrong way.

Upvotes: 0

Views: 799

Answers (2)

Hans Passant
Hans Passant

Reputation: 942328

Well, it isn't normal practice. You'd want some kind of control over how the object gets serialized so that it doesn't trip you up with details that are only relevant to a PropertyGrid. That's not usually hard to do:

class VendorSerialized {
    public VendorSerialized(VendorType obj) {
        // Set properties
        //...
    }
    public VendorType AfterSerialization() {
        var obj = new VendorType();
        // Set the vendor object properties from deserialized data
        //...
        return obj;
    }
    // Properties here...
    //...
}

Problem solved :)

Upvotes: 1

bbudge
bbudge

Reputation: 1137

If you are serializing data into a file or other interchange format to be shared between users in different cultures, using anything but InvariantCulture won't work.

TypeConverter can be used in simple serialization scenarios, when all needed types are known to have an appropriate TypeConverter.

Upvotes: 1

Related Questions