JL.
JL.

Reputation: 81342

Dynamic Type Conversion

I have the following method

public static void SerializeToXMLFile(Object obj,Type type, string fileName)
{
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

    ns.Add("", "");

    XmlSerializer serializer = new XmlSerializer(type);
    TextWriter tw = new StreamWriter(fileName);

    serializer.Serialize(tw, obj, ns);
    tw.Close();
}

The problem is that notice in the line of code that obj will be serialized as an object.

serializer.Serialize(tw, obj, ns);

What I would prefer is that it is serlized as its relevant type for example:

serializer.Serialize(tw, (type) obj, ns);

How is this done? To get the type conversion to work from a dynamic variable?

Upvotes: 1

Views: 1115

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503120

No, it will be serialized as the appropriate type.

The Serialize method has a parameter type of object, so even if you could make this cast, it wouldn't do any good. It's not like it's a generic method which could use the compile-time type.

If you believe the relevant data isn't being persisted, please post a short but complete example to show this. It should work fine.

Upvotes: 2

Related Questions