User2012384
User2012384

Reputation: 4919

Create a method for a specific type

Below are two lines of code:

XmlDocument xmlDoc = new XmlDocument(filePath);
string k = xmlDoc.XmlToString();

What I want to do is:

Originally, there's no "XmlToString" method under the XmlDocument class, how can I create a method like this?

Upvotes: 0

Views: 66

Answers (1)

wdavo
wdavo

Reputation: 5110

What you are referring to are extensions methods and you can create your own by creating a new static class to contain the method, then writing a new static method using the "this' modifier and your type (XmlDocument) as the first parameter. E.G:

public static class MyExtensionMethods
{
  public static string XmlToString(this XmlDocument doc)
  {
    return "....";
}

}

Usage:

static void Main(string[] args)
{
  XmlDocument doc = new XmlDocument();
  doc.XmlToString();
}

Upvotes: 5

Related Questions