Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
C# Serialization
Message
From
27/06/2011 16:50:07
 
General information
Forum:
ASP.NET
Category:
Class design
Miscellaneous
Thread ID:
01516342
Message ID:
01516354
Views:
62
>Is there any real benefit to serializing a class versus just the data the class contains?

I don't know, but it certainly is easier serializing the whole class (I assume anyway ... since I haven't done it the other way, of serializing just the data).
[Serializable]
public class MyClass
{
    // put properties and methods here

    // static method to serialize the class
    public static string GetString(MyClass message)
    {
        XmlSerializer x = new XmlSerializer(typeof(MyClass));
        using (StringWriter sw = new StringWriter())
        {
            x.Serialize(sw, message);
            return sw.ToString();
        }
    }

    // static method to de-serialize the class
    public static MyClass GetObject(string xml)
    {
	MyClass message = null;

	try
	{
		StringReader sr = new StringReader(xml);
		XmlSerializer x = new XmlSerializer(typeof(MyClass));
		message = (MyClass)x.Deserialize(sr);
	}
	catch
	{
	}

	return message;
    }
}
Pretty easy, huh?

~~Bonnie
Bonnie Berent DeWitt
NET/C# MVP since 2003

http://geek-goddess-bonnie.blogspot.com
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform