Author Topic: [C#] XML Serialize/Deserialize - Stream Extension Class  (Read 1739 times)

0 Members and 1 Guest are viewing this topic.

Offline xor

  • Peasant
  • *
  • Posts: 59
  • Cookies: 32
    • View Profile
[C#] XML Serialize/Deserialize - Stream Extension Class
« on: May 19, 2015, 02:12:42 am »
Code: [Select]
    public static class XmlSerializerExtensions
    {
        public static T LoadFromXml<T>(this Stream stream)
        {
            var type = typeof(T);
            var serializer = new XmlSerializer(type);
            return (T)serializer.Deserialize(stream);
        }


        public static void SaveToXml<T>(this Stream stream, T obj)
        {
            var type = typeof (T);
            var serializer = new XmlSerializer(type);
            serializer.Serialize(stream, obj);
        }
    }
« Last Edit: May 19, 2015, 02:13:02 am by xor »

Offline Xires

  • Noob Eater
  • Administrator
  • Knight
  • *
  • Posts: 379
  • Cookies: 149
    • View Profile
    • Feed The Trolls - Xires
Re: [C#] XML Serialize/Deserialize - Stream Extension Class
« Reply #1 on: May 21, 2015, 12:09:05 pm »
I think I would overload SaveToXml() to serialize to a string and return that string.  Has more cookies.
-Xires

Offline ArkPhaze

  • Peasant
  • *
  • Posts: 136
  • Cookies: 20
  • null terminated
    • View Profile
Re: [C#] XML Serialize/Deserialize - Stream Extension Class
« Reply #2 on: May 23, 2015, 03:05:20 am »
There's absolutely no safety behind these functions to check if the data is even serializable or not. You're missing out on a lot of useful functionality.
sig=: ArkPhaze

[ J/ASM/.NET/C/C++ - Software Engineer ]

Offline xor

  • Peasant
  • *
  • Posts: 59
  • Cookies: 32
    • View Profile
Re: [C#] XML Serialize/Deserialize - Stream Extension Class
« Reply #3 on: May 27, 2015, 06:52:53 pm »
You're right ArkPhaze. Exception handling is to be done by the caller.
As for overloads, that's user preference.


This function builds upon Streams as a means of quickly reading / writing to File Systems, Memory, Network. It's by no means designed for production systems, though I don't see the inherent safety issues? So any enlightenment would be nice.


-- xor

Offline ArkPhaze

  • Peasant
  • *
  • Posts: 136
  • Cookies: 20
  • null terminated
    • View Profile
Re: [C#] XML Serialize/Deserialize - Stream Extension Class
« Reply #4 on: May 31, 2015, 01:05:06 am »
I'm talking about taking on a similar TryParse() paradigm, and these 2 methods:
https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.candeserialize%28v=vs.110%29.aspx
https://msdn.microsoft.com/en-us/library/system.type.isserializable%28v=vs.110%29.aspx

These should probably not be done on the caller side for best design.
« Last Edit: May 31, 2015, 01:17:25 am by ArkPhaze »
sig=: ArkPhaze

[ J/ASM/.NET/C/C++ - Software Engineer ]