C# Extension Method Example

I was telling a friend of mine about extension methods and created this one not much later, so I thought I’d post it, for him and anybody else that it could help.
 
This first snippet of code is a static class that has my extension method called GetElementName defined inside of it.  GetElementName takes two arguments.  The first is defined with “this XElement parentElement”.  The “this” keyword is there to specify the type for which the method is defined (in this case XElement).  The second parameter is defined with “string name” which is the name of the child element I’m looking for.
 

    4     /// <summary>

    5     /// Gets the case-sensitive LocalName of a child element.

    6     /// </summary>

    7     /// <param name="parentElement">XElement object to search through</param>

    8     /// <param name="name">The (case insensitive) LocalName of the child element you are looking for</param>

    9     /// <returns>String containing the LocalName of the XName child elements</returns>

   10     public static class MyCustomExtensions

   11     {

   12         public static string GetChildElementName(this XElement parentElement, string name)

   13         {

   16             var children = from c in parentElement.Elements()

   17                            where c.Name.LocalName.ToLower() == name.ToLower()

   18                            select c.Name;

   19             if (children.Count() > 0)

   20                 { return children.First().LocalName; }

   21             else

   22                 { return String.Empty; }

   23         }

   24     }

 

Now to use the extension method, I can just use the GetChildElementName method like it was always a part of the XElement class as long as I have a reference to the namespace that the MyCustomExtensions class is inside of.  I’ll have intellisense available for me and everything.

   15             File Defined somewhere as test.xml

   16             <Test>

   17                 <Path>http://www.google.com</Path>

   18                 <Path>http://www.bing.com</Path>

   19                 <Path>http://www.yahoo.com</Path>

   20             </Test>

   21             */

   22             XElement myTestElement = XElement.Load("test.xml");

   23 

   24             // Use GetChildElementName() to get the name of "Path" in case I can’t trust what case was used

   25             string name = myTestElement.GetChildElementName("path");

   26             IEnumerable<XElement> children = myTestElement.Elements(name);

Facebooktwittergoogle_plusredditpinterestlinkedinmailFacebooktwittergoogle_plusredditpinterestlinkedinmailby feather

Leave a Reply

Your email address will not be published. Required fields are marked *