DotNet ExtensionClass

Dot Net Extension methods

In my previous post DotNet XSD.exe generation tool , we have seen how to generate code from XSD schemas. But most of the time we need to extend the classes generated with some specific functionalities. To prevent those enrichment to disappear the next time the schema is updated and the relative code generated again, we can use .Net Extension methods.

Extension methods

Basically, we are adding a method to a class without access to the class. We can use this to enrich existing .Net classes, like adding a new method to the String class.

In my case, I want to add a method to generate some html from the xml class that was created.

In my code, I have a file sample.cs with a class root in namespace appns.xml. To add a new method, I will create a new file sample-extensions.cs with the same namespace appns.xml.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
namespace appns.xml
{
   // Create a static class to host our extensions methods.
   public static class sample_extensions
   {
       // Create static method, the key is to use 'this' and the type we need to extend (root)
       public static string ToHtml(this root r)
       {
           return "<div>...</div>";
       }
   }
}

Then when trying to access an object of type root, we can see the new method ToHtml showing as an extension. Extension Method Access

References

Microsoft Reference