object into an XML string

Microsoft added the ability to create a static method in a static class that behaves like it’s a member of the class that it is called on. This has some interesting ramifications including that you can call an extension method off of a null reference

So let’s say you want to create an extension method that makes it easy to turn any object into an XML string. We could write:

public static class ObjectExtensions
         public static string ToXml(this object input, bool shouldPrettyPrint)
             if (input == null) throw new ArgumentNullException("input");
            var xs = new XmlSerializer(input.GetType());
         using (var memoryStream = new MemoryStream())
          using (var xmlTextWriter = new XmlTextWriter(memoryStream, new UTF8Encoding()))
              xs.Serialize(xmlTextWriter, input);
               return Encoding.UTF8.GetString(memoryStream.ToArray());

Now, we can easily write:

 // can convert primatives to xml
     string intXml = 5.ToXml();
     // can convert complex types to xml
    string objXml = product.ToXml();
    // can even call as static method if you choose:
    objXml = ObjectExtensions.ToXml(products);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s