Thursday, 21 August 2008

Playing with Extension Methods

I've had a issue with option Xml such as in our configuration stores. Basically I wanted to grab data from an XAttribute (see System.Xml.Linq) but wanted to avoid having to constantly check for null nodes. To ease the pain I wrote the following:

 

public static class Extensions {
/// <summary>
/// The extension method allows you to grab data from an XAttribute of if its null, supply a default
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="node">The node.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
public static T ValueOrDefault<T>(this XAttribute node, T defaultValue) where T : IConvertible {
if (node == null) {
return defaultValue;
}
return (T)Convert.ChangeType(node.Value, typeof(T));
}
}



now I can write




var results = from element in doc.Descendants("SomeTag").Where(e => e != null)
select new {
Prop1 = element.Attribute("attribute1").ValueOrDefault(String.Empty),
Prop2 = element.Attribute("attribute1").ValueOrDefault(String.Empty),
};



instead of




var results = from element in doc.Descendants("SomeTag").Where(e => e != null)
select new {
Prop1 = element.Attribute("attribute1") != null ? element.Attribute("attribute1").Value : String.Empty,
Prop2 = element.Attribute("attribute2") != null ? element.Attribute("attribute2").Value : String.Empty,
};



Or some multi line version of it. Its was just as easy to create one for XElement.

2 comments:

Richard OD said...

Preet,

Interesting technique. Personally I'd just use the null coalescing operator (??) instead.

Oh, BTW- I've also start blogging!

preet sangha said...

Hey Richard - nice to hear from you. I wanted cleaner syntax than what I had earlier. Could you post an example please? My version using ?? was ugly looking and much harder to read than the above example.