Is it possible to use Serializer.Deserialize() within the class being created?

I want to clean up the creation of a class using the Serializer.Deserialize() call.  Currently I have the lines that are provided on the MSDN site:
XmlSerializer serializer = new XmlSerializer(typeof(OrderedItem), "http://www.cpandl.com");
FileStream fs = new FileStream(filename, FileMode.Open);
OrderedItem i;
i = (OrderedItem) serializer.Deserialize(fs);
Is there any way to place this code inside of the OrderedItem class, maybe in the constructor   And to this constructor I would pass the filename string.

Any ideas on how to hide this code within OrderedItem
Thanks,
Nate


Answer this question

Is it possible to use Serializer.Deserialize() within the class being created?

  • chrouble

    That seems to do the trick. Thanks.

  • Mapper

    You can create a static method on OrderedItem, that does the serialization and returns an object for you

    Something like:

    public static OrderedItem Create( string Filename )
    {
    XmlSerializer serializer = new XmlSerializer(typeof(OrderedItem), "http://www.cpandl.com");
    using( FileStream fs = new FileStream(filename, FileMode.Open) )
    return (OrderedItem) serializer.Deserialize(fs);
    }


    and then

    OrderedItem item = OrderedItem.Create( someFilename );

    --VV [MS]
    vascov@microsoft.com


  • Is it possible to use Serializer.Deserialize() within the class being created?