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
.
|
|
Then when trying to access an object of type root
, we can see the new method ToHtml
showing as an extension.