An example of .NET class extension
May 10th, 2012

One of the most incredible features of C# introduced recently is an ability to extend virtually any class with extra functionality via class extension technique.
This example demonstrates this concept which I find extremely useful in many cases.

Say, you’re developing an application that deals a lot with XML and there’s a frequent need to serialize different kind of objects to XML.

One way would be to have a helper function shared across you code that’ll do the job, right? Something like…

using System.IO;
using System.Xml;
using System.Xml.Serialization;
    public class Helper {
        public static XmlDocument ToXml(object model)
        {
            var retVal = new XmlDocument();
            var ms = new MemoryStream();
            var xs = new XmlSerializer(model.GetType());
            xs.Serialize(ms, model);
            using ( ms )
            {
                ms.Position = 0;
                retVal.Load(ms);
            }
            return retVal;
        }
    }

Then, in order to invoke this you’d write something like this:

...
var model = new Model();// create a new instance of a class Model
var serializedModel = Helper.ToXml(model);// serialize it to XML and save in serializedModel variable
...

Looks pretty solid, huh?
But, just adding a few more characters to the existing code would make it look way more attractive and professional. So, here you are:

using System.IO;
using System.Xml;
using System.Xml.Serialization;
    public static class Helper {
        public static XmlDocument ToXml(this object model)
        {
            var retVal = new XmlDocument();
            var ms = new MemoryStream();
            var xs = new XmlSerializer(model.GetType());
            xs.Serialize(ms, model);
            using ( ms )
            {
                ms.Position = 0;
                retVal.Load(ms);
            }
            return retVal;
        }
    }

Well, as you can see all we did was re-declaring Helper class as static and adding this keyword to the method’s only parameter. What it does, in essence, is we’re now extending .NET native class object with another public method ToXml. Now, your calling code will look much cleaner and readable:

...
var model = new Model();// create a new instance of a class Model
var serializedModel = model.ToXml();// serialize it to XML and save in serializedModel variable
...
No Comments
Leave a Reply
You must be logged in to post a comment.